Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 1
// These are filled with ranges (rangeFrom[i] up to but not including
2
// rangeTo[i]) of code points that count as extending characters.
3
let rangeFrom = [], rangeTo = []
4
 
5
;(() => {
6
  // Compressed representation of the Grapheme_Cluster_Break=Extend
7
  // information from
8
  // http://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
9
  // Each pair of elements represents a range, as an offet from the
10
  // previous range and a length. Numbers are in base-36, with the empty
11
  // string being a shorthand for 1.
12
  let numbers = "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);
13
  for (let i = 0, n = 0; i < numbers.length; i++)
14
    (i % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i]);
15
})();
16
 
17
function isExtendingChar(code) {
18
  if (code < 768) return false
19
  for (let from = 0, to = rangeFrom.length;;) {
20
    let mid = (from + to) >> 1;
21
    if (code < rangeFrom[mid]) to = mid;
22
    else if (code >= rangeTo[mid]) from = mid + 1;
23
    else return true
24
    if (from == to) return false
25
  }
26
}
27
 
28
function isRegionalIndicator(code) {
29
  return code >= 0x1F1E6 && code <= 0x1F1FF
30
}
31
 
32
const ZWJ = 0x200d;
33
 
34
function findClusterBreak$1(str, pos, forward = true, includeExtending = true) {
35
  return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending)
36
}
37
 
38
function nextClusterBreak(str, pos, includeExtending) {
39
  if (pos == str.length) return pos
40
  // If pos is in the middle of a surrogate pair, move to its start
41
  if (pos && surrogateLow$1(str.charCodeAt(pos)) && surrogateHigh$1(str.charCodeAt(pos - 1))) pos--;
42
  let prev = codePointAt$1(str, pos);
43
  pos += codePointSize$1(prev);
44
  while (pos < str.length) {
45
    let next = codePointAt$1(str, pos);
46
    if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
47
      pos += codePointSize$1(next);
48
      prev = next;
49
    } else if (isRegionalIndicator(next)) {
50
      let countBefore = 0, i = pos - 2;
51
      while (i >= 0 && isRegionalIndicator(codePointAt$1(str, i))) { countBefore++; i -= 2; }
52
      if (countBefore % 2 == 0) break
53
      else pos += 2;
54
    } else {
55
      break
56
    }
57
  }
58
  return pos
59
}
60
 
61
function prevClusterBreak(str, pos, includeExtending) {
62
  while (pos > 0) {
63
    let found = nextClusterBreak(str, pos - 2, includeExtending);
64
    if (found < pos) return found
65
    pos--;
66
  }
67
  return 0
68
}
69
 
70
function codePointAt$1(str, pos) {
71
  let code0 = str.charCodeAt(pos);
72
  if (!surrogateHigh$1(code0) || pos + 1 == str.length) return code0
73
  let code1 = str.charCodeAt(pos + 1);
74
  if (!surrogateLow$1(code1)) return code0
75
  return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000
76
}
77
 
78
function surrogateLow$1(ch) { return ch >= 0xDC00 && ch < 0xE000 }
79
function surrogateHigh$1(ch) { return ch >= 0xD800 && ch < 0xDC00 }
80
function codePointSize$1(code) { return code < 0x10000 ? 1 : 2 }
81
 
1 efrain 82
/**
83
The data structure for documents. @nonabstract
84
*/
85
class Text {
86
    /**
87
    Get the line description around the given position.
88
    */
89
    lineAt(pos) {
90
        if (pos < 0 || pos > this.length)
91
            throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
92
        return this.lineInner(pos, false, 1, 0);
93
    }
94
    /**
95
    Get the description for the given (1-based) line number.
96
    */
97
    line(n) {
98
        if (n < 1 || n > this.lines)
99
            throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
100
        return this.lineInner(n, true, 1, 0);
101
    }
102
    /**
103
    Replace a range of the text with the given content.
104
    */
105
    replace(from, to, text) {
106
        [from, to] = clip(this, from, to);
107
        let parts = [];
108
        this.decompose(0, from, parts, 2 /* Open.To */);
109
        if (text.length)
110
            text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);
111
        this.decompose(to, this.length, parts, 1 /* Open.From */);
112
        return TextNode.from(parts, this.length - (to - from) + text.length);
113
    }
114
    /**
115
    Append another document to this one.
116
    */
117
    append(other) {
118
        return this.replace(this.length, this.length, other);
119
    }
120
    /**
121
    Retrieve the text between the given points.
122
    */
123
    slice(from, to = this.length) {
124
        [from, to] = clip(this, from, to);
125
        let parts = [];
126
        this.decompose(from, to, parts, 0);
127
        return TextNode.from(parts, to - from);
128
    }
129
    /**
130
    Test whether this text is equal to another instance.
131
    */
132
    eq(other) {
133
        if (other == this)
134
            return true;
135
        if (other.length != this.length || other.lines != this.lines)
136
            return false;
137
        let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
138
        let a = new RawTextCursor(this), b = new RawTextCursor(other);
139
        for (let skip = start, pos = start;;) {
140
            a.next(skip);
141
            b.next(skip);
142
            skip = 0;
143
            if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
144
                return false;
145
            pos += a.value.length;
146
            if (a.done || pos >= end)
147
                return true;
148
        }
149
    }
150
    /**
151
    Iterate over the text. When `dir` is `-1`, iteration happens
152
    from end to start. This will return lines and the breaks between
153
    them as separate strings.
154
    */
155
    iter(dir = 1) { return new RawTextCursor(this, dir); }
156
    /**
157
    Iterate over a range of the text. When `from` > `to`, the
158
    iterator will run in reverse.
159
    */
160
    iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
161
    /**
162
    Return a cursor that iterates over the given range of lines,
163
    _without_ returning the line breaks between, and yielding empty
164
    strings for empty lines.
165
 
166
    When `from` and `to` are given, they should be 1-based line numbers.
167
    */
168
    iterLines(from, to) {
169
        let inner;
170
        if (from == null) {
171
            inner = this.iter();
172
        }
173
        else {
174
            if (to == null)
175
                to = this.lines + 1;
176
            let start = this.line(from).from;
177
            inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
178
        }
179
        return new LineCursor(inner);
180
    }
181
    /**
182
    Return the document as a string, using newline characters to
183
    separate lines.
184
    */
185
    toString() { return this.sliceString(0); }
186
    /**
187
    Convert the document to an array of lines (which can be
188
    deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
189
    */
190
    toJSON() {
191
        let lines = [];
192
        this.flatten(lines);
193
        return lines;
194
    }
195
    /**
196
    @internal
197
    */
198
    constructor() { }
199
    /**
200
    Create a `Text` instance for the given array of lines.
201
    */
202
    static of(text) {
203
        if (text.length == 0)
204
            throw new RangeError("A document must have at least one line");
205
        if (text.length == 1 && !text[0])
206
            return Text.empty;
207
        return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
208
    }
209
}
210
// Leaves store an array of line strings. There are always line breaks
211
// between these strings. Leaves are limited in size and have to be
212
// contained in TextNode instances for bigger documents.
213
class TextLeaf extends Text {
214
    constructor(text, length = textLength(text)) {
215
        super();
216
        this.text = text;
217
        this.length = length;
218
    }
219
    get lines() { return this.text.length; }
220
    get children() { return null; }
221
    lineInner(target, isLine, line, offset) {
222
        for (let i = 0;; i++) {
223
            let string = this.text[i], end = offset + string.length;
224
            if ((isLine ? line : end) >= target)
225
                return new Line(offset, end, line, string);
226
            offset = end + 1;
227
            line++;
228
        }
229
    }
230
    decompose(from, to, target, open) {
231
        let text = from <= 0 && to >= this.length ? this
232
            : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
233
        if (open & 1 /* Open.From */) {
234
            let prev = target.pop();
235
            let joined = appendText(text.text, prev.text.slice(), 0, text.length);
236
            if (joined.length <= 32 /* Tree.Branch */) {
237
                target.push(new TextLeaf(joined, prev.length + text.length));
238
            }
239
            else {
240
                let mid = joined.length >> 1;
241
                target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
242
            }
243
        }
244
        else {
245
            target.push(text);
246
        }
247
    }
248
    replace(from, to, text) {
249
        if (!(text instanceof TextLeaf))
250
            return super.replace(from, to, text);
251
        [from, to] = clip(this, from, to);
252
        let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
253
        let newLen = this.length + text.length - (to - from);
254
        if (lines.length <= 32 /* Tree.Branch */)
255
            return new TextLeaf(lines, newLen);
256
        return TextNode.from(TextLeaf.split(lines, []), newLen);
257
    }
258
    sliceString(from, to = this.length, lineSep = "\n") {
259
        [from, to] = clip(this, from, to);
260
        let result = "";
261
        for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
262
            let line = this.text[i], end = pos + line.length;
263
            if (pos > from && i)
264
                result += lineSep;
265
            if (from < end && to > pos)
266
                result += line.slice(Math.max(0, from - pos), to - pos);
267
            pos = end + 1;
268
        }
269
        return result;
270
    }
271
    flatten(target) {
272
        for (let line of this.text)
273
            target.push(line);
274
    }
275
    scanIdentical() { return 0; }
276
    static split(text, target) {
277
        let part = [], len = -1;
278
        for (let line of text) {
279
            part.push(line);
280
            len += line.length + 1;
281
            if (part.length == 32 /* Tree.Branch */) {
282
                target.push(new TextLeaf(part, len));
283
                part = [];
284
                len = -1;
285
            }
286
        }
287
        if (len > -1)
288
            target.push(new TextLeaf(part, len));
289
        return target;
290
    }
291
}
292
// Nodes provide the tree structure of the `Text` type. They store a
293
// number of other nodes or leaves, taking care to balance themselves
294
// on changes. There are implied line breaks _between_ the children of
295
// a node (but not before the first or after the last child).
296
class TextNode extends Text {
297
    constructor(children, length) {
298
        super();
299
        this.children = children;
300
        this.length = length;
301
        this.lines = 0;
302
        for (let child of children)
303
            this.lines += child.lines;
304
    }
305
    lineInner(target, isLine, line, offset) {
306
        for (let i = 0;; i++) {
307
            let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
308
            if ((isLine ? endLine : end) >= target)
309
                return child.lineInner(target, isLine, line, offset);
310
            offset = end + 1;
311
            line = endLine + 1;
312
        }
313
    }
314
    decompose(from, to, target, open) {
315
        for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
316
            let child = this.children[i], end = pos + child.length;
317
            if (from <= end && to >= pos) {
318
                let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));
319
                if (pos >= from && end <= to && !childOpen)
320
                    target.push(child);
321
                else
322
                    child.decompose(from - pos, to - pos, target, childOpen);
323
            }
324
            pos = end + 1;
325
        }
326
    }
327
    replace(from, to, text) {
328
        [from, to] = clip(this, from, to);
329
        if (text.lines < this.lines)
330
            for (let i = 0, pos = 0; i < this.children.length; i++) {
331
                let child = this.children[i], end = pos + child.length;
332
                // Fast path: if the change only affects one child and the
333
                // child's size remains in the acceptable range, only update
334
                // that child
335
                if (from >= pos && to <= end) {
336
                    let updated = child.replace(from - pos, to - pos, text);
337
                    let totalLines = this.lines - child.lines + updated.lines;
338
                    if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&
339
                        updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {
340
                        let copy = this.children.slice();
341
                        copy[i] = updated;
342
                        return new TextNode(copy, this.length - (to - from) + text.length);
343
                    }
344
                    return super.replace(pos, end, updated);
345
                }
346
                pos = end + 1;
347
            }
348
        return super.replace(from, to, text);
349
    }
350
    sliceString(from, to = this.length, lineSep = "\n") {
351
        [from, to] = clip(this, from, to);
352
        let result = "";
353
        for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
354
            let child = this.children[i], end = pos + child.length;
355
            if (pos > from && i)
356
                result += lineSep;
357
            if (from < end && to > pos)
358
                result += child.sliceString(from - pos, to - pos, lineSep);
359
            pos = end + 1;
360
        }
361
        return result;
362
    }
363
    flatten(target) {
364
        for (let child of this.children)
365
            child.flatten(target);
366
    }
367
    scanIdentical(other, dir) {
368
        if (!(other instanceof TextNode))
369
            return 0;
370
        let length = 0;
371
        let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
372
            : [this.children.length - 1, other.children.length - 1, -1, -1];
373
        for (;; iA += dir, iB += dir) {
374
            if (iA == eA || iB == eB)
375
                return length;
376
            let chA = this.children[iA], chB = other.children[iB];
377
            if (chA != chB)
378
                return length + chA.scanIdentical(chB, dir);
379
            length += chA.length + 1;
380
        }
381
    }
382
    static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
383
        let lines = 0;
384
        for (let ch of children)
385
            lines += ch.lines;
386
        if (lines < 32 /* Tree.Branch */) {
387
            let flat = [];
388
            for (let ch of children)
389
                ch.flatten(flat);
390
            return new TextLeaf(flat, length);
391
        }
392
        let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
393
        let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
394
        function add(child) {
395
            let last;
396
            if (child.lines > maxChunk && child instanceof TextNode) {
397
                for (let node of child.children)
398
                    add(node);
399
            }
400
            else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
401
                flush();
402
                chunked.push(child);
403
            }
404
            else if (child instanceof TextLeaf && currentLines &&
405
                (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
406
                child.lines + last.lines <= 32 /* Tree.Branch */) {
407
                currentLines += child.lines;
408
                currentLen += child.length + 1;
409
                currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
410
            }
411
            else {
412
                if (currentLines + child.lines > chunk)
413
                    flush();
414
                currentLines += child.lines;
415
                currentLen += child.length + 1;
416
                currentChunk.push(child);
417
            }
418
        }
419
        function flush() {
420
            if (currentLines == 0)
421
                return;
422
            chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
423
            currentLen = -1;
424
            currentLines = currentChunk.length = 0;
425
        }
426
        for (let child of children)
427
            add(child);
428
        flush();
429
        return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
430
    }
431
}
432
Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
433
function textLength(text) {
434
    let length = -1;
435
    for (let line of text)
436
        length += line.length + 1;
437
    return length;
438
}
439
function appendText(text, target, from = 0, to = 1e9) {
440
    for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
441
        let line = text[i], end = pos + line.length;
442
        if (end >= from) {
443
            if (end > to)
444
                line = line.slice(0, to - pos);
445
            if (pos < from)
446
                line = line.slice(from - pos);
447
            if (first) {
448
                target[target.length - 1] += line;
449
                first = false;
450
            }
451
            else
452
                target.push(line);
453
        }
454
        pos = end + 1;
455
    }
456
    return target;
457
}
458
function sliceText(text, from, to) {
459
    return appendText(text, [""], from, to);
460
}
461
class RawTextCursor {
462
    constructor(text, dir = 1) {
463
        this.dir = dir;
464
        this.done = false;
465
        this.lineBreak = false;
466
        this.value = "";
467
        this.nodes = [text];
468
        this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
469
    }
470
    nextInner(skip, dir) {
471
        this.done = this.lineBreak = false;
472
        for (;;) {
473
            let last = this.nodes.length - 1;
474
            let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
475
            let size = top instanceof TextLeaf ? top.text.length : top.children.length;
476
            if (offset == (dir > 0 ? size : 0)) {
477
                if (last == 0) {
478
                    this.done = true;
479
                    this.value = "";
480
                    return this;
481
                }
482
                if (dir > 0)
483
                    this.offsets[last - 1]++;
484
                this.nodes.pop();
485
                this.offsets.pop();
486
            }
487
            else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
488
                this.offsets[last] += dir;
489
                if (skip == 0) {
490
                    this.lineBreak = true;
491
                    this.value = "\n";
492
                    return this;
493
                }
494
                skip--;
495
            }
496
            else if (top instanceof TextLeaf) {
497
                // Move to the next string
498
                let next = top.text[offset + (dir < 0 ? -1 : 0)];
499
                this.offsets[last] += dir;
500
                if (next.length > Math.max(0, skip)) {
501
                    this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
502
                    return this;
503
                }
504
                skip -= next.length;
505
            }
506
            else {
507
                let next = top.children[offset + (dir < 0 ? -1 : 0)];
508
                if (skip > next.length) {
509
                    skip -= next.length;
510
                    this.offsets[last] += dir;
511
                }
512
                else {
513
                    if (dir < 0)
514
                        this.offsets[last]--;
515
                    this.nodes.push(next);
516
                    this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
517
                }
518
            }
519
        }
520
    }
521
    next(skip = 0) {
522
        if (skip < 0) {
523
            this.nextInner(-skip, (-this.dir));
524
            skip = this.value.length;
525
        }
526
        return this.nextInner(skip, this.dir);
527
    }
528
}
529
class PartialTextCursor {
530
    constructor(text, start, end) {
531
        this.value = "";
532
        this.done = false;
533
        this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
534
        this.pos = start > end ? text.length : 0;
535
        this.from = Math.min(start, end);
536
        this.to = Math.max(start, end);
537
    }
538
    nextInner(skip, dir) {
539
        if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
540
            this.value = "";
541
            this.done = true;
542
            return this;
543
        }
544
        skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
545
        let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
546
        if (skip > limit)
547
            skip = limit;
548
        limit -= skip;
549
        let { value } = this.cursor.next(skip);
550
        this.pos += (value.length + skip) * dir;
551
        this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
552
        this.done = !this.value;
553
        return this;
554
    }
555
    next(skip = 0) {
556
        if (skip < 0)
557
            skip = Math.max(skip, this.from - this.pos);
558
        else if (skip > 0)
559
            skip = Math.min(skip, this.to - this.pos);
560
        return this.nextInner(skip, this.cursor.dir);
561
    }
562
    get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
563
}
564
class LineCursor {
565
    constructor(inner) {
566
        this.inner = inner;
567
        this.afterBreak = true;
568
        this.value = "";
569
        this.done = false;
570
    }
571
    next(skip = 0) {
572
        let { done, lineBreak, value } = this.inner.next(skip);
573
        if (done && this.afterBreak) {
574
            this.value = "";
575
            this.afterBreak = false;
576
        }
577
        else if (done) {
578
            this.done = true;
579
            this.value = "";
580
        }
581
        else if (lineBreak) {
582
            if (this.afterBreak) {
583
                this.value = "";
584
            }
585
            else {
586
                this.afterBreak = true;
587
                this.next();
588
            }
589
        }
590
        else {
591
            this.value = value;
592
            this.afterBreak = false;
593
        }
594
        return this;
595
    }
596
    get lineBreak() { return false; }
597
}
598
if (typeof Symbol != "undefined") {
599
    Text.prototype[Symbol.iterator] = function () { return this.iter(); };
600
    RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
601
        LineCursor.prototype[Symbol.iterator] = function () { return this; };
602
}
603
/**
604
This type describes a line in the document. It is created
605
on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
606
*/
607
class Line {
608
    /**
609
    @internal
610
    */
611
    constructor(
612
    /**
613
    The position of the start of the line.
614
    */
615
    from,
616
    /**
617
    The position at the end of the line (_before_ the line break,
618
    or at the end of document for the last line).
619
    */
620
    to,
621
    /**
622
    This line's line number (1-based).
623
    */
624
    number,
625
    /**
626
    The line's content.
627
    */
628
    text) {
629
        this.from = from;
630
        this.to = to;
631
        this.number = number;
632
        this.text = text;
633
    }
634
    /**
635
    The length of the line (not including any line break after it).
636
    */
637
    get length() { return this.to - this.from; }
638
}
639
function clip(text, from, to) {
640
    from = Math.max(0, Math.min(text.length, from));
641
    return [from, Math.max(from, Math.min(text.length, to))];
642
}
643
 
644
/**
645
Returns a next grapheme cluster break _after_ (not equal to)
646
`pos`, if `forward` is true, or before otherwise. Returns `pos`
647
itself if no further cluster break is available in the string.
648
Moves across surrogate pairs, extending characters (when
649
`includeExtending` is true), characters joined with zero-width
650
joiners, and flag emoji.
651
*/
652
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
1441 ariadna 653
    return findClusterBreak$1(str, pos, forward, includeExtending);
1 efrain 654
}
655
function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
656
function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
657
/**
658
Find the code point at the given position in a string (like the
659
[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
660
string method).
661
*/
662
function codePointAt(str, pos) {
663
    let code0 = str.charCodeAt(pos);
664
    if (!surrogateHigh(code0) || pos + 1 == str.length)
665
        return code0;
666
    let code1 = str.charCodeAt(pos + 1);
667
    if (!surrogateLow(code1))
668
        return code0;
669
    return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
670
}
671
/**
672
Given a Unicode codepoint, return the JavaScript string that
673
respresents it (like
674
[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
675
*/
676
function fromCodePoint(code) {
677
    if (code <= 0xffff)
678
        return String.fromCharCode(code);
679
    code -= 0x10000;
680
    return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
681
}
682
/**
1441 ariadna 683
The amount of positions a character takes up in a JavaScript string.
1 efrain 684
*/
685
function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
686
 
687
const DefaultSplit = /\r\n?|\n/;
688
/**
689
Distinguishes different ways in which positions can be mapped.
690
*/
691
var MapMode = /*@__PURE__*/(function (MapMode) {
692
    /**
693
    Map a position to a valid new position, even when its context
694
    was deleted.
695
    */
696
    MapMode[MapMode["Simple"] = 0] = "Simple";
697
    /**
698
    Return null if deletion happens across the position.
699
    */
700
    MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
701
    /**
702
    Return null if the character _before_ the position is deleted.
703
    */
704
    MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
705
    /**
706
    Return null if the character _after_ the position is deleted.
707
    */
708
    MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
709
return MapMode})(MapMode || (MapMode = {}));
710
/**
711
A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
712
that doesn't store the inserted text. As such, it can't be
713
applied, but is cheaper to store and manipulate.
714
*/
715
class ChangeDesc {
716
    // Sections are encoded as pairs of integers. The first is the
717
    // length in the current document, and the second is -1 for
718
    // unaffected sections, and the length of the replacement content
719
    // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
720
    // 0), and a replacement two positive numbers.
721
    /**
722
    @internal
723
    */
724
    constructor(
725
    /**
726
    @internal
727
    */
728
    sections) {
729
        this.sections = sections;
730
    }
731
    /**
732
    The length of the document before the change.
733
    */
734
    get length() {
735
        let result = 0;
736
        for (let i = 0; i < this.sections.length; i += 2)
737
            result += this.sections[i];
738
        return result;
739
    }
740
    /**
741
    The length of the document after the change.
742
    */
743
    get newLength() {
744
        let result = 0;
745
        for (let i = 0; i < this.sections.length; i += 2) {
746
            let ins = this.sections[i + 1];
747
            result += ins < 0 ? this.sections[i] : ins;
748
        }
749
        return result;
750
    }
751
    /**
752
    False when there are actual changes in this set.
753
    */
754
    get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
755
    /**
756
    Iterate over the unchanged parts left by these changes. `posA`
757
    provides the position of the range in the old document, `posB`
758
    the new position in the changed document.
759
    */
760
    iterGaps(f) {
761
        for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
762
            let len = this.sections[i++], ins = this.sections[i++];
763
            if (ins < 0) {
764
                f(posA, posB, len);
765
                posB += len;
766
            }
767
            else {
768
                posB += ins;
769
            }
770
            posA += len;
771
        }
772
    }
773
    /**
774
    Iterate over the ranges changed by these changes. (See
775
    [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
776
    variant that also provides you with the inserted text.)
777
    `fromA`/`toA` provides the extent of the change in the starting
778
    document, `fromB`/`toB` the extent of the replacement in the
779
    changed document.
780
 
781
    When `individual` is true, adjacent changes (which are kept
782
    separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
783
    reported separately.
784
    */
785
    iterChangedRanges(f, individual = false) {
786
        iterChanges(this, f, individual);
787
    }
788
    /**
789
    Get a description of the inverted form of these changes.
790
    */
791
    get invertedDesc() {
792
        let sections = [];
793
        for (let i = 0; i < this.sections.length;) {
794
            let len = this.sections[i++], ins = this.sections[i++];
795
            if (ins < 0)
796
                sections.push(len, ins);
797
            else
798
                sections.push(ins, len);
799
        }
800
        return new ChangeDesc(sections);
801
    }
802
    /**
803
    Compute the combined effect of applying another set of changes
804
    after this one. The length of the document after this set should
805
    match the length before `other`.
806
    */
807
    composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
808
    /**
809
    Map this description, which should start with the same document
810
    as `other`, over another set of changes, so that it can be
811
    applied after it. When `before` is true, map as if the changes
1441 ariadna 812
    in `this` happened before the ones in `other`.
1 efrain 813
    */
814
    mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
815
    mapPos(pos, assoc = -1, mode = MapMode.Simple) {
816
        let posA = 0, posB = 0;
817
        for (let i = 0; i < this.sections.length;) {
818
            let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
819
            if (ins < 0) {
820
                if (endA > pos)
821
                    return posB + (pos - posA);
822
                posB += len;
823
            }
824
            else {
825
                if (mode != MapMode.Simple && endA >= pos &&
826
                    (mode == MapMode.TrackDel && posA < pos && endA > pos ||
827
                        mode == MapMode.TrackBefore && posA < pos ||
828
                        mode == MapMode.TrackAfter && endA > pos))
829
                    return null;
830
                if (endA > pos || endA == pos && assoc < 0 && !len)
831
                    return pos == posA || assoc < 0 ? posB : posB + ins;
832
                posB += ins;
833
            }
834
            posA = endA;
835
        }
836
        if (pos > posA)
837
            throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
838
        return posB;
839
    }
840
    /**
841
    Check whether these changes touch a given range. When one of the
842
    changes entirely covers the range, the string `"cover"` is
843
    returned.
844
    */
845
    touchesRange(from, to = from) {
846
        for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
847
            let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
848
            if (ins >= 0 && pos <= to && end >= from)
849
                return pos < from && end > to ? "cover" : true;
850
            pos = end;
851
        }
852
        return false;
853
    }
854
    /**
855
    @internal
856
    */
857
    toString() {
858
        let result = "";
859
        for (let i = 0; i < this.sections.length;) {
860
            let len = this.sections[i++], ins = this.sections[i++];
861
            result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
862
        }
863
        return result;
864
    }
865
    /**
866
    Serialize this change desc to a JSON-representable value.
867
    */
868
    toJSON() { return this.sections; }
869
    /**
870
    Create a change desc from its JSON representation (as produced
871
    by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
872
    */
873
    static fromJSON(json) {
874
        if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
875
            throw new RangeError("Invalid JSON representation of ChangeDesc");
876
        return new ChangeDesc(json);
877
    }
878
    /**
879
    @internal
880
    */
881
    static create(sections) { return new ChangeDesc(sections); }
882
}
883
/**
884
A change set represents a group of modifications to a document. It
885
stores the document length, and can only be applied to documents
886
with exactly that length.
887
*/
888
class ChangeSet extends ChangeDesc {
889
    constructor(sections,
890
    /**
891
    @internal
892
    */
893
    inserted) {
894
        super(sections);
895
        this.inserted = inserted;
896
    }
897
    /**
898
    Apply the changes to a document, returning the modified
899
    document.
900
    */
901
    apply(doc) {
902
        if (this.length != doc.length)
903
            throw new RangeError("Applying change set to a document with the wrong length");
904
        iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
905
        return doc;
906
    }
907
    mapDesc(other, before = false) { return mapSet(this, other, before, true); }
908
    /**
909
    Given the document as it existed _before_ the changes, return a
910
    change set that represents the inverse of this set, which could
911
    be used to go from the document created by the changes back to
912
    the document as it existed before the changes.
913
    */
914
    invert(doc) {
915
        let sections = this.sections.slice(), inserted = [];
916
        for (let i = 0, pos = 0; i < sections.length; i += 2) {
917
            let len = sections[i], ins = sections[i + 1];
918
            if (ins >= 0) {
919
                sections[i] = ins;
920
                sections[i + 1] = len;
921
                let index = i >> 1;
922
                while (inserted.length < index)
923
                    inserted.push(Text.empty);
924
                inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
925
            }
926
            pos += len;
927
        }
928
        return new ChangeSet(sections, inserted);
929
    }
930
    /**
931
    Combine two subsequent change sets into a single set. `other`
932
    must start in the document produced by `this`. If `this` goes
933
    `docA` → `docB` and `other` represents `docB` → `docC`, the
934
    returned value will represent the change `docA` → `docC`.
935
    */
936
    compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
937
    /**
938
    Given another change set starting in the same document, maps this
939
    change set over the other, producing a new change set that can be
940
    applied to the document produced by applying `other`. When
941
    `before` is `true`, order changes as if `this` comes before
942
    `other`, otherwise (the default) treat `other` as coming first.
943
 
944
    Given two changes `A` and `B`, `A.compose(B.map(A))` and
945
    `B.compose(A.map(B, true))` will produce the same document. This
946
    provides a basic form of [operational
947
    transformation](https://en.wikipedia.org/wiki/Operational_transformation),
948
    and can be used for collaborative editing.
949
    */
950
    map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
951
    /**
952
    Iterate over the changed ranges in the document, calling `f` for
953
    each, with the range in the original document (`fromA`-`toA`)
954
    and the range that replaces it in the new document
955
    (`fromB`-`toB`).
956
 
957
    When `individual` is true, adjacent changes are reported
958
    separately.
959
    */
960
    iterChanges(f, individual = false) {
961
        iterChanges(this, f, individual);
962
    }
963
    /**
964
    Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
965
    set.
966
    */
967
    get desc() { return ChangeDesc.create(this.sections); }
968
    /**
969
    @internal
970
    */
971
    filter(ranges) {
972
        let resultSections = [], resultInserted = [], filteredSections = [];
973
        let iter = new SectionIter(this);
974
        done: for (let i = 0, pos = 0;;) {
975
            let next = i == ranges.length ? 1e9 : ranges[i++];
976
            while (pos < next || pos == next && iter.len == 0) {
977
                if (iter.done)
978
                    break done;
979
                let len = Math.min(iter.len, next - pos);
980
                addSection(filteredSections, len, -1);
981
                let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
982
                addSection(resultSections, len, ins);
983
                if (ins > 0)
984
                    addInsert(resultInserted, resultSections, iter.text);
985
                iter.forward(len);
986
                pos += len;
987
            }
988
            let end = ranges[i++];
989
            while (pos < end) {
990
                if (iter.done)
991
                    break done;
992
                let len = Math.min(iter.len, end - pos);
993
                addSection(resultSections, len, -1);
994
                addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
995
                iter.forward(len);
996
                pos += len;
997
            }
998
        }
999
        return { changes: new ChangeSet(resultSections, resultInserted),
1000
            filtered: ChangeDesc.create(filteredSections) };
1001
    }
1002
    /**
1003
    Serialize this change set to a JSON-representable value.
1004
    */
1005
    toJSON() {
1006
        let parts = [];
1007
        for (let i = 0; i < this.sections.length; i += 2) {
1008
            let len = this.sections[i], ins = this.sections[i + 1];
1009
            if (ins < 0)
1010
                parts.push(len);
1011
            else if (ins == 0)
1012
                parts.push([len]);
1013
            else
1014
                parts.push([len].concat(this.inserted[i >> 1].toJSON()));
1015
        }
1016
        return parts;
1017
    }
1018
    /**
1019
    Create a change set for the given changes, for a document of the
1020
    given length, using `lineSep` as line separator.
1021
    */
1022
    static of(changes, length, lineSep) {
1023
        let sections = [], inserted = [], pos = 0;
1024
        let total = null;
1025
        function flush(force = false) {
1026
            if (!force && !sections.length)
1027
                return;
1028
            if (pos < length)
1029
                addSection(sections, length - pos, -1);
1030
            let set = new ChangeSet(sections, inserted);
1031
            total = total ? total.compose(set.map(total)) : set;
1032
            sections = [];
1033
            inserted = [];
1034
            pos = 0;
1035
        }
1036
        function process(spec) {
1037
            if (Array.isArray(spec)) {
1038
                for (let sub of spec)
1039
                    process(sub);
1040
            }
1041
            else if (spec instanceof ChangeSet) {
1042
                if (spec.length != length)
1043
                    throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
1044
                flush();
1045
                total = total ? total.compose(spec.map(total)) : spec;
1046
            }
1047
            else {
1048
                let { from, to = from, insert } = spec;
1049
                if (from > to || from < 0 || to > length)
1050
                    throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
1051
                let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
1052
                let insLen = insText.length;
1053
                if (from == to && insLen == 0)
1054
                    return;
1055
                if (from < pos)
1056
                    flush();
1057
                if (from > pos)
1058
                    addSection(sections, from - pos, -1);
1059
                addSection(sections, to - from, insLen);
1060
                addInsert(inserted, sections, insText);
1061
                pos = to;
1062
            }
1063
        }
1064
        process(changes);
1065
        flush(!total);
1066
        return total;
1067
    }
1068
    /**
1069
    Create an empty changeset of the given length.
1070
    */
1071
    static empty(length) {
1072
        return new ChangeSet(length ? [length, -1] : [], []);
1073
    }
1074
    /**
1075
    Create a changeset from its JSON representation (as produced by
1076
    [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
1077
    */
1078
    static fromJSON(json) {
1079
        if (!Array.isArray(json))
1080
            throw new RangeError("Invalid JSON representation of ChangeSet");
1081
        let sections = [], inserted = [];
1082
        for (let i = 0; i < json.length; i++) {
1083
            let part = json[i];
1084
            if (typeof part == "number") {
1085
                sections.push(part, -1);
1086
            }
1087
            else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
1088
                throw new RangeError("Invalid JSON representation of ChangeSet");
1089
            }
1090
            else if (part.length == 1) {
1091
                sections.push(part[0], 0);
1092
            }
1093
            else {
1094
                while (inserted.length < i)
1095
                    inserted.push(Text.empty);
1096
                inserted[i] = Text.of(part.slice(1));
1097
                sections.push(part[0], inserted[i].length);
1098
            }
1099
        }
1100
        return new ChangeSet(sections, inserted);
1101
    }
1102
    /**
1103
    @internal
1104
    */
1105
    static createSet(sections, inserted) {
1106
        return new ChangeSet(sections, inserted);
1107
    }
1108
}
1109
function addSection(sections, len, ins, forceJoin = false) {
1110
    if (len == 0 && ins <= 0)
1111
        return;
1112
    let last = sections.length - 2;
1113
    if (last >= 0 && ins <= 0 && ins == sections[last + 1])
1114
        sections[last] += len;
1441 ariadna 1115
    else if (last >= 0 && len == 0 && sections[last] == 0)
1 efrain 1116
        sections[last + 1] += ins;
1117
    else if (forceJoin) {
1118
        sections[last] += len;
1119
        sections[last + 1] += ins;
1120
    }
1121
    else
1122
        sections.push(len, ins);
1123
}
1124
function addInsert(values, sections, value) {
1125
    if (value.length == 0)
1126
        return;
1127
    let index = (sections.length - 2) >> 1;
1128
    if (index < values.length) {
1129
        values[values.length - 1] = values[values.length - 1].append(value);
1130
    }
1131
    else {
1132
        while (values.length < index)
1133
            values.push(Text.empty);
1134
        values.push(value);
1135
    }
1136
}
1137
function iterChanges(desc, f, individual) {
1138
    let inserted = desc.inserted;
1139
    for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
1140
        let len = desc.sections[i++], ins = desc.sections[i++];
1141
        if (ins < 0) {
1142
            posA += len;
1143
            posB += len;
1144
        }
1145
        else {
1146
            let endA = posA, endB = posB, text = Text.empty;
1147
            for (;;) {
1148
                endA += len;
1149
                endB += ins;
1150
                if (ins && inserted)
1151
                    text = text.append(inserted[(i - 2) >> 1]);
1152
                if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
1153
                    break;
1154
                len = desc.sections[i++];
1155
                ins = desc.sections[i++];
1156
            }
1157
            f(posA, endA, posB, endB, text);
1158
            posA = endA;
1159
            posB = endB;
1160
        }
1161
    }
1162
}
1163
function mapSet(setA, setB, before, mkSet = false) {
1164
    // Produce a copy of setA that applies to the document after setB
1165
    // has been applied (assuming both start at the same document).
1166
    let sections = [], insert = mkSet ? [] : null;
1167
    let a = new SectionIter(setA), b = new SectionIter(setB);
1168
    // Iterate over both sets in parallel. inserted tracks, for changes
1169
    // in A that have to be processed piece-by-piece, whether their
1170
    // content has been inserted already, and refers to the section
1171
    // index.
1172
    for (let inserted = -1;;) {
1441 ariadna 1173
        if (a.done && b.len || b.done && a.len) {
1174
            throw new Error("Mismatched change set lengths");
1175
        }
1176
        else if (a.ins == -1 && b.ins == -1) {
1 efrain 1177
            // Move across ranges skipped by both sets.
1178
            let len = Math.min(a.len, b.len);
1179
            addSection(sections, len, -1);
1180
            a.forward(len);
1181
            b.forward(len);
1182
        }
1183
        else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
1184
            // If there's a change in B that comes before the next change in
1185
            // A (ordered by start pos, then len, then before flag), skip
1186
            // that (and process any changes in A it covers).
1187
            let len = b.len;
1188
            addSection(sections, b.ins, -1);
1189
            while (len) {
1190
                let piece = Math.min(a.len, len);
1191
                if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
1192
                    addSection(sections, 0, a.ins);
1193
                    if (insert)
1194
                        addInsert(insert, sections, a.text);
1195
                    inserted = a.i;
1196
                }
1197
                a.forward(piece);
1198
                len -= piece;
1199
            }
1200
            b.next();
1201
        }
1202
        else if (a.ins >= 0) {
1203
            // Process the part of a change in A up to the start of the next
1204
            // non-deletion change in B (if overlapping).
1205
            let len = 0, left = a.len;
1206
            while (left) {
1207
                if (b.ins == -1) {
1208
                    let piece = Math.min(left, b.len);
1209
                    len += piece;
1210
                    left -= piece;
1211
                    b.forward(piece);
1212
                }
1213
                else if (b.ins == 0 && b.len < left) {
1214
                    left -= b.len;
1215
                    b.next();
1216
                }
1217
                else {
1218
                    break;
1219
                }
1220
            }
1221
            addSection(sections, len, inserted < a.i ? a.ins : 0);
1222
            if (insert && inserted < a.i)
1223
                addInsert(insert, sections, a.text);
1224
            inserted = a.i;
1225
            a.forward(a.len - left);
1226
        }
1227
        else if (a.done && b.done) {
1228
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1229
        }
1230
        else {
1231
            throw new Error("Mismatched change set lengths");
1232
        }
1233
    }
1234
}
1235
function composeSets(setA, setB, mkSet = false) {
1236
    let sections = [];
1237
    let insert = mkSet ? [] : null;
1238
    let a = new SectionIter(setA), b = new SectionIter(setB);
1239
    for (let open = false;;) {
1240
        if (a.done && b.done) {
1241
            return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1242
        }
1243
        else if (a.ins == 0) { // Deletion in A
1244
            addSection(sections, a.len, 0, open);
1245
            a.next();
1246
        }
1247
        else if (b.len == 0 && !b.done) { // Insertion in B
1248
            addSection(sections, 0, b.ins, open);
1249
            if (insert)
1250
                addInsert(insert, sections, b.text);
1251
            b.next();
1252
        }
1253
        else if (a.done || b.done) {
1254
            throw new Error("Mismatched change set lengths");
1255
        }
1256
        else {
1257
            let len = Math.min(a.len2, b.len), sectionLen = sections.length;
1258
            if (a.ins == -1) {
1259
                let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
1260
                addSection(sections, len, insB, open);
1261
                if (insert && insB)
1262
                    addInsert(insert, sections, b.text);
1263
            }
1264
            else if (b.ins == -1) {
1265
                addSection(sections, a.off ? 0 : a.len, len, open);
1266
                if (insert)
1267
                    addInsert(insert, sections, a.textBit(len));
1268
            }
1269
            else {
1270
                addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
1271
                if (insert && !b.off)
1272
                    addInsert(insert, sections, b.text);
1273
            }
1274
            open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
1275
            a.forward2(len);
1276
            b.forward(len);
1277
        }
1278
    }
1279
}
1280
class SectionIter {
1281
    constructor(set) {
1282
        this.set = set;
1283
        this.i = 0;
1284
        this.next();
1285
    }
1286
    next() {
1287
        let { sections } = this.set;
1288
        if (this.i < sections.length) {
1289
            this.len = sections[this.i++];
1290
            this.ins = sections[this.i++];
1291
        }
1292
        else {
1293
            this.len = 0;
1294
            this.ins = -2;
1295
        }
1296
        this.off = 0;
1297
    }
1298
    get done() { return this.ins == -2; }
1299
    get len2() { return this.ins < 0 ? this.len : this.ins; }
1300
    get text() {
1301
        let { inserted } = this.set, index = (this.i - 2) >> 1;
1302
        return index >= inserted.length ? Text.empty : inserted[index];
1303
    }
1304
    textBit(len) {
1305
        let { inserted } = this.set, index = (this.i - 2) >> 1;
1306
        return index >= inserted.length && !len ? Text.empty
1307
            : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
1308
    }
1309
    forward(len) {
1310
        if (len == this.len)
1311
            this.next();
1312
        else {
1313
            this.len -= len;
1314
            this.off += len;
1315
        }
1316
    }
1317
    forward2(len) {
1318
        if (this.ins == -1)
1319
            this.forward(len);
1320
        else if (len == this.ins)
1321
            this.next();
1322
        else {
1323
            this.ins -= len;
1324
            this.off += len;
1325
        }
1326
    }
1327
}
1328
 
1329
/**
1330
A single selection range. When
1331
[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
1332
is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
1333
multiple ranges. By default, selections hold exactly one range.
1334
*/
1335
class SelectionRange {
1336
    constructor(
1337
    /**
1338
    The lower boundary of the range.
1339
    */
1340
    from,
1341
    /**
1342
    The upper boundary of the range.
1343
    */
1344
    to, flags) {
1345
        this.from = from;
1346
        this.to = to;
1347
        this.flags = flags;
1348
    }
1349
    /**
1350
    The anchor of the range—the side that doesn't move when you
1351
    extend it.
1352
    */
1353
    get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }
1354
    /**
1355
    The head of the range, which is moved when the range is
1356
    [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
1357
    */
1358
    get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }
1359
    /**
1360
    True when `anchor` and `head` are at the same position.
1361
    */
1362
    get empty() { return this.from == this.to; }
1363
    /**
1364
    If this is a cursor that is explicitly associated with the
1365
    character on one of its sides, this returns the side. -1 means
1366
    the character before its position, 1 the character after, and 0
1367
    means no association.
1368
    */
1369
    get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }
1370
    /**
1371
    The bidirectional text level associated with this cursor, if
1372
    any.
1373
    */
1374
    get bidiLevel() {
1375
        let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;
1376
        return level == 7 ? null : level;
1377
    }
1378
    /**
1379
    The goal column (stored vertical offset) associated with a
1380
    cursor. This is used to preserve the vertical position when
1381
    [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
1382
    lines of different length.
1383
    */
1384
    get goalColumn() {
1385
        let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;
1386
        return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;
1387
    }
1388
    /**
1389
    Map this range through a change, producing a valid range in the
1390
    updated document.
1391
    */
1392
    map(change, assoc = -1) {
1393
        let from, to;
1394
        if (this.empty) {
1395
            from = to = change.mapPos(this.from, assoc);
1396
        }
1397
        else {
1398
            from = change.mapPos(this.from, 1);
1399
            to = change.mapPos(this.to, -1);
1400
        }
1401
        return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
1402
    }
1403
    /**
1404
    Extend this range to cover at least `from` to `to`.
1405
    */
1406
    extend(from, to = from) {
1407
        if (from <= this.anchor && to >= this.anchor)
1408
            return EditorSelection.range(from, to);
1409
        let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
1410
        return EditorSelection.range(this.anchor, head);
1411
    }
1412
    /**
1413
    Compare this range to another range.
1414
    */
1415
    eq(other, includeAssoc = false) {
1416
        return this.anchor == other.anchor && this.head == other.head &&
1417
            (!includeAssoc || !this.empty || this.assoc == other.assoc);
1418
    }
1419
    /**
1420
    Return a JSON-serializable object representing the range.
1421
    */
1422
    toJSON() { return { anchor: this.anchor, head: this.head }; }
1423
    /**
1424
    Convert a JSON representation of a range to a `SelectionRange`
1425
    instance.
1426
    */
1427
    static fromJSON(json) {
1428
        if (!json || typeof json.anchor != "number" || typeof json.head != "number")
1429
            throw new RangeError("Invalid JSON representation for SelectionRange");
1430
        return EditorSelection.range(json.anchor, json.head);
1431
    }
1432
    /**
1433
    @internal
1434
    */
1435
    static create(from, to, flags) {
1436
        return new SelectionRange(from, to, flags);
1437
    }
1438
}
1439
/**
1440
An editor selection holds one or more selection ranges.
1441
*/
1442
class EditorSelection {
1443
    constructor(
1444
    /**
1445
    The ranges in the selection, sorted by position. Ranges cannot
1446
    overlap (but they may touch, if they aren't empty).
1447
    */
1448
    ranges,
1449
    /**
1450
    The index of the _main_ range in the selection (which is
1451
    usually the range that was added last).
1452
    */
1453
    mainIndex) {
1454
        this.ranges = ranges;
1455
        this.mainIndex = mainIndex;
1456
    }
1457
    /**
1458
    Map a selection through a change. Used to adjust the selection
1459
    position for changes.
1460
    */
1461
    map(change, assoc = -1) {
1462
        if (change.empty)
1463
            return this;
1464
        return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
1465
    }
1466
    /**
1467
    Compare this selection to another selection. By default, ranges
1468
    are compared only by position. When `includeAssoc` is true,
1469
    cursor ranges must also have the same
1470
    [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
1471
    */
1472
    eq(other, includeAssoc = false) {
1473
        if (this.ranges.length != other.ranges.length ||
1474
            this.mainIndex != other.mainIndex)
1475
            return false;
1476
        for (let i = 0; i < this.ranges.length; i++)
1477
            if (!this.ranges[i].eq(other.ranges[i], includeAssoc))
1478
                return false;
1479
        return true;
1480
    }
1481
    /**
1482
    Get the primary selection range. Usually, you should make sure
1483
    your code applies to _all_ ranges, by using methods like
1484
    [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
1485
    */
1486
    get main() { return this.ranges[this.mainIndex]; }
1487
    /**
1488
    Make sure the selection only has one range. Returns a selection
1489
    holding only the main range from this selection.
1490
    */
1491
    asSingle() {
1492
        return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
1493
    }
1494
    /**
1495
    Extend this selection with an extra range.
1496
    */
1497
    addRange(range, main = true) {
1498
        return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
1499
    }
1500
    /**
1501
    Replace a given range with another range, and then normalize the
1502
    selection to merge and sort ranges if necessary.
1503
    */
1504
    replaceRange(range, which = this.mainIndex) {
1505
        let ranges = this.ranges.slice();
1506
        ranges[which] = range;
1507
        return EditorSelection.create(ranges, this.mainIndex);
1508
    }
1509
    /**
1510
    Convert this selection to an object that can be serialized to
1511
    JSON.
1512
    */
1513
    toJSON() {
1514
        return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
1515
    }
1516
    /**
1517
    Create a selection from a JSON representation.
1518
    */
1519
    static fromJSON(json) {
1520
        if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
1521
            throw new RangeError("Invalid JSON representation for EditorSelection");
1522
        return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
1523
    }
1524
    /**
1525
    Create a selection holding a single range.
1526
    */
1527
    static single(anchor, head = anchor) {
1528
        return new EditorSelection([EditorSelection.range(anchor, head)], 0);
1529
    }
1530
    /**
1531
    Sort and merge the given set of ranges, creating a valid
1532
    selection.
1533
    */
1534
    static create(ranges, mainIndex = 0) {
1535
        if (ranges.length == 0)
1536
            throw new RangeError("A selection needs at least one range");
1537
        for (let pos = 0, i = 0; i < ranges.length; i++) {
1538
            let range = ranges[i];
1539
            if (range.empty ? range.from <= pos : range.from < pos)
1540
                return EditorSelection.normalized(ranges.slice(), mainIndex);
1541
            pos = range.to;
1542
        }
1543
        return new EditorSelection(ranges, mainIndex);
1544
    }
1545
    /**
1546
    Create a cursor selection range at the given position. You can
1547
    safely ignore the optional arguments in most situations.
1548
    */
1549
    static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
1550
        return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |
1551
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |
1552
            ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));
1553
    }
1554
    /**
1555
    Create a selection range.
1556
    */
1557
    static range(anchor, head, goalColumn, bidiLevel) {
1558
        let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |
1559
            (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
1560
        return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)
1561
            : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);
1562
    }
1563
    /**
1564
    @internal
1565
    */
1566
    static normalized(ranges, mainIndex = 0) {
1567
        let main = ranges[mainIndex];
1568
        ranges.sort((a, b) => a.from - b.from);
1569
        mainIndex = ranges.indexOf(main);
1570
        for (let i = 1; i < ranges.length; i++) {
1571
            let range = ranges[i], prev = ranges[i - 1];
1572
            if (range.empty ? range.from <= prev.to : range.from < prev.to) {
1573
                let from = prev.from, to = Math.max(range.to, prev.to);
1574
                if (i <= mainIndex)
1575
                    mainIndex--;
1576
                ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
1577
            }
1578
        }
1579
        return new EditorSelection(ranges, mainIndex);
1580
    }
1581
}
1582
function checkSelection(selection, docLength) {
1583
    for (let range of selection.ranges)
1584
        if (range.to > docLength)
1585
            throw new RangeError("Selection points outside of document");
1586
}
1587
 
1588
let nextID = 0;
1589
/**
1590
A facet is a labeled value that is associated with an editor
1591
state. It takes inputs from any number of extensions, and combines
1592
those into a single output value.
1593
 
1594
Examples of uses of facets are the [tab
1595
size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
1596
attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
1597
listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
1598
 
1599
Note that `Facet` instances can be used anywhere where
1600
[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
1601
*/
1602
class Facet {
1603
    constructor(
1604
    /**
1605
    @internal
1606
    */
1607
    combine,
1608
    /**
1609
    @internal
1610
    */
1611
    compareInput,
1612
    /**
1613
    @internal
1614
    */
1615
    compare, isStatic, enables) {
1616
        this.combine = combine;
1617
        this.compareInput = compareInput;
1618
        this.compare = compare;
1619
        this.isStatic = isStatic;
1620
        /**
1621
        @internal
1622
        */
1623
        this.id = nextID++;
1624
        this.default = combine([]);
1625
        this.extensions = typeof enables == "function" ? enables(this) : enables;
1626
    }
1627
    /**
1628
    Returns a facet reader for this facet, which can be used to
1629
    [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
1630
    */
1631
    get reader() { return this; }
1632
    /**
1633
    Define a new facet.
1634
    */
1635
    static define(config = {}) {
1636
        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);
1637
    }
1638
    /**
1639
    Returns an extension that adds the given value to this facet.
1640
    */
1641
    of(value) {
1642
        return new FacetProvider([], this, 0 /* Provider.Static */, value);
1643
    }
1644
    /**
1645
    Create an extension that computes a value for the facet from a
1646
    state. You must take care to declare the parts of the state that
1647
    this value depends on, since your function is only called again
1648
    for a new state when one of those parts changed.
1649
 
1650
    In cases where your value depends only on a single field, you'll
1651
    want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
1652
    */
1653
    compute(deps, get) {
1654
        if (this.isStatic)
1655
            throw new Error("Can't compute a static facet");
1656
        return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
1657
    }
1658
    /**
1659
    Create an extension that computes zero or more values for this
1660
    facet from a state.
1661
    */
1662
    computeN(deps, get) {
1663
        if (this.isStatic)
1664
            throw new Error("Can't compute a static facet");
1665
        return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
1666
    }
1667
    from(field, get) {
1668
        if (!get)
1669
            get = x => x;
1670
        return this.compute([field], state => get(state.field(field)));
1671
    }
1672
}
1673
function sameArray$1(a, b) {
1674
    return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1675
}
1676
class FacetProvider {
1677
    constructor(dependencies, facet, type, value) {
1678
        this.dependencies = dependencies;
1679
        this.facet = facet;
1680
        this.type = type;
1681
        this.value = value;
1682
        this.id = nextID++;
1683
    }
1684
    dynamicSlot(addresses) {
1685
        var _a;
1686
        let getter = this.value;
1687
        let compare = this.facet.compareInput;
1688
        let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
1689
        let depDoc = false, depSel = false, depAddrs = [];
1690
        for (let dep of this.dependencies) {
1691
            if (dep == "doc")
1692
                depDoc = true;
1693
            else if (dep == "selection")
1694
                depSel = true;
1695
            else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
1696
                depAddrs.push(addresses[dep.id]);
1697
        }
1698
        return {
1699
            create(state) {
1700
                state.values[idx] = getter(state);
1701
                return 1 /* SlotStatus.Changed */;
1702
            },
1703
            update(state, tr) {
1704
                if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
1705
                    let newVal = getter(state);
1706
                    if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1707
                        state.values[idx] = newVal;
1708
                        return 1 /* SlotStatus.Changed */;
1709
                    }
1710
                }
1711
                return 0;
1712
            },
1713
            reconfigure: (state, oldState) => {
1714
                let newVal, oldAddr = oldState.config.address[id];
1715
                if (oldAddr != null) {
1716
                    let oldVal = getAddr(oldState, oldAddr);
1717
                    if (this.dependencies.every(dep => {
1718
                        return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
1719
                            dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
1720
                    }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1721
                        state.values[idx] = oldVal;
1722
                        return 0;
1723
                    }
1724
                }
1725
                else {
1726
                    newVal = getter(state);
1727
                }
1728
                state.values[idx] = newVal;
1729
                return 1 /* SlotStatus.Changed */;
1730
            }
1731
        };
1732
    }
1733
}
1734
function compareArray(a, b, compare) {
1735
    if (a.length != b.length)
1736
        return false;
1737
    for (let i = 0; i < a.length; i++)
1738
        if (!compare(a[i], b[i]))
1739
            return false;
1740
    return true;
1741
}
1742
function ensureAll(state, addrs) {
1743
    let changed = false;
1744
    for (let addr of addrs)
1745
        if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
1746
            changed = true;
1747
    return changed;
1748
}
1749
function dynamicFacetSlot(addresses, facet, providers) {
1750
    let providerAddrs = providers.map(p => addresses[p.id]);
1751
    let providerTypes = providers.map(p => p.type);
1752
    let dynamic = providerAddrs.filter(p => !(p & 1));
1753
    let idx = addresses[facet.id] >> 1;
1754
    function get(state) {
1755
        let values = [];
1756
        for (let i = 0; i < providerAddrs.length; i++) {
1757
            let value = getAddr(state, providerAddrs[i]);
1758
            if (providerTypes[i] == 2 /* Provider.Multi */)
1759
                for (let val of value)
1760
                    values.push(val);
1761
            else
1762
                values.push(value);
1763
        }
1764
        return facet.combine(values);
1765
    }
1766
    return {
1767
        create(state) {
1768
            for (let addr of providerAddrs)
1769
                ensureAddr(state, addr);
1770
            state.values[idx] = get(state);
1771
            return 1 /* SlotStatus.Changed */;
1772
        },
1773
        update(state, tr) {
1774
            if (!ensureAll(state, dynamic))
1775
                return 0;
1776
            let value = get(state);
1777
            if (facet.compare(value, state.values[idx]))
1778
                return 0;
1779
            state.values[idx] = value;
1780
            return 1 /* SlotStatus.Changed */;
1781
        },
1782
        reconfigure(state, oldState) {
1783
            let depChanged = ensureAll(state, providerAddrs);
1784
            let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1785
            if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
1786
                state.values[idx] = oldValue;
1787
                return 0;
1788
            }
1789
            let value = get(state);
1790
            if (facet.compare(value, oldValue)) {
1791
                state.values[idx] = oldValue;
1792
                return 0;
1793
            }
1794
            state.values[idx] = value;
1795
            return 1 /* SlotStatus.Changed */;
1796
        }
1797
    };
1798
}
1799
const initField = /*@__PURE__*/Facet.define({ static: true });
1800
/**
1801
Fields can store additional information in an editor state, and
1802
keep it in sync with the rest of the state.
1803
*/
1804
class StateField {
1805
    constructor(
1806
    /**
1807
    @internal
1808
    */
1809
    id, createF, updateF, compareF,
1810
    /**
1811
    @internal
1812
    */
1813
    spec) {
1814
        this.id = id;
1815
        this.createF = createF;
1816
        this.updateF = updateF;
1817
        this.compareF = compareF;
1818
        this.spec = spec;
1819
        /**
1820
        @internal
1821
        */
1822
        this.provides = undefined;
1823
    }
1824
    /**
1825
    Define a state field.
1826
    */
1827
    static define(config) {
1828
        let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1829
        if (config.provide)
1830
            field.provides = config.provide(field);
1831
        return field;
1832
    }
1833
    create(state) {
1834
        let init = state.facet(initField).find(i => i.field == this);
1835
        return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
1836
    }
1837
    /**
1838
    @internal
1839
    */
1840
    slot(addresses) {
1841
        let idx = addresses[this.id] >> 1;
1842
        return {
1843
            create: (state) => {
1844
                state.values[idx] = this.create(state);
1845
                return 1 /* SlotStatus.Changed */;
1846
            },
1847
            update: (state, tr) => {
1848
                let oldVal = state.values[idx];
1849
                let value = this.updateF(oldVal, tr);
1850
                if (this.compareF(oldVal, value))
1851
                    return 0;
1852
                state.values[idx] = value;
1853
                return 1 /* SlotStatus.Changed */;
1854
            },
1855
            reconfigure: (state, oldState) => {
1441 ariadna 1856
                let init = state.facet(initField), oldInit = oldState.facet(initField), reInit;
1857
                if ((reInit = init.find(i => i.field == this)) && reInit != oldInit.find(i => i.field == this)) {
1858
                    state.values[idx] = reInit.create(state);
1859
                    return 1 /* SlotStatus.Changed */;
1860
                }
1 efrain 1861
                if (oldState.config.address[this.id] != null) {
1862
                    state.values[idx] = oldState.field(this);
1863
                    return 0;
1864
                }
1865
                state.values[idx] = this.create(state);
1866
                return 1 /* SlotStatus.Changed */;
1867
            }
1868
        };
1869
    }
1870
    /**
1871
    Returns an extension that enables this field and overrides the
1872
    way it is initialized. Can be useful when you need to provide a
1873
    non-default starting value for the field.
1874
    */
1875
    init(create) {
1876
        return [this, initField.of({ field: this, create })];
1877
    }
1878
    /**
1879
    State field instances can be used as
1880
    [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1881
    given state.
1882
    */
1883
    get extension() { return this; }
1884
}
1885
const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1886
function prec(value) {
1887
    return (ext) => new PrecExtension(ext, value);
1888
}
1889
/**
1890
By default extensions are registered in the order they are found
1891
in the flattened form of nested array that was provided.
1892
Individual extension values can be assigned a precedence to
1893
override this. Extensions that do not have a precedence set get
1894
the precedence of the nearest parent with a precedence, or
1895
[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1896
final ordering of extensions is determined by first sorting by
1897
precedence and then by order within each precedence.
1898
*/
1899
const Prec = {
1900
    /**
1901
    The highest precedence level, for extensions that should end up
1902
    near the start of the precedence ordering.
1903
    */
1904
    highest: /*@__PURE__*/prec(Prec_.highest),
1905
    /**
1906
    A higher-than-default precedence, for extensions that should
1907
    come before those with default precedence.
1908
    */
1909
    high: /*@__PURE__*/prec(Prec_.high),
1910
    /**
1911
    The default precedence, which is also used for extensions
1912
    without an explicit precedence.
1913
    */
1914
    default: /*@__PURE__*/prec(Prec_.default),
1915
    /**
1916
    A lower-than-default precedence.
1917
    */
1918
    low: /*@__PURE__*/prec(Prec_.low),
1919
    /**
1920
    The lowest precedence level. Meant for things that should end up
1921
    near the end of the extension order.
1922
    */
1923
    lowest: /*@__PURE__*/prec(Prec_.lowest)
1924
};
1925
class PrecExtension {
1926
    constructor(inner, prec) {
1927
        this.inner = inner;
1928
        this.prec = prec;
1929
    }
1930
}
1931
/**
1932
Extension compartments can be used to make a configuration
1933
dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1934
configuration in a compartment, you can later
1935
[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1936
transaction.
1937
*/
1938
class Compartment {
1939
    /**
1940
    Create an instance of this compartment to add to your [state
1941
    configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1942
    */
1943
    of(ext) { return new CompartmentInstance(this, ext); }
1944
    /**
1945
    Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1946
    reconfigures this compartment.
1947
    */
1948
    reconfigure(content) {
1949
        return Compartment.reconfigure.of({ compartment: this, extension: content });
1950
    }
1951
    /**
1952
    Get the current content of the compartment in the state, or
1953
    `undefined` if it isn't present.
1954
    */
1955
    get(state) {
1956
        return state.config.compartments.get(this);
1957
    }
1958
}
1959
class CompartmentInstance {
1960
    constructor(compartment, inner) {
1961
        this.compartment = compartment;
1962
        this.inner = inner;
1963
    }
1964
}
1965
class Configuration {
1966
    constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1967
        this.base = base;
1968
        this.compartments = compartments;
1969
        this.dynamicSlots = dynamicSlots;
1970
        this.address = address;
1971
        this.staticValues = staticValues;
1972
        this.facets = facets;
1973
        this.statusTemplate = [];
1974
        while (this.statusTemplate.length < dynamicSlots.length)
1975
            this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1976
    }
1977
    staticFacet(facet) {
1978
        let addr = this.address[facet.id];
1979
        return addr == null ? facet.default : this.staticValues[addr >> 1];
1980
    }
1981
    static resolve(base, compartments, oldState) {
1982
        let fields = [];
1983
        let facets = Object.create(null);
1984
        let newCompartments = new Map();
1985
        for (let ext of flatten(base, compartments, newCompartments)) {
1986
            if (ext instanceof StateField)
1987
                fields.push(ext);
1988
            else
1989
                (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1990
        }
1991
        let address = Object.create(null);
1992
        let staticValues = [];
1993
        let dynamicSlots = [];
1994
        for (let field of fields) {
1995
            address[field.id] = dynamicSlots.length << 1;
1996
            dynamicSlots.push(a => field.slot(a));
1997
        }
1998
        let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1999
        for (let id in facets) {
2000
            let providers = facets[id], facet = providers[0].facet;
2001
            let oldProviders = oldFacets && oldFacets[id] || [];
2002
            if (providers.every(p => p.type == 0 /* Provider.Static */)) {
2003
                address[facet.id] = (staticValues.length << 1) | 1;
2004
                if (sameArray$1(oldProviders, providers)) {
2005
                    staticValues.push(oldState.facet(facet));
2006
                }
2007
                else {
2008
                    let value = facet.combine(providers.map(p => p.value));
2009
                    staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
2010
                }
2011
            }
2012
            else {
2013
                for (let p of providers) {
2014
                    if (p.type == 0 /* Provider.Static */) {
2015
                        address[p.id] = (staticValues.length << 1) | 1;
2016
                        staticValues.push(p.value);
2017
                    }
2018
                    else {
2019
                        address[p.id] = dynamicSlots.length << 1;
2020
                        dynamicSlots.push(a => p.dynamicSlot(a));
2021
                    }
2022
                }
2023
                address[facet.id] = dynamicSlots.length << 1;
2024
                dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
2025
            }
2026
        }
2027
        let dynamic = dynamicSlots.map(f => f(address));
2028
        return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
2029
    }
2030
}
2031
function flatten(extension, compartments, newCompartments) {
2032
    let result = [[], [], [], [], []];
2033
    let seen = new Map();
2034
    function inner(ext, prec) {
2035
        let known = seen.get(ext);
2036
        if (known != null) {
2037
            if (known <= prec)
2038
                return;
2039
            let found = result[known].indexOf(ext);
2040
            if (found > -1)
2041
                result[known].splice(found, 1);
2042
            if (ext instanceof CompartmentInstance)
2043
                newCompartments.delete(ext.compartment);
2044
        }
2045
        seen.set(ext, prec);
2046
        if (Array.isArray(ext)) {
2047
            for (let e of ext)
2048
                inner(e, prec);
2049
        }
2050
        else if (ext instanceof CompartmentInstance) {
2051
            if (newCompartments.has(ext.compartment))
2052
                throw new RangeError(`Duplicate use of compartment in extensions`);
2053
            let content = compartments.get(ext.compartment) || ext.inner;
2054
            newCompartments.set(ext.compartment, content);
2055
            inner(content, prec);
2056
        }
2057
        else if (ext instanceof PrecExtension) {
2058
            inner(ext.inner, ext.prec);
2059
        }
2060
        else if (ext instanceof StateField) {
2061
            result[prec].push(ext);
2062
            if (ext.provides)
2063
                inner(ext.provides, prec);
2064
        }
2065
        else if (ext instanceof FacetProvider) {
2066
            result[prec].push(ext);
2067
            if (ext.facet.extensions)
2068
                inner(ext.facet.extensions, Prec_.default);
2069
        }
2070
        else {
2071
            let content = ext.extension;
2072
            if (!content)
2073
                throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
2074
            inner(content, prec);
2075
        }
2076
    }
2077
    inner(extension, Prec_.default);
2078
    return result.reduce((a, b) => a.concat(b));
2079
}
2080
function ensureAddr(state, addr) {
2081
    if (addr & 1)
2082
        return 2 /* SlotStatus.Computed */;
2083
    let idx = addr >> 1;
2084
    let status = state.status[idx];
2085
    if (status == 4 /* SlotStatus.Computing */)
2086
        throw new Error("Cyclic dependency between fields and/or facets");
2087
    if (status & 2 /* SlotStatus.Computed */)
2088
        return status;
2089
    state.status[idx] = 4 /* SlotStatus.Computing */;
2090
    let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2091
    return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2092
}
2093
function getAddr(state, addr) {
2094
    return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2095
}
2096
 
2097
const languageData = /*@__PURE__*/Facet.define();
2098
const allowMultipleSelections = /*@__PURE__*/Facet.define({
2099
    combine: values => values.some(v => v),
2100
    static: true
2101
});
2102
const lineSeparator = /*@__PURE__*/Facet.define({
2103
    combine: values => values.length ? values[0] : undefined,
2104
    static: true
2105
});
2106
const changeFilter = /*@__PURE__*/Facet.define();
2107
const transactionFilter = /*@__PURE__*/Facet.define();
2108
const transactionExtender = /*@__PURE__*/Facet.define();
2109
const readOnly = /*@__PURE__*/Facet.define({
2110
    combine: values => values.length ? values[0] : false
2111
});
2112
 
2113
/**
2114
Annotations are tagged values that are used to add metadata to
2115
transactions in an extensible way. They should be used to model
2116
things that effect the entire transaction (such as its [time
2117
stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2118
[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2119
_alongside_ the other changes made by the transaction, [state
2120
effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2121
*/
2122
class Annotation {
2123
    /**
2124
    @internal
2125
    */
2126
    constructor(
2127
    /**
2128
    The annotation type.
2129
    */
2130
    type,
2131
    /**
2132
    The value of this annotation.
2133
    */
2134
    value) {
2135
        this.type = type;
2136
        this.value = value;
2137
    }
2138
    /**
2139
    Define a new type of annotation.
2140
    */
2141
    static define() { return new AnnotationType(); }
2142
}
2143
/**
2144
Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2145
*/
2146
class AnnotationType {
2147
    /**
2148
    Create an instance of this annotation.
2149
    */
2150
    of(value) { return new Annotation(this, value); }
2151
}
2152
/**
2153
Representation of a type of state effect. Defined with
2154
[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2155
*/
2156
class StateEffectType {
2157
    /**
2158
    @internal
2159
    */
2160
    constructor(
2161
    // The `any` types in these function types are there to work
2162
    // around TypeScript issue #37631, where the type guard on
2163
    // `StateEffect.is` mysteriously stops working when these properly
2164
    // have type `Value`.
2165
    /**
2166
    @internal
2167
    */
2168
    map) {
2169
        this.map = map;
2170
    }
2171
    /**
2172
    Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2173
    type.
2174
    */
2175
    of(value) { return new StateEffect(this, value); }
2176
}
2177
/**
2178
State effects can be used to represent additional effects
2179
associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2180
are often useful to model changes to custom [state
2181
fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2182
document or selection changes.
2183
*/
2184
class StateEffect {
2185
    /**
2186
    @internal
2187
    */
2188
    constructor(
2189
    /**
2190
    @internal
2191
    */
2192
    type,
2193
    /**
2194
    The value of this effect.
2195
    */
2196
    value) {
2197
        this.type = type;
2198
        this.value = value;
2199
    }
2200
    /**
2201
    Map this effect through a position mapping. Will return
2202
    `undefined` when that ends up deleting the effect.
2203
    */
2204
    map(mapping) {
2205
        let mapped = this.type.map(this.value, mapping);
2206
        return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2207
    }
2208
    /**
2209
    Tells you whether this effect object is of a given
2210
    [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2211
    */
2212
    is(type) { return this.type == type; }
2213
    /**
2214
    Define a new effect type. The type parameter indicates the type
2215
    of values that his effect holds. It should be a type that
2216
    doesn't include `undefined`, since that is used in
2217
    [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2218
    removed.
2219
    */
2220
    static define(spec = {}) {
2221
        return new StateEffectType(spec.map || (v => v));
2222
    }
2223
    /**
2224
    Map an array of effects through a change set.
2225
    */
2226
    static mapEffects(effects, mapping) {
2227
        if (!effects.length)
2228
            return effects;
2229
        let result = [];
2230
        for (let effect of effects) {
2231
            let mapped = effect.map(mapping);
2232
            if (mapped)
2233
                result.push(mapped);
2234
        }
2235
        return result;
2236
    }
2237
}
2238
/**
2239
This effect can be used to reconfigure the root extensions of
2240
the editor. Doing this will discard any extensions
2241
[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2242
the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2243
compartments.
2244
*/
2245
StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2246
/**
2247
Append extensions to the top-level configuration of the editor.
2248
*/
2249
StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2250
/**
2251
Changes to the editor state are grouped into transactions.
2252
Typically, a user action creates a single transaction, which may
2253
contain any number of document changes, may change the selection,
2254
or have other effects. Create a transaction by calling
2255
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2256
dispatch one by calling
2257
[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2258
*/
2259
class Transaction {
2260
    constructor(
2261
    /**
2262
    The state from which the transaction starts.
2263
    */
2264
    startState,
2265
    /**
2266
    The document changes made by this transaction.
2267
    */
2268
    changes,
2269
    /**
2270
    The selection set by this transaction, or undefined if it
2271
    doesn't explicitly set a selection.
2272
    */
2273
    selection,
2274
    /**
2275
    The effects added to the transaction.
2276
    */
2277
    effects,
2278
    /**
2279
    @internal
2280
    */
2281
    annotations,
2282
    /**
2283
    Whether the selection should be scrolled into view after this
2284
    transaction is dispatched.
2285
    */
2286
    scrollIntoView) {
2287
        this.startState = startState;
2288
        this.changes = changes;
2289
        this.selection = selection;
2290
        this.effects = effects;
2291
        this.annotations = annotations;
2292
        this.scrollIntoView = scrollIntoView;
2293
        /**
2294
        @internal
2295
        */
2296
        this._doc = null;
2297
        /**
2298
        @internal
2299
        */
2300
        this._state = null;
2301
        if (selection)
2302
            checkSelection(selection, changes.newLength);
2303
        if (!annotations.some((a) => a.type == Transaction.time))
2304
            this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2305
    }
2306
    /**
2307
    @internal
2308
    */
2309
    static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2310
        return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2311
    }
2312
    /**
2313
    The new document produced by the transaction. Contrary to
2314
    [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2315
    force the entire new state to be computed right away, so it is
2316
    recommended that [transaction
2317
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2318
    when they need to look at the new document.
2319
    */
2320
    get newDoc() {
2321
        return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2322
    }
2323
    /**
2324
    The new selection produced by the transaction. If
2325
    [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2326
    this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2327
    current selection through the changes made by the transaction.
2328
    */
2329
    get newSelection() {
2330
        return this.selection || this.startState.selection.map(this.changes);
2331
    }
2332
    /**
2333
    The new state created by the transaction. Computed on demand
2334
    (but retained for subsequent access), so it is recommended not to
2335
    access it in [transaction
2336
    filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2337
    */
2338
    get state() {
2339
        if (!this._state)
2340
            this.startState.applyTransaction(this);
2341
        return this._state;
2342
    }
2343
    /**
2344
    Get the value of the given annotation type, if any.
2345
    */
2346
    annotation(type) {
2347
        for (let ann of this.annotations)
2348
            if (ann.type == type)
2349
                return ann.value;
2350
        return undefined;
2351
    }
2352
    /**
2353
    Indicates whether the transaction changed the document.
2354
    */
2355
    get docChanged() { return !this.changes.empty; }
2356
    /**
2357
    Indicates whether this transaction reconfigures the state
2358
    (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2359
    with a top-level configuration
2360
    [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2361
    */
2362
    get reconfigured() { return this.startState.config != this.state.config; }
2363
    /**
2364
    Returns true if the transaction has a [user
2365
    event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2366
    or more specific than `event`. For example, if the transaction
2367
    has `"select.pointer"` as user event, `"select"` and
2368
    `"select.pointer"` will match it.
2369
    */
2370
    isUserEvent(event) {
2371
        let e = this.annotation(Transaction.userEvent);
2372
        return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2373
    }
2374
}
2375
/**
2376
Annotation used to store transaction timestamps. Automatically
2377
added to every transaction, holding `Date.now()`.
2378
*/
2379
Transaction.time = /*@__PURE__*/Annotation.define();
2380
/**
2381
Annotation used to associate a transaction with a user interface
2382
event. Holds a string identifying the event, using a
2383
dot-separated format to support attaching more specific
2384
information. The events used by the core libraries are:
2385
 
2386
 - `"input"` when content is entered
2387
   - `"input.type"` for typed input
2388
     - `"input.type.compose"` for composition
2389
   - `"input.paste"` for pasted input
2390
   - `"input.drop"` when adding content with drag-and-drop
2391
   - `"input.complete"` when autocompleting
2392
 - `"delete"` when the user deletes content
2393
   - `"delete.selection"` when deleting the selection
2394
   - `"delete.forward"` when deleting forward from the selection
2395
   - `"delete.backward"` when deleting backward from the selection
2396
   - `"delete.cut"` when cutting to the clipboard
2397
 - `"move"` when content is moved
2398
   - `"move.drop"` when content is moved within the editor through drag-and-drop
2399
 - `"select"` when explicitly changing the selection
2400
   - `"select.pointer"` when selecting with a mouse or other pointing device
2401
 - `"undo"` and `"redo"` for history actions
2402
 
2403
Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2404
whether the annotation matches a given event.
2405
*/
2406
Transaction.userEvent = /*@__PURE__*/Annotation.define();
2407
/**
2408
Annotation indicating whether a transaction should be added to
2409
the undo history or not.
2410
*/
2411
Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2412
/**
2413
Annotation indicating (when present and true) that a transaction
2414
represents a change made by some other actor, not the user. This
2415
is used, for example, to tag other people's changes in
2416
collaborative editing.
2417
*/
2418
Transaction.remote = /*@__PURE__*/Annotation.define();
2419
function joinRanges(a, b) {
2420
    let result = [];
2421
    for (let iA = 0, iB = 0;;) {
2422
        let from, to;
2423
        if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2424
            from = a[iA++];
2425
            to = a[iA++];
2426
        }
2427
        else if (iB < b.length) {
2428
            from = b[iB++];
2429
            to = b[iB++];
2430
        }
2431
        else
2432
            return result;
2433
        if (!result.length || result[result.length - 1] < from)
2434
            result.push(from, to);
2435
        else if (result[result.length - 1] < to)
2436
            result[result.length - 1] = to;
2437
    }
2438
}
2439
function mergeTransaction(a, b, sequential) {
2440
    var _a;
2441
    let mapForA, mapForB, changes;
2442
    if (sequential) {
2443
        mapForA = b.changes;
2444
        mapForB = ChangeSet.empty(b.changes.length);
2445
        changes = a.changes.compose(b.changes);
2446
    }
2447
    else {
2448
        mapForA = b.changes.map(a.changes);
2449
        mapForB = a.changes.mapDesc(b.changes, true);
2450
        changes = a.changes.compose(mapForA);
2451
    }
2452
    return {
2453
        changes,
2454
        selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2455
        effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2456
        annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2457
        scrollIntoView: a.scrollIntoView || b.scrollIntoView
2458
    };
2459
}
2460
function resolveTransactionInner(state, spec, docSize) {
2461
    let sel = spec.selection, annotations = asArray$1(spec.annotations);
2462
    if (spec.userEvent)
2463
        annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2464
    return {
2465
        changes: spec.changes instanceof ChangeSet ? spec.changes
2466
            : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2467
        selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2468
        effects: asArray$1(spec.effects),
2469
        annotations,
2470
        scrollIntoView: !!spec.scrollIntoView
2471
    };
2472
}
2473
function resolveTransaction(state, specs, filter) {
2474
    let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2475
    if (specs.length && specs[0].filter === false)
2476
        filter = false;
2477
    for (let i = 1; i < specs.length; i++) {
2478
        if (specs[i].filter === false)
2479
            filter = false;
2480
        let seq = !!specs[i].sequential;
2481
        s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2482
    }
2483
    let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2484
    return extendTransaction(filter ? filterTransaction(tr) : tr);
2485
}
2486
// Finish a transaction by applying filters if necessary.
2487
function filterTransaction(tr) {
2488
    let state = tr.startState;
2489
    // Change filters
2490
    let result = true;
2491
    for (let filter of state.facet(changeFilter)) {
2492
        let value = filter(tr);
2493
        if (value === false) {
2494
            result = false;
2495
            break;
2496
        }
2497
        if (Array.isArray(value))
2498
            result = result === true ? value : joinRanges(result, value);
2499
    }
2500
    if (result !== true) {
2501
        let changes, back;
2502
        if (result === false) {
2503
            back = tr.changes.invertedDesc;
2504
            changes = ChangeSet.empty(state.doc.length);
2505
        }
2506
        else {
2507
            let filtered = tr.changes.filter(result);
2508
            changes = filtered.changes;
2509
            back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2510
        }
2511
        tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2512
    }
2513
    // Transaction filters
2514
    let filters = state.facet(transactionFilter);
2515
    for (let i = filters.length - 1; i >= 0; i--) {
2516
        let filtered = filters[i](tr);
2517
        if (filtered instanceof Transaction)
2518
            tr = filtered;
2519
        else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2520
            tr = filtered[0];
2521
        else
2522
            tr = resolveTransaction(state, asArray$1(filtered), false);
2523
    }
2524
    return tr;
2525
}
2526
function extendTransaction(tr) {
2527
    let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2528
    for (let i = extenders.length - 1; i >= 0; i--) {
2529
        let extension = extenders[i](tr);
2530
        if (extension && Object.keys(extension).length)
2531
            spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2532
    }
2533
    return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2534
}
2535
const none$2 = [];
2536
function asArray$1(value) {
2537
    return value == null ? none$2 : Array.isArray(value) ? value : [value];
2538
}
2539
 
2540
/**
2541
The categories produced by a [character
2542
categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2543
do things like selecting by word.
2544
*/
2545
var CharCategory = /*@__PURE__*/(function (CharCategory) {
2546
    /**
2547
    Word characters.
2548
    */
2549
    CharCategory[CharCategory["Word"] = 0] = "Word";
2550
    /**
2551
    Whitespace.
2552
    */
2553
    CharCategory[CharCategory["Space"] = 1] = "Space";
2554
    /**
2555
    Anything else.
2556
    */
2557
    CharCategory[CharCategory["Other"] = 2] = "Other";
2558
return CharCategory})(CharCategory || (CharCategory = {}));
2559
const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2560
let wordChar;
2561
try {
2562
    wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2563
}
2564
catch (_) { }
2565
function hasWordChar(str) {
2566
    if (wordChar)
2567
        return wordChar.test(str);
2568
    for (let i = 0; i < str.length; i++) {
2569
        let ch = str[i];
2570
        if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2571
            return true;
2572
    }
2573
    return false;
2574
}
2575
function makeCategorizer(wordChars) {
2576
    return (char) => {
2577
        if (!/\S/.test(char))
2578
            return CharCategory.Space;
2579
        if (hasWordChar(char))
2580
            return CharCategory.Word;
2581
        for (let i = 0; i < wordChars.length; i++)
2582
            if (char.indexOf(wordChars[i]) > -1)
2583
                return CharCategory.Word;
2584
        return CharCategory.Other;
2585
    };
2586
}
2587
 
2588
/**
2589
The editor state class is a persistent (immutable) data structure.
2590
To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2591
[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2592
instance, without modifying the original object.
2593
 
2594
As such, _never_ mutate properties of a state directly. That'll
2595
just break things.
2596
*/
2597
class EditorState {
2598
    constructor(
2599
    /**
2600
    @internal
2601
    */
2602
    config,
2603
    /**
2604
    The current document.
2605
    */
2606
    doc,
2607
    /**
2608
    The current selection.
2609
    */
2610
    selection,
2611
    /**
2612
    @internal
2613
    */
2614
    values, computeSlot, tr) {
2615
        this.config = config;
2616
        this.doc = doc;
2617
        this.selection = selection;
2618
        this.values = values;
2619
        this.status = config.statusTemplate.slice();
2620
        this.computeSlot = computeSlot;
2621
        // Fill in the computed state immediately, so that further queries
2622
        // for it made during the update return this state
2623
        if (tr)
2624
            tr._state = this;
2625
        for (let i = 0; i < this.config.dynamicSlots.length; i++)
2626
            ensureAddr(this, i << 1);
2627
        this.computeSlot = null;
2628
    }
2629
    field(field, require = true) {
2630
        let addr = this.config.address[field.id];
2631
        if (addr == null) {
2632
            if (require)
2633
                throw new RangeError("Field is not present in this state");
2634
            return undefined;
2635
        }
2636
        ensureAddr(this, addr);
2637
        return getAddr(this, addr);
2638
    }
2639
    /**
2640
    Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2641
    state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2642
    can be passed. Unless
2643
    [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2644
    [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2645
    are assumed to start in the _current_ document (not the document
2646
    produced by previous specs), and its
2647
    [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2648
    [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2649
    to the document created by its _own_ changes. The resulting
2650
    transaction contains the combined effect of all the different
2651
    specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2652
    specs take precedence over earlier ones.
2653
    */
2654
    update(...specs) {
2655
        return resolveTransaction(this, specs, true);
2656
    }
2657
    /**
2658
    @internal
2659
    */
2660
    applyTransaction(tr) {
2661
        let conf = this.config, { base, compartments } = conf;
2662
        for (let effect of tr.effects) {
2663
            if (effect.is(Compartment.reconfigure)) {
2664
                if (conf) {
2665
                    compartments = new Map;
2666
                    conf.compartments.forEach((val, key) => compartments.set(key, val));
2667
                    conf = null;
2668
                }
2669
                compartments.set(effect.value.compartment, effect.value.extension);
2670
            }
2671
            else if (effect.is(StateEffect.reconfigure)) {
2672
                conf = null;
2673
                base = effect.value;
2674
            }
2675
            else if (effect.is(StateEffect.appendConfig)) {
2676
                conf = null;
2677
                base = asArray$1(base).concat(effect.value);
2678
            }
2679
        }
2680
        let startValues;
2681
        if (!conf) {
2682
            conf = Configuration.resolve(base, compartments, this);
2683
            let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2684
            startValues = intermediateState.values;
2685
        }
2686
        else {
2687
            startValues = tr.startState.values.slice();
2688
        }
2689
        let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
2690
        new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
2691
    }
2692
    /**
2693
    Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2694
    replaces every selection range with the given content.
2695
    */
2696
    replaceSelection(text) {
2697
        if (typeof text == "string")
2698
            text = this.toText(text);
2699
        return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2700
            range: EditorSelection.cursor(range.from + text.length) }));
2701
    }
2702
    /**
2703
    Create a set of changes and a new selection by running the given
2704
    function for each range in the active selection. The function
2705
    can return an optional set of changes (in the coordinate space
2706
    of the start document), plus an updated range (in the coordinate
2707
    space of the document produced by the call's own changes). This
2708
    method will merge all the changes and ranges into a single
2709
    changeset and selection, and return it as a [transaction
2710
    spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2711
    [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2712
    */
2713
    changeByRange(f) {
2714
        let sel = this.selection;
2715
        let result1 = f(sel.ranges[0]);
2716
        let changes = this.changes(result1.changes), ranges = [result1.range];
2717
        let effects = asArray$1(result1.effects);
2718
        for (let i = 1; i < sel.ranges.length; i++) {
2719
            let result = f(sel.ranges[i]);
2720
            let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2721
            for (let j = 0; j < i; j++)
2722
                ranges[j] = ranges[j].map(newMapped);
2723
            let mapBy = changes.mapDesc(newChanges, true);
2724
            ranges.push(result.range.map(mapBy));
2725
            changes = changes.compose(newMapped);
2726
            effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy));
2727
        }
2728
        return {
2729
            changes,
2730
            selection: EditorSelection.create(ranges, sel.mainIndex),
2731
            effects
2732
        };
2733
    }
2734
    /**
2735
    Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2736
    description, taking the state's document length and line
2737
    separator into account.
2738
    */
2739
    changes(spec = []) {
2740
        if (spec instanceof ChangeSet)
2741
            return spec;
2742
        return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2743
    }
2744
    /**
2745
    Using the state's [line
2746
    separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2747
    [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2748
    */
2749
    toText(string) {
2750
        return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2751
    }
2752
    /**
2753
    Return the given range of the document as a string.
2754
    */
2755
    sliceDoc(from = 0, to = this.doc.length) {
2756
        return this.doc.sliceString(from, to, this.lineBreak);
2757
    }
2758
    /**
2759
    Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2760
    */
2761
    facet(facet) {
2762
        let addr = this.config.address[facet.id];
2763
        if (addr == null)
2764
            return facet.default;
2765
        ensureAddr(this, addr);
2766
        return getAddr(this, addr);
2767
    }
2768
    /**
2769
    Convert this state to a JSON-serializable object. When custom
2770
    fields should be serialized, you can pass them in as an object
2771
    mapping property names (in the resulting object, which should
2772
    not use `doc` or `selection`) to fields.
2773
    */
2774
    toJSON(fields) {
2775
        let result = {
2776
            doc: this.sliceDoc(),
2777
            selection: this.selection.toJSON()
2778
        };
2779
        if (fields)
2780
            for (let prop in fields) {
2781
                let value = fields[prop];
2782
                if (value instanceof StateField && this.config.address[value.id] != null)
2783
                    result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2784
            }
2785
        return result;
2786
    }
2787
    /**
2788
    Deserialize a state from its JSON representation. When custom
2789
    fields should be deserialized, pass the same object you passed
2790
    to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2791
    third argument.
2792
    */
2793
    static fromJSON(json, config = {}, fields) {
2794
        if (!json || typeof json.doc != "string")
2795
            throw new RangeError("Invalid JSON representation for EditorState");
2796
        let fieldInit = [];
2797
        if (fields)
2798
            for (let prop in fields) {
2799
                if (Object.prototype.hasOwnProperty.call(json, prop)) {
2800
                    let field = fields[prop], value = json[prop];
2801
                    fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2802
                }
2803
            }
2804
        return EditorState.create({
2805
            doc: json.doc,
2806
            selection: EditorSelection.fromJSON(json.selection),
2807
            extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2808
        });
2809
    }
2810
    /**
2811
    Create a new state. You'll usually only need this when
2812
    initializing an editor—updated states are created by applying
2813
    transactions.
2814
    */
2815
    static create(config = {}) {
2816
        let configuration = Configuration.resolve(config.extensions || [], new Map);
2817
        let doc = config.doc instanceof Text ? config.doc
2818
            : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2819
        let selection = !config.selection ? EditorSelection.single(0)
2820
            : config.selection instanceof EditorSelection ? config.selection
2821
                : EditorSelection.single(config.selection.anchor, config.selection.head);
2822
        checkSelection(selection, doc.length);
2823
        if (!configuration.staticFacet(allowMultipleSelections))
2824
            selection = selection.asSingle();
2825
        return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2826
    }
2827
    /**
2828
    The size (in columns) of a tab in the document, determined by
2829
    the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2830
    */
2831
    get tabSize() { return this.facet(EditorState.tabSize); }
2832
    /**
2833
    Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2834
    string for this state.
2835
    */
2836
    get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2837
    /**
2838
    Returns true when the editor is
2839
    [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2840
    */
2841
    get readOnly() { return this.facet(readOnly); }
2842
    /**
2843
    Look up a translation for the given phrase (via the
2844
    [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2845
    original string if no translation is found.
2846
 
2847
    If additional arguments are passed, they will be inserted in
2848
    place of markers like `$1` (for the first value) and `$2`, etc.
2849
    A single `$` is equivalent to `$1`, and `$$` will produce a
2850
    literal dollar sign.
2851
    */
2852
    phrase(phrase, ...insert) {
2853
        for (let map of this.facet(EditorState.phrases))
2854
            if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2855
                phrase = map[phrase];
2856
                break;
2857
            }
2858
        if (insert.length)
2859
            phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2860
                if (i == "$")
2861
                    return "$";
2862
                let n = +(i || 1);
2863
                return !n || n > insert.length ? m : insert[n - 1];
2864
            });
2865
        return phrase;
2866
    }
2867
    /**
2868
    Find the values for a given language data field, provided by the
2869
    the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2870
 
2871
    Examples of language data fields are...
2872
 
2873
    - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2874
      comment syntax.
2875
    - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2876
      for providing language-specific completion sources.
2877
    - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2878
      characters that should be considered part of words in this
2879
      language.
2880
    - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2881
      bracket closing behavior.
2882
    */
2883
    languageDataAt(name, pos, side = -1) {
2884
        let values = [];
2885
        for (let provider of this.facet(languageData)) {
2886
            for (let result of provider(this, pos, side)) {
2887
                if (Object.prototype.hasOwnProperty.call(result, name))
2888
                    values.push(result[name]);
2889
            }
2890
        }
2891
        return values;
2892
    }
2893
    /**
2894
    Return a function that can categorize strings (expected to
2895
    represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2896
    into one of:
2897
 
2898
     - Word (contains an alphanumeric character or a character
2899
       explicitly listed in the local language's `"wordChars"`
2900
       language data, which should be a string)
2901
     - Space (contains only whitespace)
2902
     - Other (anything else)
2903
    */
2904
    charCategorizer(at) {
2905
        return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
2906
    }
2907
    /**
2908
    Find the word at the given position, meaning the range
2909
    containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2910
    around it. If no word characters are adjacent to the position,
2911
    this returns null.
2912
    */
2913
    wordAt(pos) {
2914
        let { text, from, length } = this.doc.lineAt(pos);
2915
        let cat = this.charCategorizer(pos);
2916
        let start = pos - from, end = pos - from;
2917
        while (start > 0) {
2918
            let prev = findClusterBreak(text, start, false);
2919
            if (cat(text.slice(prev, start)) != CharCategory.Word)
2920
                break;
2921
            start = prev;
2922
        }
2923
        while (end < length) {
2924
            let next = findClusterBreak(text, end);
2925
            if (cat(text.slice(end, next)) != CharCategory.Word)
2926
                break;
2927
            end = next;
2928
        }
2929
        return start == end ? null : EditorSelection.range(start + from, end + from);
2930
    }
2931
}
2932
/**
2933
A facet that, when enabled, causes the editor to allow multiple
2934
ranges to be selected. Be careful though, because by default the
2935
editor relies on the native DOM selection, which cannot handle
2936
multiple selections. An extension like
2937
[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2938
secondary selections visible to the user.
2939
*/
2940
EditorState.allowMultipleSelections = allowMultipleSelections;
2941
/**
2942
Configures the tab size to use in this state. The first
2943
(highest-precedence) value of the facet is used. If no value is
2944
given, this defaults to 4.
2945
*/
2946
EditorState.tabSize = /*@__PURE__*/Facet.define({
2947
    combine: values => values.length ? values[0] : 4
2948
});
2949
/**
2950
The line separator to use. By default, any of `"\n"`, `"\r\n"`
2951
and `"\r"` is treated as a separator when splitting lines, and
2952
lines are joined with `"\n"`.
2953
 
2954
When you configure a value here, only that precise separator
2955
will be used, allowing you to round-trip documents through the
2956
editor without normalizing line separators.
2957
*/
2958
EditorState.lineSeparator = lineSeparator;
2959
/**
2960
This facet controls the value of the
2961
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2962
consulted by commands and extensions that implement editing
2963
functionality to determine whether they should apply. It
2964
defaults to false, but when its highest-precedence value is
2965
`true`, such functionality disables itself.
2966
 
2967
Not to be confused with
2968
[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2969
controls whether the editor's DOM is set to be editable (and
2970
thus focusable).
2971
*/
2972
EditorState.readOnly = readOnly;
2973
/**
2974
Registers translation phrases. The
2975
[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2976
all objects registered with this facet to find translations for
2977
its argument.
2978
*/
2979
EditorState.phrases = /*@__PURE__*/Facet.define({
2980
    compare(a, b) {
2981
        let kA = Object.keys(a), kB = Object.keys(b);
2982
        return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2983
    }
2984
});
2985
/**
2986
A facet used to register [language
2987
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2988
*/
2989
EditorState.languageData = languageData;
2990
/**
2991
Facet used to register change filters, which are called for each
2992
transaction (unless explicitly
2993
[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2994
part of the transaction's changes.
2995
 
2996
Such a function can return `true` to indicate that it doesn't
2997
want to do anything, `false` to completely stop the changes in
2998
the transaction, or a set of ranges in which changes should be
2999
suppressed. Such ranges are represented as an array of numbers,
3000
with each pair of two numbers indicating the start and end of a
3001
range. So for example `[10, 20, 100, 110]` suppresses changes
3002
between 10 and 20, and between 100 and 110.
3003
*/
3004
EditorState.changeFilter = changeFilter;
3005
/**
3006
Facet used to register a hook that gets a chance to update or
3007
replace transaction specs before they are applied. This will
3008
only be applied for transactions that don't have
3009
[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
3010
can either return a single transaction spec (possibly the input
3011
transaction), or an array of specs (which will be combined in
3012
the same way as the arguments to
3013
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
3014
 
3015
When possible, it is recommended to avoid accessing
3016
[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
3017
since it will force creation of a state that will then be
3018
discarded again, if the transaction is actually filtered.
3019
 
3020
(This functionality should be used with care. Indiscriminately
3021
modifying transaction is likely to break something or degrade
3022
the user experience.)
3023
*/
3024
EditorState.transactionFilter = transactionFilter;
3025
/**
3026
This is a more limited form of
3027
[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
3028
which can only add
3029
[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
3030
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
3031
of filter runs even if the transaction has disabled regular
3032
[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
3033
for effects that don't need to touch the changes or selection,
3034
but do want to process every transaction.
3035
 
3036
Extenders run _after_ filters, when both are present.
3037
*/
3038
EditorState.transactionExtender = transactionExtender;
3039
Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
3040
 
3041
/**
3042
Utility function for combining behaviors to fill in a config
3043
object from an array of provided configs. `defaults` should hold
3044
default values for all optional fields in `Config`.
3045
 
3046
The function will, by default, error
3047
when a field gets two values that aren't `===`-equal, but you can
3048
provide combine functions per field to do something else.
3049
*/
3050
function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
3051
combine = {}) {
3052
    let result = {};
3053
    for (let config of configs)
3054
        for (let key of Object.keys(config)) {
3055
            let value = config[key], current = result[key];
3056
            if (current === undefined)
3057
                result[key] = value;
3058
            else if (current === value || value === undefined) ; // No conflict
3059
            else if (Object.hasOwnProperty.call(combine, key))
3060
                result[key] = combine[key](current, value);
3061
            else
3062
                throw new Error("Config merge conflict for field " + key);
3063
        }
3064
    for (let key in defaults)
3065
        if (result[key] === undefined)
3066
            result[key] = defaults[key];
3067
    return result;
3068
}
3069
 
3070
/**
3071
Each range is associated with a value, which must inherit from
3072
this class.
3073
*/
3074
class RangeValue {
3075
    /**
3076
    Compare this value with another value. Used when comparing
3077
    rangesets. The default implementation compares by identity.
3078
    Unless you are only creating a fixed number of unique instances
3079
    of your value type, it is a good idea to implement this
3080
    properly.
3081
    */
3082
    eq(other) { return this == other; }
3083
    /**
3084
    Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3085
    */
3086
    range(from, to = from) { return Range$1.create(from, to, this); }
3087
}
3088
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3089
RangeValue.prototype.point = false;
3090
RangeValue.prototype.mapMode = MapMode.TrackDel;
3091
/**
3092
A range associates a value with a range of positions.
3093
*/
3094
let Range$1 = class Range {
3095
    constructor(
3096
    /**
3097
    The range's start position.
3098
    */
3099
    from,
3100
    /**
3101
    Its end position.
3102
    */
3103
    to,
3104
    /**
3105
    The value associated with this range.
3106
    */
3107
    value) {
3108
        this.from = from;
3109
        this.to = to;
3110
        this.value = value;
3111
    }
3112
    /**
3113
    @internal
3114
    */
3115
    static create(from, to, value) {
3116
        return new Range(from, to, value);
3117
    }
3118
};
3119
function cmpRange(a, b) {
3120
    return a.from - b.from || a.value.startSide - b.value.startSide;
3121
}
3122
class Chunk {
3123
    constructor(from, to, value,
3124
    // Chunks are marked with the largest point that occurs
3125
    // in them (or -1 for no points), so that scans that are
3126
    // only interested in points (such as the
3127
    // heightmap-related logic) can skip range-only chunks.
3128
    maxPoint) {
3129
        this.from = from;
3130
        this.to = to;
3131
        this.value = value;
3132
        this.maxPoint = maxPoint;
3133
    }
3134
    get length() { return this.to[this.to.length - 1]; }
3135
    // Find the index of the given position and side. Use the ranges'
3136
    // `from` pos when `end == false`, `to` when `end == true`.
3137
    findIndex(pos, side, end, startAt = 0) {
3138
        let arr = end ? this.to : this.from;
3139
        for (let lo = startAt, hi = arr.length;;) {
3140
            if (lo == hi)
3141
                return lo;
3142
            let mid = (lo + hi) >> 1;
3143
            let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
3144
            if (mid == lo)
3145
                return diff >= 0 ? lo : hi;
3146
            if (diff >= 0)
3147
                hi = mid;
3148
            else
3149
                lo = mid + 1;
3150
        }
3151
    }
3152
    between(offset, from, to, f) {
1441 ariadna 3153
        for (let i = this.findIndex(from, -1e9 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
1 efrain 3154
            if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
3155
                return false;
3156
    }
3157
    map(offset, changes) {
3158
        let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
3159
        for (let i = 0; i < this.value.length; i++) {
3160
            let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
3161
            if (curFrom == curTo) {
3162
                let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
3163
                if (mapped == null)
3164
                    continue;
3165
                newFrom = newTo = mapped;
3166
                if (val.startSide != val.endSide) {
3167
                    newTo = changes.mapPos(curFrom, val.endSide);
3168
                    if (newTo < newFrom)
3169
                        continue;
3170
                }
3171
            }
3172
            else {
3173
                newFrom = changes.mapPos(curFrom, val.startSide);
3174
                newTo = changes.mapPos(curTo, val.endSide);
3175
                if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
3176
                    continue;
3177
            }
3178
            if ((newTo - newFrom || val.endSide - val.startSide) < 0)
3179
                continue;
3180
            if (newPos < 0)
3181
                newPos = newFrom;
3182
            if (val.point)
3183
                maxPoint = Math.max(maxPoint, newTo - newFrom);
3184
            value.push(val);
3185
            from.push(newFrom - newPos);
3186
            to.push(newTo - newPos);
3187
        }
3188
        return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
3189
    }
3190
}
3191
/**
3192
A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3193
way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
3194
[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
3195
structure.
3196
*/
3197
class RangeSet {
3198
    constructor(
3199
    /**
3200
    @internal
3201
    */
3202
    chunkPos,
3203
    /**
3204
    @internal
3205
    */
3206
    chunk,
3207
    /**
3208
    @internal
3209
    */
3210
    nextLayer,
3211
    /**
3212
    @internal
3213
    */
3214
    maxPoint) {
3215
        this.chunkPos = chunkPos;
3216
        this.chunk = chunk;
3217
        this.nextLayer = nextLayer;
3218
        this.maxPoint = maxPoint;
3219
    }
3220
    /**
3221
    @internal
3222
    */
3223
    static create(chunkPos, chunk, nextLayer, maxPoint) {
3224
        return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
3225
    }
3226
    /**
3227
    @internal
3228
    */
3229
    get length() {
3230
        let last = this.chunk.length - 1;
3231
        return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
3232
    }
3233
    /**
3234
    The number of ranges in the set.
3235
    */
3236
    get size() {
3237
        if (this.isEmpty)
3238
            return 0;
3239
        let size = this.nextLayer.size;
3240
        for (let chunk of this.chunk)
3241
            size += chunk.value.length;
3242
        return size;
3243
    }
3244
    /**
3245
    @internal
3246
    */
3247
    chunkEnd(index) {
3248
        return this.chunkPos[index] + this.chunk[index].length;
3249
    }
3250
    /**
3251
    Update the range set, optionally adding new ranges or filtering
3252
    out existing ones.
3253
 
3254
    (Note: The type parameter is just there as a kludge to work
3255
    around TypeScript variance issues that prevented `RangeSet<X>`
3256
    from being a subtype of `RangeSet<Y>` when `X` is a subtype of
3257
    `Y`.)
3258
    */
3259
    update(updateSpec) {
3260
        let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
3261
        let filter = updateSpec.filter;
3262
        if (add.length == 0 && !filter)
3263
            return this;
3264
        if (sort)
3265
            add = add.slice().sort(cmpRange);
3266
        if (this.isEmpty)
3267
            return add.length ? RangeSet.of(add) : this;
3268
        let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
3269
        let builder = new RangeSetBuilder();
3270
        while (cur.value || i < add.length) {
3271
            if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
3272
                let range = add[i++];
3273
                if (!builder.addInner(range.from, range.to, range.value))
3274
                    spill.push(range);
3275
            }
3276
            else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
3277
                (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
3278
                (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
3279
                builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
3280
                cur.nextChunk();
3281
            }
3282
            else {
3283
                if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3284
                    if (!builder.addInner(cur.from, cur.to, cur.value))
3285
                        spill.push(Range$1.create(cur.from, cur.to, cur.value));
3286
                }
3287
                cur.next();
3288
            }
3289
        }
3290
        return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
3291
            : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
3292
    }
3293
    /**
3294
    Map this range set through a set of changes, return the new set.
3295
    */
3296
    map(changes) {
3297
        if (changes.empty || this.isEmpty)
3298
            return this;
3299
        let chunks = [], chunkPos = [], maxPoint = -1;
3300
        for (let i = 0; i < this.chunk.length; i++) {
3301
            let start = this.chunkPos[i], chunk = this.chunk[i];
3302
            let touch = changes.touchesRange(start, start + chunk.length);
3303
            if (touch === false) {
3304
                maxPoint = Math.max(maxPoint, chunk.maxPoint);
3305
                chunks.push(chunk);
3306
                chunkPos.push(changes.mapPos(start));
3307
            }
3308
            else if (touch === true) {
3309
                let { mapped, pos } = chunk.map(start, changes);
3310
                if (mapped) {
3311
                    maxPoint = Math.max(maxPoint, mapped.maxPoint);
3312
                    chunks.push(mapped);
3313
                    chunkPos.push(pos);
3314
                }
3315
            }
3316
        }
3317
        let next = this.nextLayer.map(changes);
3318
        return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
3319
    }
3320
    /**
3321
    Iterate over the ranges that touch the region `from` to `to`,
3322
    calling `f` for each. There is no guarantee that the ranges will
3323
    be reported in any specific order. When the callback returns
3324
    `false`, iteration stops.
3325
    */
3326
    between(from, to, f) {
3327
        if (this.isEmpty)
3328
            return;
3329
        for (let i = 0; i < this.chunk.length; i++) {
3330
            let start = this.chunkPos[i], chunk = this.chunk[i];
3331
            if (to >= start && from <= start + chunk.length &&
3332
                chunk.between(start, from - start, to - start, f) === false)
3333
                return;
3334
        }
3335
        this.nextLayer.between(from, to, f);
3336
    }
3337
    /**
3338
    Iterate over the ranges in this set, in order, including all
3339
    ranges that end at or after `from`.
3340
    */
3341
    iter(from = 0) {
3342
        return HeapCursor.from([this]).goto(from);
3343
    }
3344
    /**
3345
    @internal
3346
    */
3347
    get isEmpty() { return this.nextLayer == this; }
3348
    /**
3349
    Iterate over the ranges in a collection of sets, in order,
3350
    starting from `from`.
3351
    */
3352
    static iter(sets, from = 0) {
3353
        return HeapCursor.from(sets).goto(from);
3354
    }
3355
    /**
3356
    Iterate over two groups of sets, calling methods on `comparator`
3357
    to notify it of possible differences.
3358
    */
3359
    static compare(oldSets, newSets,
3360
    /**
3361
    This indicates how the underlying data changed between these
3362
    ranges, and is needed to synchronize the iteration.
3363
    */
3364
    textDiff, comparator,
3365
    /**
3366
    Can be used to ignore all non-point ranges, and points below
3367
    the given size. When -1, all ranges are compared.
3368
    */
3369
    minPointSize = -1) {
3370
        let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3371
        let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3372
        let sharedChunks = findSharedChunks(a, b, textDiff);
3373
        let sideA = new SpanCursor(a, sharedChunks, minPointSize);
3374
        let sideB = new SpanCursor(b, sharedChunks, minPointSize);
3375
        textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
3376
        if (textDiff.empty && textDiff.length == 0)
3377
            compare(sideA, 0, sideB, 0, 0, comparator);
3378
    }
3379
    /**
3380
    Compare the contents of two groups of range sets, returning true
3381
    if they are equivalent in the given range.
3382
    */
3383
    static eq(oldSets, newSets, from = 0, to) {
3384
        if (to == null)
3385
            to = 1000000000 /* C.Far */ - 1;
3386
        let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
3387
        let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
3388
        if (a.length != b.length)
3389
            return false;
3390
        if (!a.length)
3391
            return true;
3392
        let sharedChunks = findSharedChunks(a, b);
3393
        let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
3394
        for (;;) {
3395
            if (sideA.to != sideB.to ||
3396
                !sameValues(sideA.active, sideB.active) ||
3397
                sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
3398
                return false;
3399
            if (sideA.to > to)
3400
                return true;
3401
            sideA.next();
3402
            sideB.next();
3403
        }
3404
    }
3405
    /**
3406
    Iterate over a group of range sets at the same time, notifying
3407
    the iterator about the ranges covering every given piece of
3408
    content. Returns the open count (see
3409
    [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
3410
    of the iteration.
3411
    */
3412
    static spans(sets, from, to, iterator,
3413
    /**
3414
    When given and greater than -1, only points of at least this
3415
    size are taken into account.
3416
    */
3417
    minPointSize = -1) {
3418
        let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
3419
        let openRanges = cursor.openStart;
3420
        for (;;) {
3421
            let curTo = Math.min(cursor.to, to);
3422
            if (cursor.point) {
3423
                let active = cursor.activeForPoint(cursor.to);
3424
                let openCount = cursor.pointFrom < from ? active.length + 1
3425
                    : cursor.point.startSide < 0 ? active.length
3426
                        : Math.min(active.length, openRanges);
3427
                iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
3428
                openRanges = Math.min(cursor.openEnd(curTo), active.length);
3429
            }
3430
            else if (curTo > pos) {
3431
                iterator.span(pos, curTo, cursor.active, openRanges);
3432
                openRanges = cursor.openEnd(curTo);
3433
            }
3434
            if (cursor.to > to)
3435
                return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
3436
            pos = cursor.to;
3437
            cursor.next();
3438
        }
3439
    }
3440
    /**
3441
    Create a range set for the given range or array of ranges. By
3442
    default, this expects the ranges to be _sorted_ (by start
3443
    position and, if two start at the same position,
3444
    `value.startSide`). You can pass `true` as second argument to
3445
    cause the method to sort them.
3446
    */
3447
    static of(ranges, sort = false) {
3448
        let build = new RangeSetBuilder();
3449
        for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)
3450
            build.add(range.from, range.to, range.value);
3451
        return build.finish();
3452
    }
3453
    /**
3454
    Join an array of range sets into a single set.
3455
    */
3456
    static join(sets) {
3457
        if (!sets.length)
3458
            return RangeSet.empty;
3459
        let result = sets[sets.length - 1];
3460
        for (let i = sets.length - 2; i >= 0; i--) {
3461
            for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)
3462
                result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));
3463
        }
3464
        return result;
3465
    }
3466
}
3467
/**
3468
The empty set of ranges.
3469
*/
3470
RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3471
function lazySort(ranges) {
3472
    if (ranges.length > 1)
3473
        for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3474
            let cur = ranges[i];
3475
            if (cmpRange(prev, cur) > 0)
3476
                return ranges.slice().sort(cmpRange);
3477
            prev = cur;
3478
        }
3479
    return ranges;
3480
}
3481
RangeSet.empty.nextLayer = RangeSet.empty;
3482
/**
3483
A range set builder is a data structure that helps build up a
3484
[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
3485
an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3486
*/
3487
class RangeSetBuilder {
3488
    finishChunk(newArrays) {
3489
        this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
3490
        this.chunkPos.push(this.chunkStart);
3491
        this.chunkStart = -1;
3492
        this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
3493
        this.maxPoint = -1;
3494
        if (newArrays) {
3495
            this.from = [];
3496
            this.to = [];
3497
            this.value = [];
3498
        }
3499
    }
3500
    /**
3501
    Create an empty builder.
3502
    */
3503
    constructor() {
3504
        this.chunks = [];
3505
        this.chunkPos = [];
3506
        this.chunkStart = -1;
3507
        this.last = null;
1441 ariadna 3508
        this.lastFrom = -1e9 /* C.Far */;
3509
        this.lastTo = -1e9 /* C.Far */;
1 efrain 3510
        this.from = [];
3511
        this.to = [];
3512
        this.value = [];
3513
        this.maxPoint = -1;
3514
        this.setMaxPoint = -1;
3515
        this.nextLayer = null;
3516
    }
3517
    /**
3518
    Add a range. Ranges should be added in sorted (by `from` and
3519
    `value.startSide`) order.
3520
    */
3521
    add(from, to, value) {
3522
        if (!this.addInner(from, to, value))
3523
            (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
3524
    }
3525
    /**
3526
    @internal
3527
    */
3528
    addInner(from, to, value) {
3529
        let diff = from - this.lastTo || value.startSide - this.last.endSide;
3530
        if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
3531
            throw new Error("Ranges must be added sorted by `from` position and `startSide`");
3532
        if (diff < 0)
3533
            return false;
3534
        if (this.from.length == 250 /* C.ChunkSize */)
3535
            this.finishChunk(true);
3536
        if (this.chunkStart < 0)
3537
            this.chunkStart = from;
3538
        this.from.push(from - this.chunkStart);
3539
        this.to.push(to - this.chunkStart);
3540
        this.last = value;
3541
        this.lastFrom = from;
3542
        this.lastTo = to;
3543
        this.value.push(value);
3544
        if (value.point)
3545
            this.maxPoint = Math.max(this.maxPoint, to - from);
3546
        return true;
3547
    }
3548
    /**
3549
    @internal
3550
    */
3551
    addChunk(from, chunk) {
3552
        if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
3553
            return false;
3554
        if (this.from.length)
3555
            this.finishChunk(true);
3556
        this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
3557
        this.chunks.push(chunk);
3558
        this.chunkPos.push(from);
3559
        let last = chunk.value.length - 1;
3560
        this.last = chunk.value[last];
3561
        this.lastFrom = chunk.from[last] + from;
3562
        this.lastTo = chunk.to[last] + from;
3563
        return true;
3564
    }
3565
    /**
3566
    Finish the range set. Returns the new set. The builder can't be
3567
    used anymore after this has been called.
3568
    */
3569
    finish() { return this.finishInner(RangeSet.empty); }
3570
    /**
3571
    @internal
3572
    */
3573
    finishInner(next) {
3574
        if (this.from.length)
3575
            this.finishChunk(false);
3576
        if (this.chunks.length == 0)
3577
            return next;
3578
        let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
3579
        this.from = null; // Make sure further `add` calls produce errors
3580
        return result;
3581
    }
3582
}
3583
function findSharedChunks(a, b, textDiff) {
3584
    let inA = new Map();
3585
    for (let set of a)
3586
        for (let i = 0; i < set.chunk.length; i++)
3587
            if (set.chunk[i].maxPoint <= 0)
3588
                inA.set(set.chunk[i], set.chunkPos[i]);
3589
    let shared = new Set();
3590
    for (let set of b)
3591
        for (let i = 0; i < set.chunk.length; i++) {
3592
            let known = inA.get(set.chunk[i]);
3593
            if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
3594
                !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
3595
                shared.add(set.chunk[i]);
3596
        }
3597
    return shared;
3598
}
3599
class LayerCursor {
3600
    constructor(layer, skip, minPoint, rank = 0) {
3601
        this.layer = layer;
3602
        this.skip = skip;
3603
        this.minPoint = minPoint;
3604
        this.rank = rank;
3605
    }
3606
    get startSide() { return this.value ? this.value.startSide : 0; }
3607
    get endSide() { return this.value ? this.value.endSide : 0; }
1441 ariadna 3608
    goto(pos, side = -1e9 /* C.Far */) {
1 efrain 3609
        this.chunkIndex = this.rangeIndex = 0;
3610
        this.gotoInner(pos, side, false);
3611
        return this;
3612
    }
3613
    gotoInner(pos, side, forward) {
3614
        while (this.chunkIndex < this.layer.chunk.length) {
3615
            let next = this.layer.chunk[this.chunkIndex];
3616
            if (!(this.skip && this.skip.has(next) ||
3617
                this.layer.chunkEnd(this.chunkIndex) < pos ||
3618
                next.maxPoint < this.minPoint))
3619
                break;
3620
            this.chunkIndex++;
3621
            forward = false;
3622
        }
3623
        if (this.chunkIndex < this.layer.chunk.length) {
3624
            let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
3625
            if (!forward || this.rangeIndex < rangeIndex)
3626
                this.setRangeIndex(rangeIndex);
3627
        }
3628
        this.next();
3629
    }
3630
    forward(pos, side) {
3631
        if ((this.to - pos || this.endSide - side) < 0)
3632
            this.gotoInner(pos, side, true);
3633
    }
3634
    next() {
3635
        for (;;) {
3636
            if (this.chunkIndex == this.layer.chunk.length) {
3637
                this.from = this.to = 1000000000 /* C.Far */;
3638
                this.value = null;
3639
                break;
3640
            }
3641
            else {
3642
                let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3643
                let from = chunkPos + chunk.from[this.rangeIndex];
3644
                this.from = from;
3645
                this.to = chunkPos + chunk.to[this.rangeIndex];
3646
                this.value = chunk.value[this.rangeIndex];
3647
                this.setRangeIndex(this.rangeIndex + 1);
3648
                if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
3649
                    break;
3650
            }
3651
        }
3652
    }
3653
    setRangeIndex(index) {
3654
        if (index == this.layer.chunk[this.chunkIndex].value.length) {
3655
            this.chunkIndex++;
3656
            if (this.skip) {
3657
                while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
3658
                    this.chunkIndex++;
3659
            }
3660
            this.rangeIndex = 0;
3661
        }
3662
        else {
3663
            this.rangeIndex = index;
3664
        }
3665
    }
3666
    nextChunk() {
3667
        this.chunkIndex++;
3668
        this.rangeIndex = 0;
3669
        this.next();
3670
    }
3671
    compare(other) {
3672
        return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
3673
            this.to - other.to || this.endSide - other.endSide;
3674
    }
3675
}
3676
class HeapCursor {
3677
    constructor(heap) {
3678
        this.heap = heap;
3679
    }
3680
    static from(sets, skip = null, minPoint = -1) {
3681
        let heap = [];
3682
        for (let i = 0; i < sets.length; i++) {
3683
            for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
3684
                if (cur.maxPoint >= minPoint)
3685
                    heap.push(new LayerCursor(cur, skip, minPoint, i));
3686
            }
3687
        }
3688
        return heap.length == 1 ? heap[0] : new HeapCursor(heap);
3689
    }
3690
    get startSide() { return this.value ? this.value.startSide : 0; }
1441 ariadna 3691
    goto(pos, side = -1e9 /* C.Far */) {
1 efrain 3692
        for (let cur of this.heap)
3693
            cur.goto(pos, side);
3694
        for (let i = this.heap.length >> 1; i >= 0; i--)
3695
            heapBubble(this.heap, i);
3696
        this.next();
3697
        return this;
3698
    }
3699
    forward(pos, side) {
3700
        for (let cur of this.heap)
3701
            cur.forward(pos, side);
3702
        for (let i = this.heap.length >> 1; i >= 0; i--)
3703
            heapBubble(this.heap, i);
3704
        if ((this.to - pos || this.value.endSide - side) < 0)
3705
            this.next();
3706
    }
3707
    next() {
3708
        if (this.heap.length == 0) {
3709
            this.from = this.to = 1000000000 /* C.Far */;
3710
            this.value = null;
3711
            this.rank = -1;
3712
        }
3713
        else {
3714
            let top = this.heap[0];
3715
            this.from = top.from;
3716
            this.to = top.to;
3717
            this.value = top.value;
3718
            this.rank = top.rank;
3719
            if (top.value)
3720
                top.next();
3721
            heapBubble(this.heap, 0);
3722
        }
3723
    }
3724
}
3725
function heapBubble(heap, index) {
3726
    for (let cur = heap[index];;) {
3727
        let childIndex = (index << 1) + 1;
3728
        if (childIndex >= heap.length)
3729
            break;
3730
        let child = heap[childIndex];
3731
        if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
3732
            child = heap[childIndex + 1];
3733
            childIndex++;
3734
        }
3735
        if (cur.compare(child) < 0)
3736
            break;
3737
        heap[childIndex] = cur;
3738
        heap[index] = child;
3739
        index = childIndex;
3740
    }
3741
}
3742
class SpanCursor {
3743
    constructor(sets, skip, minPoint) {
3744
        this.minPoint = minPoint;
3745
        this.active = [];
3746
        this.activeTo = [];
3747
        this.activeRank = [];
3748
        this.minActive = -1;
3749
        // A currently active point range, if any
3750
        this.point = null;
3751
        this.pointFrom = 0;
3752
        this.pointRank = 0;
1441 ariadna 3753
        this.to = -1e9 /* C.Far */;
1 efrain 3754
        this.endSide = 0;
3755
        // The amount of open active ranges at the start of the iterator.
3756
        // Not including points.
3757
        this.openStart = -1;
3758
        this.cursor = HeapCursor.from(sets, skip, minPoint);
3759
    }
1441 ariadna 3760
    goto(pos, side = -1e9 /* C.Far */) {
1 efrain 3761
        this.cursor.goto(pos, side);
3762
        this.active.length = this.activeTo.length = this.activeRank.length = 0;
3763
        this.minActive = -1;
3764
        this.to = pos;
3765
        this.endSide = side;
3766
        this.openStart = -1;
3767
        this.next();
3768
        return this;
3769
    }
3770
    forward(pos, side) {
3771
        while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
3772
            this.removeActive(this.minActive);
3773
        this.cursor.forward(pos, side);
3774
    }
3775
    removeActive(index) {
3776
        remove(this.active, index);
3777
        remove(this.activeTo, index);
3778
        remove(this.activeRank, index);
3779
        this.minActive = findMinIndex(this.active, this.activeTo);
3780
    }
3781
    addActive(trackOpen) {
3782
        let i = 0, { value, to, rank } = this.cursor;
3783
        // Organize active marks by rank first, then by size
3784
        while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)
3785
            i++;
3786
        insert(this.active, i, value);
3787
        insert(this.activeTo, i, to);
3788
        insert(this.activeRank, i, rank);
3789
        if (trackOpen)
3790
            insert(trackOpen, i, this.cursor.from);
3791
        this.minActive = findMinIndex(this.active, this.activeTo);
3792
    }
3793
    // After calling this, if `this.point` != null, the next range is a
3794
    // point. Otherwise, it's a regular range, covered by `this.active`.
3795
    next() {
3796
        let from = this.to, wasPoint = this.point;
3797
        this.point = null;
3798
        let trackOpen = this.openStart < 0 ? [] : null;
3799
        for (;;) {
3800
            let a = this.minActive;
3801
            if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
3802
                if (this.activeTo[a] > from) {
3803
                    this.to = this.activeTo[a];
3804
                    this.endSide = this.active[a].endSide;
3805
                    break;
3806
                }
3807
                this.removeActive(a);
3808
                if (trackOpen)
3809
                    remove(trackOpen, a);
3810
            }
3811
            else if (!this.cursor.value) {
3812
                this.to = this.endSide = 1000000000 /* C.Far */;
3813
                break;
3814
            }
3815
            else if (this.cursor.from > from) {
3816
                this.to = this.cursor.from;
3817
                this.endSide = this.cursor.startSide;
3818
                break;
3819
            }
3820
            else {
3821
                let nextVal = this.cursor.value;
3822
                if (!nextVal.point) { // Opening a range
3823
                    this.addActive(trackOpen);
3824
                    this.cursor.next();
3825
                }
3826
                else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
3827
                    // Ignore any non-empty points that end precisely at the end of the prev point
3828
                    this.cursor.next();
3829
                }
3830
                else { // New point
3831
                    this.point = nextVal;
3832
                    this.pointFrom = this.cursor.from;
3833
                    this.pointRank = this.cursor.rank;
3834
                    this.to = this.cursor.to;
3835
                    this.endSide = nextVal.endSide;
3836
                    this.cursor.next();
3837
                    this.forward(this.to, this.endSide);
3838
                    break;
3839
                }
3840
            }
3841
        }
3842
        if (trackOpen) {
3843
            this.openStart = 0;
3844
            for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
3845
                this.openStart++;
3846
        }
3847
    }
3848
    activeForPoint(to) {
3849
        if (!this.active.length)
3850
            return this.active;
3851
        let active = [];
3852
        for (let i = this.active.length - 1; i >= 0; i--) {
3853
            if (this.activeRank[i] < this.pointRank)
3854
                break;
3855
            if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
3856
                active.push(this.active[i]);
3857
        }
3858
        return active.reverse();
3859
    }
3860
    openEnd(to) {
3861
        let open = 0;
3862
        for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
3863
            open++;
3864
        return open;
3865
    }
3866
}
3867
function compare(a, startA, b, startB, length, comparator) {
3868
    a.goto(startA);
3869
    b.goto(startB);
3870
    let endB = startB + length;
3871
    let pos = startB, dPos = startB - startA;
3872
    for (;;) {
1441 ariadna 3873
        let dEnd = (a.to + dPos) - b.to, diff = dEnd || a.endSide - b.endSide;
1 efrain 3874
        let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3875
        if (a.point || b.point) {
3876
            if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&
3877
                sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3878
                comparator.comparePoint(pos, clipEnd, a.point, b.point);
3879
        }
3880
        else {
3881
            if (clipEnd > pos && !sameValues(a.active, b.active))
3882
                comparator.compareRange(pos, clipEnd, a.active, b.active);
3883
        }
3884
        if (end > endB)
3885
            break;
1441 ariadna 3886
        if ((dEnd || a.openEnd != b.openEnd) && comparator.boundChange)
3887
            comparator.boundChange(end);
1 efrain 3888
        pos = end;
3889
        if (diff <= 0)
3890
            a.next();
3891
        if (diff >= 0)
3892
            b.next();
3893
    }
3894
}
3895
function sameValues(a, b) {
3896
    if (a.length != b.length)
3897
        return false;
3898
    for (let i = 0; i < a.length; i++)
3899
        if (a[i] != b[i] && !a[i].eq(b[i]))
3900
            return false;
3901
    return true;
3902
}
3903
function remove(array, index) {
3904
    for (let i = index, e = array.length - 1; i < e; i++)
3905
        array[i] = array[i + 1];
3906
    array.pop();
3907
}
3908
function insert(array, index, value) {
3909
    for (let i = array.length - 1; i >= index; i--)
3910
        array[i + 1] = array[i];
3911
    array[index] = value;
3912
}
3913
function findMinIndex(value, array) {
3914
    let found = -1, foundPos = 1000000000 /* C.Far */;
3915
    for (let i = 0; i < array.length; i++)
3916
        if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3917
            found = i;
3918
            foundPos = array[i];
3919
        }
3920
    return found;
3921
}
3922
 
3923
/**
3924
Count the column position at the given offset into the string,
3925
taking extending characters and tab size into account.
3926
*/
3927
function countColumn(string, tabSize, to = string.length) {
3928
    let n = 0;
1441 ariadna 3929
    for (let i = 0; i < to && i < string.length;) {
1 efrain 3930
        if (string.charCodeAt(i) == 9) {
3931
            n += tabSize - (n % tabSize);
3932
            i++;
3933
        }
3934
        else {
3935
            n++;
3936
            i = findClusterBreak(string, i);
3937
        }
3938
    }
3939
    return n;
3940
}
3941
/**
3942
Find the offset that corresponds to the given column position in a
3943
string, taking extending characters and tab size into account. By
3944
default, the string length is returned when it is too short to
3945
reach the column. Pass `strict` true to make it return -1 in that
3946
situation.
3947
*/
3948
function findColumn(string, col, tabSize, strict) {
3949
    for (let i = 0, n = 0;;) {
3950
        if (n >= col)
3951
            return i;
3952
        if (i == string.length)
3953
            break;
3954
        n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3955
        i = findClusterBreak(string, i);
3956
    }
3957
    return strict === true ? -1 : string.length;
3958
}
3959
 
3960
const C = "\u037c";
3961
const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
3962
const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
3963
const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
3964
 
3965
// :: - Style modules encapsulate a set of CSS rules defined from
3966
// JavaScript. Their definitions are only available in a given DOM
3967
// root after it has been _mounted_ there with `StyleModule.mount`.
3968
//
3969
// Style modules should be created once and stored somewhere, as
3970
// opposed to re-creating them every time you need them. The amount of
3971
// CSS rules generated for a given DOM root is bounded by the amount
3972
// of style modules that were used. So to avoid leaking rules, don't
3973
// create these dynamically, but treat them as one-time allocations.
3974
class StyleModule {
3975
  // :: (Object<Style>, ?{finish: ?(string) → string})
3976
  // Create a style module from the given spec.
3977
  //
3978
  // When `finish` is given, it is called on regular (non-`@`)
3979
  // selectors (after `&` expansion) to compute the final selector.
3980
  constructor(spec, options) {
3981
    this.rules = [];
3982
    let {finish} = options || {};
3983
 
3984
    function splitSelector(selector) {
3985
      return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
3986
    }
3987
 
3988
    function render(selectors, spec, target, isKeyframes) {
3989
      let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
3990
      if (isAt && spec == null) return target.push(selectors[0] + ";")
3991
      for (let prop in spec) {
3992
        let value = spec[prop];
3993
        if (/&/.test(prop)) {
3994
          render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
3995
                 value, target);
3996
        } else if (value && typeof value == "object") {
3997
          if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.")
3998
          render(splitSelector(prop), value, local, keyframes);
3999
        } else if (value != null) {
4000
          local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";");
4001
        }
4002
      }
4003
      if (local.length || keyframes) {
4004
        target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
4005
                    " {" + local.join(" ") + "}");
4006
      }
4007
    }
4008
 
4009
    for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules);
4010
  }
4011
 
4012
  // :: () → string
4013
  // Returns a string containing the module's CSS rules.
4014
  getRules() { return this.rules.join("\n") }
4015
 
4016
  // :: () → string
4017
  // Generate a new unique CSS class name.
4018
  static newName() {
4019
    let id = top[COUNT] || 1;
4020
    top[COUNT] = id + 1;
4021
    return C + id.toString(36)
4022
  }
4023
 
4024
  // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
4025
  //
4026
  // Mount the given set of modules in the given DOM root, which ensures
4027
  // that the CSS rules defined by the module are available in that
4028
  // context.
4029
  //
4030
  // Rules are only added to the document once per root.
4031
  //
4032
  // Rule order will follow the order of the modules, so that rules from
4033
  // modules later in the array take precedence of those from earlier
4034
  // modules. If you call this function multiple times for the same root
4035
  // in a way that changes the order of already mounted modules, the old
4036
  // order will be changed.
4037
  //
4038
  // If a Content Security Policy nonce is provided, it is added to
4039
  // the `<style>` tag generated by the library.
4040
  static mount(root, modules, options) {
4041
    let set = root[SET], nonce = options && options.nonce;
4042
    if (!set) set = new StyleSet(root, nonce);
4043
    else if (nonce) set.setNonce(nonce);
4044
    set.mount(Array.isArray(modules) ? modules : [modules], root);
4045
  }
4046
}
4047
 
4048
let adoptedSet = new Map; //<Document, StyleSet>
4049
 
4050
class StyleSet {
4051
  constructor(root, nonce) {
4052
    let doc = root.ownerDocument || root, win = doc.defaultView;
4053
    if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {
4054
      let adopted = adoptedSet.get(doc);
4055
      if (adopted) return root[SET] = adopted
4056
      this.sheet = new win.CSSStyleSheet;
4057
      adoptedSet.set(doc, this);
4058
    } else {
4059
      this.styleTag = doc.createElement("style");
4060
      if (nonce) this.styleTag.setAttribute("nonce", nonce);
4061
    }
4062
    this.modules = [];
4063
    root[SET] = this;
4064
  }
4065
 
4066
  mount(modules, root) {
4067
    let sheet = this.sheet;
4068
    let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */
4069
    for (let i = 0; i < modules.length; i++) {
4070
      let mod = modules[i], index = this.modules.indexOf(mod);
4071
      if (index < j && index > -1) { // Ordering conflict
4072
        this.modules.splice(index, 1);
4073
        j--;
4074
        index = -1;
4075
      }
4076
      if (index == -1) {
4077
        this.modules.splice(j++, 0, mod);
4078
        if (sheet) for (let k = 0; k < mod.rules.length; k++)
4079
          sheet.insertRule(mod.rules[k], pos++);
4080
      } else {
4081
        while (j < index) pos += this.modules[j++].rules.length;
4082
        pos += mod.rules.length;
4083
        j++;
4084
      }
4085
    }
4086
 
4087
    if (sheet) {
4088
      if (root.adoptedStyleSheets.indexOf(this.sheet) < 0)
4089
        root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets];
4090
    } else {
4091
      let text = "";
4092
      for (let i = 0; i < this.modules.length; i++)
4093
        text += this.modules[i].getRules() + "\n";
4094
      this.styleTag.textContent = text;
4095
      let target = root.head || root;
4096
      if (this.styleTag.parentNode != target)
4097
        target.insertBefore(this.styleTag, target.firstChild);
4098
    }
4099
  }
4100
 
4101
  setNonce(nonce) {
4102
    if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
4103
      this.styleTag.setAttribute("nonce", nonce);
4104
  }
4105
}
4106
 
4107
// Style::Object<union<Style,string>>
4108
//
4109
// A style is an object that, in the simple case, maps CSS property
4110
// names to strings holding their values, as in `{color: "red",
4111
// fontWeight: "bold"}`. The property names can be given in
4112
// camel-case—the library will insert a dash before capital letters
4113
// when converting them to CSS.
4114
//
4115
// If you include an underscore in a property name, it and everything
4116
// after it will be removed from the output, which can be useful when
4117
// providing a property multiple times, for browser compatibility
4118
// reasons.
4119
//
4120
// A property in a style object can also be a sub-selector, which
4121
// extends the current context to add a pseudo-selector or a child
4122
// selector. Such a property should contain a `&` character, which
4123
// will be replaced by the current selector. For example `{"&:before":
4124
// {content: '"hi"'}}`. Sub-selectors and regular properties can
4125
// freely be mixed in a given object. Any property containing a `&` is
4126
// assumed to be a sub-selector.
4127
//
4128
// Finally, a property can specify an @-block to be wrapped around the
4129
// styles defined inside the object that's the property's value. For
4130
// example to create a media query you can do `{"@media screen and
4131
// (min-width: 400px)": {...}}`.
4132
 
4133
var base = {
4134
  8: "Backspace",
4135
  9: "Tab",
4136
  10: "Enter",
4137
  12: "NumLock",
4138
  13: "Enter",
4139
  16: "Shift",
4140
  17: "Control",
4141
  18: "Alt",
4142
  20: "CapsLock",
4143
  27: "Escape",
4144
  32: " ",
4145
  33: "PageUp",
4146
  34: "PageDown",
4147
  35: "End",
4148
  36: "Home",
4149
  37: "ArrowLeft",
4150
  38: "ArrowUp",
4151
  39: "ArrowRight",
4152
  40: "ArrowDown",
4153
  44: "PrintScreen",
4154
  45: "Insert",
4155
  46: "Delete",
4156
  59: ";",
4157
  61: "=",
4158
  91: "Meta",
4159
  92: "Meta",
4160
  106: "*",
4161
  107: "+",
4162
  108: ",",
4163
  109: "-",
4164
  110: ".",
4165
  111: "/",
4166
  144: "NumLock",
4167
  145: "ScrollLock",
4168
  160: "Shift",
4169
  161: "Shift",
4170
  162: "Control",
4171
  163: "Control",
4172
  164: "Alt",
4173
  165: "Alt",
4174
  173: "-",
4175
  186: ";",
4176
  187: "=",
4177
  188: ",",
4178
  189: "-",
4179
  190: ".",
4180
  191: "/",
4181
  192: "`",
4182
  219: "[",
4183
  220: "\\",
4184
  221: "]",
4185
  222: "'"
4186
};
4187
 
4188
var shift = {
4189
  48: ")",
4190
  49: "!",
4191
  50: "@",
4192
  51: "#",
4193
  52: "$",
4194
  53: "%",
4195
  54: "^",
4196
  55: "&",
4197
  56: "*",
4198
  57: "(",
4199
  59: ":",
4200
  61: "+",
4201
  173: "_",
4202
  186: ":",
4203
  187: "+",
4204
  188: "<",
4205
  189: "_",
4206
  190: ">",
4207
  191: "?",
4208
  192: "~",
4209
  219: "{",
4210
  220: "|",
4211
  221: "}",
4212
  222: "\""
4213
};
4214
 
4215
var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
4216
var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
4217
 
4218
// Fill in the digit keys
4219
for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
4220
 
4221
// The function keys
4222
for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
4223
 
4224
// And the alphabetic keys
4225
for (var i = 65; i <= 90; i++) {
4226
  base[i] = String.fromCharCode(i + 32);
4227
  shift[i] = String.fromCharCode(i);
4228
}
4229
 
4230
// For each code that doesn't have a shift-equivalent, copy the base name
4231
for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
4232
 
4233
function keyName(event) {
4234
  // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.
4235
  // On IE, shift effect is never included in `.key`.
4236
  var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||
4237
      ie$1 && event.shiftKey && event.key && event.key.length == 1 ||
4238
      event.key == "Unidentified";
4239
  var name = (!ignoreKey && event.key) ||
4240
    (event.shiftKey ? shift : base)[event.keyCode] ||
4241
    event.key || "Unidentified";
4242
  // Edge sometimes produces wrong names (Issue #3)
4243
  if (name == "Esc") name = "Escape";
4244
  if (name == "Del") name = "Delete";
4245
  // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
4246
  if (name == "Left") name = "ArrowLeft";
4247
  if (name == "Up") name = "ArrowUp";
4248
  if (name == "Right") name = "ArrowRight";
4249
  if (name == "Down") name = "ArrowDown";
4250
  return name
4251
}
4252
 
4253
function getSelection(root) {
4254
    let target;
4255
    // Browsers differ on whether shadow roots have a getSelection
4256
    // method. If it exists, use that, otherwise, call it on the
4257
    // document.
4258
    if (root.nodeType == 11) { // Shadow root
4259
        target = root.getSelection ? root : root.ownerDocument;
4260
    }
4261
    else {
4262
        target = root;
4263
    }
4264
    return target.getSelection();
4265
}
4266
function contains(dom, node) {
4267
    return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
4268
}
4269
function hasSelection(dom, selection) {
4270
    if (!selection.anchorNode)
4271
        return false;
4272
    try {
4273
        // Firefox will raise 'permission denied' errors when accessing
4274
        // properties of `sel.anchorNode` when it's in a generated CSS
4275
        // element.
4276
        return contains(dom, selection.anchorNode);
4277
    }
4278
    catch (_) {
4279
        return false;
4280
    }
4281
}
4282
function clientRectsFor(dom) {
4283
    if (dom.nodeType == 3)
4284
        return textRange(dom, 0, dom.nodeValue.length).getClientRects();
4285
    else if (dom.nodeType == 1)
4286
        return dom.getClientRects();
4287
    else
4288
        return [];
4289
}
4290
// Scans forward and backward through DOM positions equivalent to the
4291
// given one to see if the two are in the same place (i.e. after a
4292
// text node vs at the end of that text node)
4293
function isEquivalentPosition(node, off, targetNode, targetOff) {
4294
    return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||
4295
        scanFor(node, off, targetNode, targetOff, 1)) : false;
4296
}
4297
function domIndex(node) {
4298
    for (var index = 0;; index++) {
4299
        node = node.previousSibling;
4300
        if (!node)
4301
            return index;
4302
    }
4303
}
4304
function isBlockElement(node) {
4305
    return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
4306
}
4307
function scanFor(node, off, targetNode, targetOff, dir) {
4308
    for (;;) {
4309
        if (node == targetNode && off == targetOff)
4310
            return true;
4311
        if (off == (dir < 0 ? 0 : maxOffset(node))) {
4312
            if (node.nodeName == "DIV")
4313
                return false;
4314
            let parent = node.parentNode;
4315
            if (!parent || parent.nodeType != 1)
4316
                return false;
4317
            off = domIndex(node) + (dir < 0 ? 0 : 1);
4318
            node = parent;
4319
        }
4320
        else if (node.nodeType == 1) {
4321
            node = node.childNodes[off + (dir < 0 ? -1 : 0)];
4322
            if (node.nodeType == 1 && node.contentEditable == "false")
4323
                return false;
4324
            off = dir < 0 ? maxOffset(node) : 0;
4325
        }
4326
        else {
4327
            return false;
4328
        }
4329
    }
4330
}
4331
function maxOffset(node) {
4332
    return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
4333
}
4334
function flattenRect(rect, left) {
4335
    let x = left ? rect.left : rect.right;
4336
    return { left: x, right: x, top: rect.top, bottom: rect.bottom };
4337
}
4338
function windowRect(win) {
4339
    let vp = win.visualViewport;
4340
    if (vp)
4341
        return {
4342
            left: 0, right: vp.width,
4343
            top: 0, bottom: vp.height
4344
        };
4345
    return { left: 0, right: win.innerWidth,
4346
        top: 0, bottom: win.innerHeight };
4347
}
4348
function getScale(elt, rect) {
4349
    let scaleX = rect.width / elt.offsetWidth;
4350
    let scaleY = rect.height / elt.offsetHeight;
4351
    if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
4352
        scaleX = 1;
4353
    if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
4354
        scaleY = 1;
4355
    return { scaleX, scaleY };
4356
}
4357
function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4358
    let doc = dom.ownerDocument, win = doc.defaultView || window;
4359
    for (let cur = dom, stop = false; cur && !stop;) {
4360
        if (cur.nodeType == 1) { // Element
4361
            let bounding, top = cur == doc.body;
4362
            let scaleX = 1, scaleY = 1;
4363
            if (top) {
4364
                bounding = windowRect(win);
4365
            }
4366
            else {
4367
                if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))
4368
                    stop = true;
4369
                if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {
4370
                    cur = cur.assignedSlot || cur.parentNode;
4371
                    continue;
4372
                }
4373
                let rect = cur.getBoundingClientRect();
4374
                ({ scaleX, scaleY } = getScale(cur, rect));
4375
                // Make sure scrollbar width isn't included in the rectangle
4376
                bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,
4377
                    top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };
4378
            }
4379
            let moveX = 0, moveY = 0;
4380
            if (y == "nearest") {
4381
                if (rect.top < bounding.top) {
1441 ariadna 4382
                    moveY = rect.top - (bounding.top + yMargin);
1 efrain 4383
                    if (side > 0 && rect.bottom > bounding.bottom + moveY)
1441 ariadna 4384
                        moveY = rect.bottom - bounding.bottom + yMargin;
1 efrain 4385
                }
4386
                else if (rect.bottom > bounding.bottom) {
4387
                    moveY = rect.bottom - bounding.bottom + yMargin;
4388
                    if (side < 0 && (rect.top - moveY) < bounding.top)
1441 ariadna 4389
                        moveY = rect.top - (bounding.top + yMargin);
1 efrain 4390
                }
4391
            }
4392
            else {
4393
                let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
4394
                let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :
4395
                    y == "start" || y == "center" && side < 0 ? rect.top - yMargin :
4396
                        rect.bottom - boundingHeight + yMargin;
4397
                moveY = targetTop - bounding.top;
4398
            }
4399
            if (x == "nearest") {
4400
                if (rect.left < bounding.left) {
1441 ariadna 4401
                    moveX = rect.left - (bounding.left + xMargin);
1 efrain 4402
                    if (side > 0 && rect.right > bounding.right + moveX)
1441 ariadna 4403
                        moveX = rect.right - bounding.right + xMargin;
1 efrain 4404
                }
4405
                else if (rect.right > bounding.right) {
4406
                    moveX = rect.right - bounding.right + xMargin;
4407
                    if (side < 0 && rect.left < bounding.left + moveX)
1441 ariadna 4408
                        moveX = rect.left - (bounding.left + xMargin);
1 efrain 4409
                }
4410
            }
4411
            else {
4412
                let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :
4413
                    (x == "start") == ltr ? rect.left - xMargin :
4414
                        rect.right - (bounding.right - bounding.left) + xMargin;
4415
                moveX = targetLeft - bounding.left;
4416
            }
4417
            if (moveX || moveY) {
4418
                if (top) {
4419
                    win.scrollBy(moveX, moveY);
4420
                }
4421
                else {
4422
                    let movedX = 0, movedY = 0;
4423
                    if (moveY) {
4424
                        let start = cur.scrollTop;
4425
                        cur.scrollTop += moveY / scaleY;
4426
                        movedY = (cur.scrollTop - start) * scaleY;
4427
                    }
4428
                    if (moveX) {
4429
                        let start = cur.scrollLeft;
4430
                        cur.scrollLeft += moveX / scaleX;
4431
                        movedX = (cur.scrollLeft - start) * scaleX;
4432
                    }
4433
                    rect = { left: rect.left - movedX, top: rect.top - movedY,
4434
                        right: rect.right - movedX, bottom: rect.bottom - movedY };
4435
                    if (movedX && Math.abs(movedX - moveX) < 1)
4436
                        x = "nearest";
4437
                    if (movedY && Math.abs(movedY - moveY) < 1)
4438
                        y = "nearest";
4439
                }
4440
            }
4441
            if (top)
4442
                break;
1441 ariadna 4443
            if (rect.top < bounding.top || rect.bottom > bounding.bottom ||
4444
                rect.left < bounding.left || rect.right > bounding.right)
4445
                rect = { left: Math.max(rect.left, bounding.left), right: Math.min(rect.right, bounding.right),
4446
                    top: Math.max(rect.top, bounding.top), bottom: Math.min(rect.bottom, bounding.bottom) };
1 efrain 4447
            cur = cur.assignedSlot || cur.parentNode;
4448
        }
4449
        else if (cur.nodeType == 11) { // A shadow root
4450
            cur = cur.host;
4451
        }
4452
        else {
4453
            break;
4454
        }
4455
    }
4456
}
1441 ariadna 4457
function scrollableParents(dom) {
4458
    let doc = dom.ownerDocument, x, y;
1 efrain 4459
    for (let cur = dom.parentNode; cur;) {
1441 ariadna 4460
        if (cur == doc.body || (x && y)) {
1 efrain 4461
            break;
4462
        }
4463
        else if (cur.nodeType == 1) {
1441 ariadna 4464
            if (!y && cur.scrollHeight > cur.clientHeight)
4465
                y = cur;
4466
            if (!x && cur.scrollWidth > cur.clientWidth)
4467
                x = cur;
1 efrain 4468
            cur = cur.assignedSlot || cur.parentNode;
4469
        }
4470
        else if (cur.nodeType == 11) {
4471
            cur = cur.host;
4472
        }
4473
        else {
4474
            break;
4475
        }
4476
    }
1441 ariadna 4477
    return { x, y };
1 efrain 4478
}
4479
class DOMSelectionState {
4480
    constructor() {
4481
        this.anchorNode = null;
4482
        this.anchorOffset = 0;
4483
        this.focusNode = null;
4484
        this.focusOffset = 0;
4485
    }
4486
    eq(domSel) {
4487
        return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&
4488
            this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
4489
    }
4490
    setRange(range) {
4491
        let { anchorNode, focusNode } = range;
4492
        // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)
4493
        this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
4494
    }
4495
    set(anchorNode, anchorOffset, focusNode, focusOffset) {
4496
        this.anchorNode = anchorNode;
4497
        this.anchorOffset = anchorOffset;
4498
        this.focusNode = focusNode;
4499
        this.focusOffset = focusOffset;
4500
    }
4501
}
4502
let preventScrollSupported = null;
4503
// Feature-detects support for .focus({preventScroll: true}), and uses
4504
// a fallback kludge when not supported.
4505
function focusPreventScroll(dom) {
4506
    if (dom.setActive)
4507
        return dom.setActive(); // in IE
4508
    if (preventScrollSupported)
4509
        return dom.focus(preventScrollSupported);
4510
    let stack = [];
4511
    for (let cur = dom; cur; cur = cur.parentNode) {
4512
        stack.push(cur, cur.scrollTop, cur.scrollLeft);
4513
        if (cur == cur.ownerDocument)
4514
            break;
4515
    }
4516
    dom.focus(preventScrollSupported == null ? {
4517
        get preventScroll() {
4518
            preventScrollSupported = { preventScroll: true };
4519
            return true;
4520
        }
4521
    } : undefined);
4522
    if (!preventScrollSupported) {
4523
        preventScrollSupported = false;
4524
        for (let i = 0; i < stack.length;) {
4525
            let elt = stack[i++], top = stack[i++], left = stack[i++];
4526
            if (elt.scrollTop != top)
4527
                elt.scrollTop = top;
4528
            if (elt.scrollLeft != left)
4529
                elt.scrollLeft = left;
4530
        }
4531
    }
4532
}
4533
let scratchRange;
4534
function textRange(node, from, to = from) {
4535
    let range = scratchRange || (scratchRange = document.createRange());
4536
    range.setEnd(node, to);
4537
    range.setStart(node, from);
4538
    return range;
4539
}
4540
function dispatchKey(elt, name, code, mods) {
4541
    let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };
4542
    if (mods)
4543
        ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods);
4544
    let down = new KeyboardEvent("keydown", options);
4545
    down.synthetic = true;
4546
    elt.dispatchEvent(down);
4547
    let up = new KeyboardEvent("keyup", options);
4548
    up.synthetic = true;
4549
    elt.dispatchEvent(up);
4550
    return down.defaultPrevented || up.defaultPrevented;
4551
}
4552
function getRoot(node) {
4553
    while (node) {
4554
        if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
4555
            return node;
4556
        node = node.assignedSlot || node.parentNode;
4557
    }
4558
    return null;
4559
}
4560
function clearAttributes(node) {
4561
    while (node.attributes.length)
4562
        node.removeAttributeNode(node.attributes[0]);
4563
}
4564
function atElementStart(doc, selection) {
4565
    let node = selection.focusNode, offset = selection.focusOffset;
4566
    if (!node || selection.anchorNode != node || selection.anchorOffset != offset)
4567
        return false;
4568
    // Safari can report bogus offsets (#1152)
4569
    offset = Math.min(offset, maxOffset(node));
4570
    for (;;) {
4571
        if (offset) {
4572
            if (node.nodeType != 1)
4573
                return false;
4574
            let prev = node.childNodes[offset - 1];
4575
            if (prev.contentEditable == "false")
4576
                offset--;
4577
            else {
4578
                node = prev;
4579
                offset = maxOffset(node);
4580
            }
4581
        }
4582
        else if (node == doc) {
4583
            return true;
4584
        }
4585
        else {
4586
            offset = domIndex(node);
4587
            node = node.parentNode;
4588
        }
4589
    }
4590
}
4591
function isScrolledToBottom(elt) {
4592
    return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
4593
}
4594
function textNodeBefore(startNode, startOffset) {
4595
    for (let node = startNode, offset = startOffset;;) {
4596
        if (node.nodeType == 3 && offset > 0) {
4597
            return { node: node, offset: offset };
4598
        }
4599
        else if (node.nodeType == 1 && offset > 0) {
4600
            if (node.contentEditable == "false")
4601
                return null;
4602
            node = node.childNodes[offset - 1];
4603
            offset = maxOffset(node);
4604
        }
4605
        else if (node.parentNode && !isBlockElement(node)) {
4606
            offset = domIndex(node);
4607
            node = node.parentNode;
4608
        }
4609
        else {
4610
            return null;
4611
        }
4612
    }
4613
}
4614
function textNodeAfter(startNode, startOffset) {
4615
    for (let node = startNode, offset = startOffset;;) {
4616
        if (node.nodeType == 3 && offset < node.nodeValue.length) {
4617
            return { node: node, offset: offset };
4618
        }
4619
        else if (node.nodeType == 1 && offset < node.childNodes.length) {
4620
            if (node.contentEditable == "false")
4621
                return null;
4622
            node = node.childNodes[offset];
4623
            offset = 0;
4624
        }
4625
        else if (node.parentNode && !isBlockElement(node)) {
4626
            offset = domIndex(node) + 1;
4627
            node = node.parentNode;
4628
        }
4629
        else {
4630
            return null;
4631
        }
4632
    }
4633
}
4634
 
4635
class DOMPos {
4636
    constructor(node, offset, precise = true) {
4637
        this.node = node;
4638
        this.offset = offset;
4639
        this.precise = precise;
4640
    }
4641
    static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }
4642
    static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }
4643
}
4644
const noChildren = [];
4645
class ContentView {
4646
    constructor() {
4647
        this.parent = null;
4648
        this.dom = null;
4649
        this.flags = 2 /* ViewFlag.NodeDirty */;
4650
    }
4651
    get overrideDOMText() { return null; }
4652
    get posAtStart() {
4653
        return this.parent ? this.parent.posBefore(this) : 0;
4654
    }
4655
    get posAtEnd() {
4656
        return this.posAtStart + this.length;
4657
    }
4658
    posBefore(view) {
4659
        let pos = this.posAtStart;
4660
        for (let child of this.children) {
4661
            if (child == view)
4662
                return pos;
4663
            pos += child.length + child.breakAfter;
4664
        }
4665
        throw new RangeError("Invalid child in posBefore");
4666
    }
4667
    posAfter(view) {
4668
        return this.posBefore(view) + view.length;
4669
    }
4670
    sync(view, track) {
4671
        if (this.flags & 2 /* ViewFlag.NodeDirty */) {
4672
            let parent = this.dom;
4673
            let prev = null, next;
4674
            for (let child of this.children) {
4675
                if (child.flags & 7 /* ViewFlag.Dirty */) {
4676
                    if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
4677
                        let contentView = ContentView.get(next);
4678
                        if (!contentView || !contentView.parent && contentView.canReuseDOM(child))
4679
                            child.reuseDOM(next);
4680
                    }
4681
                    child.sync(view, track);
1441 ariadna 4682
                    child.flags &= -8 /* ViewFlag.Dirty */;
1 efrain 4683
                }
4684
                next = prev ? prev.nextSibling : parent.firstChild;
4685
                if (track && !track.written && track.node == parent && next != child.dom)
4686
                    track.written = true;
4687
                if (child.dom.parentNode == parent) {
4688
                    while (next && next != child.dom)
4689
                        next = rm$1(next);
4690
                }
4691
                else {
4692
                    parent.insertBefore(child.dom, next);
4693
                }
4694
                prev = child.dom;
4695
            }
4696
            next = prev ? prev.nextSibling : parent.firstChild;
4697
            if (next && track && track.node == parent)
4698
                track.written = true;
4699
            while (next)
4700
                next = rm$1(next);
4701
        }
4702
        else if (this.flags & 1 /* ViewFlag.ChildDirty */) {
4703
            for (let child of this.children)
4704
                if (child.flags & 7 /* ViewFlag.Dirty */) {
4705
                    child.sync(view, track);
1441 ariadna 4706
                    child.flags &= -8 /* ViewFlag.Dirty */;
1 efrain 4707
                }
4708
        }
4709
    }
4710
    reuseDOM(_dom) { }
4711
    localPosFromDOM(node, offset) {
4712
        let after;
4713
        if (node == this.dom) {
4714
            after = this.dom.childNodes[offset];
4715
        }
4716
        else {
4717
            let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
4718
            for (;;) {
4719
                let parent = node.parentNode;
4720
                if (parent == this.dom)
4721
                    break;
4722
                if (bias == 0 && parent.firstChild != parent.lastChild) {
4723
                    if (node == parent.firstChild)
4724
                        bias = -1;
4725
                    else
4726
                        bias = 1;
4727
                }
4728
                node = parent;
4729
            }
4730
            if (bias < 0)
4731
                after = node;
4732
            else
4733
                after = node.nextSibling;
4734
        }
4735
        if (after == this.dom.firstChild)
4736
            return 0;
4737
        while (after && !ContentView.get(after))
4738
            after = after.nextSibling;
4739
        if (!after)
4740
            return this.length;
4741
        for (let i = 0, pos = 0;; i++) {
4742
            let child = this.children[i];
4743
            if (child.dom == after)
4744
                return pos;
4745
            pos += child.length + child.breakAfter;
4746
        }
4747
    }
4748
    domBoundsAround(from, to, offset = 0) {
4749
        let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
4750
        for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {
4751
            let child = this.children[i], end = pos + child.length;
4752
            if (pos < from && end > to)
4753
                return child.domBoundsAround(from, to, pos);
4754
            if (end >= from && fromI == -1) {
4755
                fromI = i;
4756
                fromStart = pos;
4757
            }
4758
            if (pos > to && child.dom.parentNode == this.dom) {
4759
                toI = i;
4760
                toEnd = prevEnd;
4761
                break;
4762
            }
4763
            prevEnd = end;
4764
            pos = end + child.breakAfter;
4765
        }
4766
        return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd,
4767
            startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
4768
            endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null };
4769
    }
4770
    markDirty(andParent = false) {
4771
        this.flags |= 2 /* ViewFlag.NodeDirty */;
4772
        this.markParentsDirty(andParent);
4773
    }
4774
    markParentsDirty(childList) {
4775
        for (let parent = this.parent; parent; parent = parent.parent) {
4776
            if (childList)
4777
                parent.flags |= 2 /* ViewFlag.NodeDirty */;
4778
            if (parent.flags & 1 /* ViewFlag.ChildDirty */)
4779
                return;
4780
            parent.flags |= 1 /* ViewFlag.ChildDirty */;
4781
            childList = false;
4782
        }
4783
    }
4784
    setParent(parent) {
4785
        if (this.parent != parent) {
4786
            this.parent = parent;
4787
            if (this.flags & 7 /* ViewFlag.Dirty */)
4788
                this.markParentsDirty(true);
4789
        }
4790
    }
4791
    setDOM(dom) {
4792
        if (this.dom == dom)
4793
            return;
4794
        if (this.dom)
4795
            this.dom.cmView = null;
4796
        this.dom = dom;
4797
        dom.cmView = this;
4798
    }
4799
    get rootView() {
4800
        for (let v = this;;) {
4801
            let parent = v.parent;
4802
            if (!parent)
4803
                return v;
4804
            v = parent;
4805
        }
4806
    }
4807
    replaceChildren(from, to, children = noChildren) {
4808
        this.markDirty();
4809
        for (let i = from; i < to; i++) {
4810
            let child = this.children[i];
4811
            if (child.parent == this && children.indexOf(child) < 0)
4812
                child.destroy();
4813
        }
1441 ariadna 4814
        if (children.length < 250)
4815
            this.children.splice(from, to - from, ...children);
4816
        else
4817
            this.children = [].concat(this.children.slice(0, from), children, this.children.slice(to));
1 efrain 4818
        for (let i = 0; i < children.length; i++)
4819
            children[i].setParent(this);
4820
    }
4821
    ignoreMutation(_rec) { return false; }
4822
    ignoreEvent(_event) { return false; }
4823
    childCursor(pos = this.length) {
4824
        return new ChildCursor(this.children, pos, this.children.length);
4825
    }
4826
    childPos(pos, bias = 1) {
4827
        return this.childCursor().findPos(pos, bias);
4828
    }
4829
    toString() {
4830
        let name = this.constructor.name.replace("View", "");
4831
        return name + (this.children.length ? "(" + this.children.join() + ")" :
4832
            this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") +
4833
            (this.breakAfter ? "#" : "");
4834
    }
4835
    static get(node) { return node.cmView; }
4836
    get isEditable() { return true; }
4837
    get isWidget() { return false; }
4838
    get isHidden() { return false; }
4839
    merge(from, to, source, hasStart, openStart, openEnd) {
4840
        return false;
4841
    }
4842
    become(other) { return false; }
4843
    canReuseDOM(other) {
4844
        return other.constructor == this.constructor && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
4845
    }
4846
    // When this is a zero-length view with a side, this should return a
4847
    // number <= 0 to indicate it is before its position, or a
4848
    // number > 0 when after its position.
4849
    getSide() { return 0; }
4850
    destroy() {
4851
        for (let child of this.children)
4852
            if (child.parent == this)
4853
                child.destroy();
4854
        this.parent = null;
4855
    }
4856
}
4857
ContentView.prototype.breakAfter = 0;
4858
// Remove a DOM node and return its next sibling.
4859
function rm$1(dom) {
4860
    let next = dom.nextSibling;
4861
    dom.parentNode.removeChild(dom);
4862
    return next;
4863
}
4864
class ChildCursor {
4865
    constructor(children, pos, i) {
4866
        this.children = children;
4867
        this.pos = pos;
4868
        this.i = i;
4869
        this.off = 0;
4870
    }
4871
    findPos(pos, bias = 1) {
4872
        for (;;) {
4873
            if (pos > this.pos || pos == this.pos &&
4874
                (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
4875
                this.off = pos - this.pos;
4876
                return this;
4877
            }
4878
            let next = this.children[--this.i];
4879
            this.pos -= next.length + next.breakAfter;
4880
        }
4881
    }
4882
}
4883
function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) {
4884
    let { children } = parent;
4885
    let before = children.length ? children[fromI] : null;
4886
    let last = insert.length ? insert[insert.length - 1] : null;
4887
    let breakAtEnd = last ? last.breakAfter : breakAtStart;
4888
    // Change within a single child
4889
    if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 &&
4890
        before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd))
4891
        return;
4892
    if (toI < children.length) {
4893
        let after = children[toI];
4894
        // Make sure the end of the child after the update is preserved in `after`
4895
        if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
4896
            // If we're splitting a child, separate part of it to avoid that
4897
            // being mangled when updating the child before the update.
4898
            if (fromI == toI) {
4899
                after = after.split(toOff);
4900
                toOff = 0;
4901
            }
4902
            // If the element after the replacement should be merged with
4903
            // the last replacing element, update `content`
4904
            if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
4905
                insert[insert.length - 1] = after;
4906
            }
4907
            else {
4908
                // Remove the start of the after element, if necessary, and
4909
                // add it to `content`.
4910
                if (toOff || after.children.length && !after.children[0].length)
4911
                    after.merge(0, toOff, null, false, 0, openEnd);
4912
                insert.push(after);
4913
            }
4914
        }
4915
        else if (after === null || after === void 0 ? void 0 : after.breakAfter) {
4916
            // The element at `toI` is entirely covered by this range.
4917
            // Preserve its line break, if any.
4918
            if (last)
4919
                last.breakAfter = 1;
4920
            else
4921
                breakAtStart = 1;
4922
        }
4923
        // Since we've handled the next element from the current elements
4924
        // now, make sure `toI` points after that.
4925
        toI++;
4926
    }
4927
    if (before) {
4928
        before.breakAfter = breakAtStart;
4929
        if (fromOff > 0) {
4930
            if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) {
4931
                before.breakAfter = insert.shift().breakAfter;
4932
            }
4933
            else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
4934
                before.merge(fromOff, before.length, null, false, openStart, 0);
4935
            }
4936
            fromI++;
4937
        }
4938
    }
4939
    // Try to merge widgets on the boundaries of the replacement
4940
    while (fromI < toI && insert.length) {
4941
        if (children[toI - 1].become(insert[insert.length - 1])) {
4942
            toI--;
4943
            insert.pop();
4944
            openEnd = insert.length ? 0 : openStart;
4945
        }
4946
        else if (children[fromI].become(insert[0])) {
4947
            fromI++;
4948
            insert.shift();
4949
            openStart = insert.length ? 0 : openEnd;
4950
        }
4951
        else {
4952
            break;
4953
        }
4954
    }
4955
    if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter &&
4956
        children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd))
4957
        fromI--;
4958
    if (fromI < toI || insert.length)
4959
        parent.replaceChildren(fromI, toI, insert);
4960
}
4961
function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) {
4962
    let cur = parent.childCursor();
4963
    let { i: toI, off: toOff } = cur.findPos(to, 1);
4964
    let { i: fromI, off: fromOff } = cur.findPos(from, -1);
4965
    let dLen = from - to;
4966
    for (let view of insert)
4967
        dLen += view.length;
4968
    parent.length += dLen;
4969
    replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd);
4970
}
4971
 
4972
let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
4973
let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
4974
const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent);
4975
const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent);
4976
const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
4977
const ie = !!(ie_upto10 || ie_11up || ie_edge);
4978
const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent);
4979
const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent);
4980
const webkit = "webkitFontSmoothing" in doc.documentElement.style;
4981
const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);
4982
const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
4983
var browser = {
4984
    mac: ios || /*@__PURE__*//Mac/.test(nav.platform),
4985
    windows: /*@__PURE__*//Win/.test(nav.platform),
4986
    linux: /*@__PURE__*//Linux|X11/.test(nav.platform),
4987
    ie,
4988
    ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
4989
    gecko,
4990
    gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4991
    chrome: !!chrome,
4992
    chrome_version: chrome ? +chrome[1] : 0,
4993
    ios,
4994
    android: /*@__PURE__*//Android\b/.test(nav.userAgent),
4995
    webkit,
4996
    safari,
1441 ariadna 4997
    webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
1 efrain 4998
    tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
4999
};
5000
 
5001
const MaxJoinLen = 256;
5002
class TextView extends ContentView {
5003
    constructor(text) {
5004
        super();
5005
        this.text = text;
5006
    }
5007
    get length() { return this.text.length; }
5008
    createDOM(textDOM) {
5009
        this.setDOM(textDOM || document.createTextNode(this.text));
5010
    }
5011
    sync(view, track) {
5012
        if (!this.dom)
5013
            this.createDOM();
5014
        if (this.dom.nodeValue != this.text) {
5015
            if (track && track.node == this.dom)
5016
                track.written = true;
5017
            this.dom.nodeValue = this.text;
5018
        }
5019
    }
5020
    reuseDOM(dom) {
5021
        if (dom.nodeType == 3)
5022
            this.createDOM(dom);
5023
    }
5024
    merge(from, to, source) {
5025
        if ((this.flags & 8 /* ViewFlag.Composition */) ||
5026
            source && (!(source instanceof TextView) ||
5027
                this.length - (to - from) + source.length > MaxJoinLen ||
5028
                (source.flags & 8 /* ViewFlag.Composition */)))
5029
            return false;
5030
        this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
5031
        this.markDirty();
5032
        return true;
5033
    }
5034
    split(from) {
5035
        let result = new TextView(this.text.slice(from));
5036
        this.text = this.text.slice(0, from);
5037
        this.markDirty();
5038
        result.flags |= this.flags & 8 /* ViewFlag.Composition */;
5039
        return result;
5040
    }
5041
    localPosFromDOM(node, offset) {
5042
        return node == this.dom ? offset : offset ? this.text.length : 0;
5043
    }
5044
    domAtPos(pos) { return new DOMPos(this.dom, pos); }
5045
    domBoundsAround(_from, _to, offset) {
5046
        return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
5047
    }
5048
    coordsAt(pos, side) {
5049
        return textCoords(this.dom, pos, side);
5050
    }
5051
}
5052
class MarkView extends ContentView {
5053
    constructor(mark, children = [], length = 0) {
5054
        super();
5055
        this.mark = mark;
5056
        this.children = children;
5057
        this.length = length;
5058
        for (let ch of children)
5059
            ch.setParent(this);
5060
    }
5061
    setAttrs(dom) {
5062
        clearAttributes(dom);
5063
        if (this.mark.class)
5064
            dom.className = this.mark.class;
5065
        if (this.mark.attrs)
5066
            for (let name in this.mark.attrs)
5067
                dom.setAttribute(name, this.mark.attrs[name]);
5068
        return dom;
5069
    }
5070
    canReuseDOM(other) {
5071
        return super.canReuseDOM(other) && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
5072
    }
5073
    reuseDOM(node) {
5074
        if (node.nodeName == this.mark.tagName.toUpperCase()) {
5075
            this.setDOM(node);
5076
            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
5077
        }
5078
    }
5079
    sync(view, track) {
5080
        if (!this.dom)
5081
            this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
5082
        else if (this.flags & 4 /* ViewFlag.AttrsDirty */)
5083
            this.setAttrs(this.dom);
5084
        super.sync(view, track);
5085
    }
5086
    merge(from, to, source, _hasStart, openStart, openEnd) {
5087
        if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||
5088
            (from && openStart <= 0) || (to < this.length && openEnd <= 0)))
5089
            return false;
5090
        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);
5091
        this.markDirty();
5092
        return true;
5093
    }
5094
    split(from) {
5095
        let result = [], off = 0, detachFrom = -1, i = 0;
5096
        for (let elt of this.children) {
5097
            let end = off + elt.length;
5098
            if (end > from)
5099
                result.push(off < from ? elt.split(from - off) : elt);
5100
            if (detachFrom < 0 && off >= from)
5101
                detachFrom = i;
5102
            off = end;
5103
            i++;
5104
        }
5105
        let length = this.length - from;
5106
        this.length = from;
5107
        if (detachFrom > -1) {
5108
            this.children.length = detachFrom;
5109
            this.markDirty();
5110
        }
5111
        return new MarkView(this.mark, result, length);
5112
    }
5113
    domAtPos(pos) {
5114
        return inlineDOMAtPos(this, pos);
5115
    }
5116
    coordsAt(pos, side) {
5117
        return coordsInChildren(this, pos, side);
5118
    }
5119
}
5120
function textCoords(text, pos, side) {
5121
    let length = text.nodeValue.length;
5122
    if (pos > length)
5123
        pos = length;
5124
    let from = pos, to = pos, flatten = 0;
5125
    if (pos == 0 && side < 0 || pos == length && side >= 0) {
5126
        if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges
5127
            if (pos) {
5128
                from--;
5129
                flatten = 1;
5130
            } // FIXME this is wrong in RTL text
5131
            else if (to < length) {
5132
                to++;
5133
                flatten = -1;
5134
            }
5135
        }
5136
    }
5137
    else {
5138
        if (side < 0)
5139
            from--;
5140
        else if (to < length)
5141
            to++;
5142
    }
5143
    let rects = textRange(text, from, to).getClientRects();
5144
    if (!rects.length)
5145
        return null;
5146
    let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
5147
    if (browser.safari && !flatten && rect.width == 0)
5148
        rect = Array.prototype.find.call(rects, r => r.width) || rect;
5149
    return flatten ? flattenRect(rect, flatten < 0) : rect || null;
5150
}
5151
// Also used for collapsed ranges that don't have a placeholder widget!
5152
class WidgetView extends ContentView {
5153
    static create(widget, length, side) {
5154
        return new WidgetView(widget, length, side);
5155
    }
5156
    constructor(widget, length, side) {
5157
        super();
5158
        this.widget = widget;
5159
        this.length = length;
5160
        this.side = side;
5161
        this.prevWidget = null;
5162
    }
5163
    split(from) {
5164
        let result = WidgetView.create(this.widget, this.length - from, this.side);
5165
        this.length -= from;
5166
        return result;
5167
    }
5168
    sync(view) {
5169
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5170
            if (this.dom && this.prevWidget)
5171
                this.prevWidget.destroy(this.dom);
5172
            this.prevWidget = null;
5173
            this.setDOM(this.widget.toDOM(view));
5174
            if (!this.widget.editable)
5175
                this.dom.contentEditable = "false";
5176
        }
5177
    }
5178
    getSide() { return this.side; }
5179
    merge(from, to, source, hasStart, openStart, openEnd) {
5180
        if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||
5181
            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5182
            return false;
5183
        this.length = from + (source ? source.length : 0) + (this.length - to);
5184
        return true;
5185
    }
5186
    become(other) {
5187
        if (other instanceof WidgetView && other.side == this.side &&
5188
            this.widget.constructor == other.widget.constructor) {
5189
            if (!this.widget.compare(other.widget))
5190
                this.markDirty(true);
5191
            if (this.dom && !this.prevWidget)
5192
                this.prevWidget = this.widget;
5193
            this.widget = other.widget;
5194
            this.length = other.length;
5195
            return true;
5196
        }
5197
        return false;
5198
    }
5199
    ignoreMutation() { return true; }
5200
    ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5201
    get overrideDOMText() {
5202
        if (this.length == 0)
5203
            return Text.empty;
5204
        let top = this;
5205
        while (top.parent)
5206
            top = top.parent;
5207
        let { view } = top, text = view && view.state.doc, start = this.posAtStart;
5208
        return text ? text.slice(start, start + this.length) : Text.empty;
5209
    }
5210
    domAtPos(pos) {
5211
        return (this.length ? pos == 0 : this.side > 0)
5212
            ? DOMPos.before(this.dom)
5213
            : DOMPos.after(this.dom, pos == this.length);
5214
    }
5215
    domBoundsAround() { return null; }
5216
    coordsAt(pos, side) {
5217
        let custom = this.widget.coordsAt(this.dom, pos, side);
5218
        if (custom)
5219
            return custom;
5220
        let rects = this.dom.getClientRects(), rect = null;
5221
        if (!rects.length)
5222
            return null;
5223
        let fromBack = this.side ? this.side < 0 : pos > 0;
5224
        for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {
5225
            rect = rects[i];
5226
            if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
5227
                break;
5228
        }
5229
        return flattenRect(rect, !fromBack);
5230
    }
5231
    get isEditable() { return false; }
5232
    get isWidget() { return true; }
5233
    get isHidden() { return this.widget.isHidden; }
5234
    destroy() {
5235
        super.destroy();
5236
        if (this.dom)
5237
            this.widget.destroy(this.dom);
5238
    }
5239
}
5240
// These are drawn around uneditable widgets to avoid a number of
5241
// browser bugs that show up when the cursor is directly next to
5242
// uneditable inline content.
5243
class WidgetBufferView extends ContentView {
5244
    constructor(side) {
5245
        super();
5246
        this.side = side;
5247
    }
5248
    get length() { return 0; }
5249
    merge() { return false; }
5250
    become(other) {
5251
        return other instanceof WidgetBufferView && other.side == this.side;
5252
    }
5253
    split() { return new WidgetBufferView(this.side); }
5254
    sync() {
5255
        if (!this.dom) {
5256
            let dom = document.createElement("img");
5257
            dom.className = "cm-widgetBuffer";
5258
            dom.setAttribute("aria-hidden", "true");
5259
            this.setDOM(dom);
5260
        }
5261
    }
5262
    getSide() { return this.side; }
5263
    domAtPos(pos) { return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom); }
5264
    localPosFromDOM() { return 0; }
5265
    domBoundsAround() { return null; }
5266
    coordsAt(pos) {
5267
        return this.dom.getBoundingClientRect();
5268
    }
5269
    get overrideDOMText() {
5270
        return Text.empty;
5271
    }
5272
    get isHidden() { return true; }
5273
}
5274
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
5275
function inlineDOMAtPos(parent, pos) {
5276
    let dom = parent.dom, { children } = parent, i = 0;
5277
    for (let off = 0; i < children.length; i++) {
5278
        let child = children[i], end = off + child.length;
5279
        if (end == off && child.getSide() <= 0)
5280
            continue;
5281
        if (pos > off && pos < end && child.dom.parentNode == dom)
5282
            return child.domAtPos(pos - off);
5283
        if (pos <= off)
5284
            break;
5285
        off = end;
5286
    }
5287
    for (let j = i; j > 0; j--) {
5288
        let prev = children[j - 1];
5289
        if (prev.dom.parentNode == dom)
5290
            return prev.domAtPos(prev.length);
5291
    }
5292
    for (let j = i; j < children.length; j++) {
5293
        let next = children[j];
5294
        if (next.dom.parentNode == dom)
5295
            return next.domAtPos(0);
5296
    }
5297
    return new DOMPos(dom, 0);
5298
}
5299
// Assumes `view`, if a mark view, has precisely 1 child.
5300
function joinInlineInto(parent, view, open) {
5301
    let last, { children } = parent;
5302
    if (open > 0 && view instanceof MarkView && children.length &&
5303
        (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
5304
        joinInlineInto(last, view.children[0], open - 1);
5305
    }
5306
    else {
5307
        children.push(view);
5308
        view.setParent(parent);
5309
    }
5310
    parent.length += view.length;
5311
}
5312
function coordsInChildren(view, pos, side) {
5313
    let before = null, beforePos = -1, after = null, afterPos = -1;
5314
    function scan(view, pos) {
5315
        for (let i = 0, off = 0; i < view.children.length && off <= pos; i++) {
5316
            let child = view.children[i], end = off + child.length;
5317
            if (end >= pos) {
5318
                if (child.children.length) {
5319
                    scan(child, pos - off);
5320
                }
5321
                else if ((!after || after.isHidden && side > 0) &&
5322
                    (end > pos || off == end && child.getSide() > 0)) {
5323
                    after = child;
5324
                    afterPos = pos - off;
5325
                }
5326
                else if (off < pos || (off == end && child.getSide() < 0) && !child.isHidden) {
5327
                    before = child;
5328
                    beforePos = pos - off;
5329
                }
5330
            }
5331
            off = end;
5332
        }
5333
    }
5334
    scan(view, pos);
5335
    let target = (side < 0 ? before : after) || before || after;
5336
    if (target)
5337
        return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
5338
    return fallbackRect(view);
5339
}
5340
function fallbackRect(view) {
5341
    let last = view.dom.lastChild;
5342
    if (!last)
5343
        return view.dom.getBoundingClientRect();
5344
    let rects = clientRectsFor(last);
5345
    return rects[rects.length - 1] || null;
5346
}
5347
 
5348
function combineAttrs(source, target) {
5349
    for (let name in source) {
5350
        if (name == "class" && target.class)
5351
            target.class += " " + source.class;
5352
        else if (name == "style" && target.style)
5353
            target.style += ";" + source.style;
5354
        else
5355
            target[name] = source[name];
5356
    }
5357
    return target;
5358
}
1441 ariadna 5359
const noAttrs$1 = /*@__PURE__*/Object.create(null);
1 efrain 5360
function attrsEq(a, b, ignore) {
5361
    if (a == b)
5362
        return true;
5363
    if (!a)
1441 ariadna 5364
        a = noAttrs$1;
1 efrain 5365
    if (!b)
1441 ariadna 5366
        b = noAttrs$1;
1 efrain 5367
    let keysA = Object.keys(a), keysB = Object.keys(b);
5368
    if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=
5369
        keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
5370
        return false;
5371
    for (let key of keysA) {
5372
        if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))
5373
            return false;
5374
    }
5375
    return true;
5376
}
5377
function updateAttrs(dom, prev, attrs) {
5378
    let changed = false;
5379
    if (prev)
5380
        for (let name in prev)
5381
            if (!(attrs && name in attrs)) {
5382
                changed = true;
5383
                if (name == "style")
5384
                    dom.style.cssText = "";
5385
                else
5386
                    dom.removeAttribute(name);
5387
            }
5388
    if (attrs)
5389
        for (let name in attrs)
5390
            if (!(prev && prev[name] == attrs[name])) {
5391
                changed = true;
5392
                if (name == "style")
5393
                    dom.style.cssText = attrs[name];
5394
                else
5395
                    dom.setAttribute(name, attrs[name]);
5396
            }
5397
    return changed;
5398
}
5399
function getAttrs$1(dom) {
5400
    let attrs = Object.create(null);
5401
    for (let i = 0; i < dom.attributes.length; i++) {
5402
        let attr = dom.attributes[i];
5403
        attrs[attr.name] = attr.value;
5404
    }
5405
    return attrs;
5406
}
5407
 
5408
/**
5409
Widgets added to the content are described by subclasses of this
5410
class. Using a description object like that makes it possible to
5411
delay creating of the DOM structure for a widget until it is
5412
needed, and to avoid redrawing widgets even if the decorations
5413
that define them are recreated.
5414
*/
5415
class WidgetType {
5416
    /**
5417
    Compare this instance to another instance of the same type.
5418
    (TypeScript can't express this, but only instances of the same
5419
    specific class will be passed to this method.) This is used to
5420
    avoid redrawing widgets when they are replaced by a new
5421
    decoration of the same type. The default implementation just
5422
    returns `false`, which will cause new instances of the widget to
5423
    always be redrawn.
5424
    */
5425
    eq(widget) { return false; }
5426
    /**
5427
    Update a DOM element created by a widget of the same type (but
5428
    different, non-`eq` content) to reflect this widget. May return
5429
    true to indicate that it could update, false to indicate it
5430
    couldn't (in which case the widget will be redrawn). The default
5431
    implementation just returns false.
5432
    */
5433
    updateDOM(dom, view) { return false; }
5434
    /**
5435
    @internal
5436
    */
5437
    compare(other) {
5438
        return this == other || this.constructor == other.constructor && this.eq(other);
5439
    }
5440
    /**
5441
    The estimated height this widget will have, to be used when
5442
    estimating the height of content that hasn't been drawn. May
5443
    return -1 to indicate you don't know. The default implementation
5444
    returns -1.
5445
    */
5446
    get estimatedHeight() { return -1; }
5447
    /**
5448
    For inline widgets that are displayed inline (as opposed to
5449
    `inline-block`) and introduce line breaks (through `<br>` tags
5450
    or textual newlines), this must indicate the amount of line
5451
    breaks they introduce. Defaults to 0.
5452
    */
5453
    get lineBreaks() { return 0; }
5454
    /**
5455
    Can be used to configure which kinds of events inside the widget
5456
    should be ignored by the editor. The default is to ignore all
5457
    events.
5458
    */
5459
    ignoreEvent(event) { return true; }
5460
    /**
5461
    Override the way screen coordinates for positions at/in the
5462
    widget are found. `pos` will be the offset into the widget, and
5463
    `side` the side of the position that is being queried—less than
5464
    zero for before, greater than zero for after, and zero for
5465
    directly at that position.
5466
    */
5467
    coordsAt(dom, pos, side) { return null; }
5468
    /**
5469
    @internal
5470
    */
5471
    get isHidden() { return false; }
5472
    /**
5473
    @internal
5474
    */
5475
    get editable() { return false; }
5476
    /**
5477
    This is called when the an instance of the widget is removed
5478
    from the editor view.
5479
    */
5480
    destroy(dom) { }
5481
}
5482
/**
5483
The different types of blocks that can occur in an editor view.
5484
*/
5485
var BlockType = /*@__PURE__*/(function (BlockType) {
5486
    /**
5487
    A line of text.
5488
    */
5489
    BlockType[BlockType["Text"] = 0] = "Text";
5490
    /**
5491
    A block widget associated with the position after it.
5492
    */
5493
    BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore";
5494
    /**
5495
    A block widget associated with the position before it.
5496
    */
5497
    BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter";
5498
    /**
5499
    A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
5500
    */
5501
    BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange";
5502
return BlockType})(BlockType || (BlockType = {}));
5503
/**
5504
A decoration provides information on how to draw or style a piece
5505
of content. You'll usually use it wrapped in a
5506
[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
5507
@nonabstract
5508
*/
5509
class Decoration extends RangeValue {
5510
    constructor(
5511
    /**
5512
    @internal
5513
    */
5514
    startSide,
5515
    /**
5516
    @internal
5517
    */
5518
    endSide,
5519
    /**
5520
    @internal
5521
    */
5522
    widget,
5523
    /**
5524
    The config object used to create this decoration. You can
5525
    include additional properties in there to store metadata about
5526
    your decoration.
5527
    */
5528
    spec) {
5529
        super();
5530
        this.startSide = startSide;
5531
        this.endSide = endSide;
5532
        this.widget = widget;
5533
        this.spec = spec;
5534
    }
5535
    /**
5536
    @internal
5537
    */
5538
    get heightRelevant() { return false; }
5539
    /**
5540
    Create a mark decoration, which influences the styling of the
5541
    content in its range. Nested mark decorations will cause nested
5542
    DOM elements to be created. Nesting order is determined by
5543
    precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
5544
    the higher-precedence decorations creating the inner DOM nodes.
5545
    Such elements are split on line boundaries and on the boundaries
5546
    of lower-precedence decorations.
5547
    */
5548
    static mark(spec) {
5549
        return new MarkDecoration(spec);
5550
    }
5551
    /**
5552
    Create a widget decoration, which displays a DOM element at the
5553
    given position.
5554
    */
5555
    static widget(spec) {
1441 ariadna 5556
        let side = Math.max(-1e4, Math.min(10000, spec.side || 0)), block = !!spec.block;
1 efrain 5557
        side += (block && !spec.inlineOrder)
1441 ariadna 5558
            ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -4e8 /* Side.BlockBefore */)
5559
            : (side > 0 ? 100000000 /* Side.InlineAfter */ : -1e8 /* Side.InlineBefore */);
1 efrain 5560
        return new PointDecoration(spec, side, side, block, spec.widget || null, false);
5561
    }
5562
    /**
5563
    Create a replace decoration which replaces the given range with
5564
    a widget, or simply hides it.
5565
    */
5566
    static replace(spec) {
5567
        let block = !!spec.block, startSide, endSide;
5568
        if (spec.isBlockGap) {
1441 ariadna 5569
            startSide = -5e8 /* Side.GapStart */;
1 efrain 5570
            endSide = 400000000 /* Side.GapEnd */;
5571
        }
5572
        else {
5573
            let { start, end } = getInclusive(spec, block);
1441 ariadna 5574
            startSide = (start ? (block ? -3e8 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;
5575
            endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -6e8 /* Side.NonIncEnd */) + 1;
1 efrain 5576
        }
5577
        return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
5578
    }
5579
    /**
5580
    Create a line decoration, which can add DOM attributes to the
5581
    line starting at the given position.
5582
    */
5583
    static line(spec) {
5584
        return new LineDecoration(spec);
5585
    }
5586
    /**
5587
    Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
5588
    decorated range or ranges. If the ranges aren't already sorted,
5589
    pass `true` for `sort` to make the library sort them for you.
5590
    */
5591
    static set(of, sort = false) {
5592
        return RangeSet.of(of, sort);
5593
    }
5594
    /**
5595
    @internal
5596
    */
5597
    hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }
5598
}
5599
/**
5600
The empty set of decorations.
5601
*/
5602
Decoration.none = RangeSet.empty;
5603
class MarkDecoration extends Decoration {
5604
    constructor(spec) {
5605
        let { start, end } = getInclusive(spec);
1441 ariadna 5606
        super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -6e8 /* Side.NonIncEnd */, null, spec);
1 efrain 5607
        this.tagName = spec.tagName || "span";
5608
        this.class = spec.class || "";
5609
        this.attrs = spec.attributes || null;
5610
    }
5611
    eq(other) {
5612
        var _a, _b;
5613
        return this == other ||
5614
            other instanceof MarkDecoration &&
5615
                this.tagName == other.tagName &&
5616
                (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)) &&
5617
                attrsEq(this.attrs, other.attrs, "class");
5618
    }
5619
    range(from, to = from) {
5620
        if (from >= to)
5621
            throw new RangeError("Mark decorations may not be empty");
5622
        return super.range(from, to);
5623
    }
5624
}
5625
MarkDecoration.prototype.point = false;
5626
class LineDecoration extends Decoration {
5627
    constructor(spec) {
1441 ariadna 5628
        super(-2e8 /* Side.Line */, -2e8 /* Side.Line */, null, spec);
1 efrain 5629
    }
5630
    eq(other) {
5631
        return other instanceof LineDecoration &&
5632
            this.spec.class == other.spec.class &&
5633
            attrsEq(this.spec.attributes, other.spec.attributes);
5634
    }
5635
    range(from, to = from) {
5636
        if (to != from)
5637
            throw new RangeError("Line decoration ranges must be zero-length");
5638
        return super.range(from, to);
5639
    }
5640
}
5641
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
5642
LineDecoration.prototype.point = true;
5643
class PointDecoration extends Decoration {
5644
    constructor(spec, startSide, endSide, block, widget, isReplace) {
5645
        super(startSide, endSide, widget, spec);
5646
        this.block = block;
5647
        this.isReplace = isReplace;
5648
        this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
5649
    }
5650
    // Only relevant when this.block == true
5651
    get type() {
5652
        return this.startSide != this.endSide ? BlockType.WidgetRange
5653
            : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
5654
    }
5655
    get heightRelevant() {
5656
        return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
5657
    }
5658
    eq(other) {
5659
        return other instanceof PointDecoration &&
5660
            widgetsEq(this.widget, other.widget) &&
5661
            this.block == other.block &&
5662
            this.startSide == other.startSide && this.endSide == other.endSide;
5663
    }
5664
    range(from, to = from) {
5665
        if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))
5666
            throw new RangeError("Invalid range for replacement decoration");
5667
        if (!this.isReplace && to != from)
5668
            throw new RangeError("Widget decorations can only have zero-length ranges");
5669
        return super.range(from, to);
5670
    }
5671
}
5672
PointDecoration.prototype.point = true;
5673
function getInclusive(spec, block = false) {
5674
    let { inclusiveStart: start, inclusiveEnd: end } = spec;
5675
    if (start == null)
5676
        start = spec.inclusive;
5677
    if (end == null)
5678
        end = spec.inclusive;
5679
    return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };
5680
}
5681
function widgetsEq(a, b) {
5682
    return a == b || !!(a && b && a.compare(b));
5683
}
5684
function addRange(from, to, ranges, margin = 0) {
5685
    let last = ranges.length - 1;
5686
    if (last >= 0 && ranges[last] + margin >= from)
5687
        ranges[last] = Math.max(ranges[last], to);
5688
    else
5689
        ranges.push(from, to);
5690
}
5691
 
1441 ariadna 5692
class LineView extends ContentView {
5693
    constructor() {
5694
        super(...arguments);
5695
        this.children = [];
5696
        this.length = 0;
5697
        this.prevAttrs = undefined;
5698
        this.attrs = null;
5699
        this.breakAfter = 0;
5700
    }
5701
    // Consumes source
5702
    merge(from, to, source, hasStart, openStart, openEnd) {
5703
        if (source) {
5704
            if (!(source instanceof LineView))
5705
                return false;
5706
            if (!this.dom)
5707
                source.transferDOM(this); // Reuse source.dom when appropriate
5708
        }
5709
        if (hasStart)
5710
            this.setDeco(source ? source.attrs : null);
5711
        mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart, openEnd);
5712
        return true;
5713
    }
5714
    split(at) {
5715
        let end = new LineView;
5716
        end.breakAfter = this.breakAfter;
5717
        if (this.length == 0)
5718
            return end;
5719
        let { i, off } = this.childPos(at);
5720
        if (off) {
5721
            end.append(this.children[i].split(off), 0);
5722
            this.children[i].merge(off, this.children[i].length, null, false, 0, 0);
5723
            i++;
5724
        }
5725
        for (let j = i; j < this.children.length; j++)
5726
            end.append(this.children[j], 0);
5727
        while (i > 0 && this.children[i - 1].length == 0)
5728
            this.children[--i].destroy();
5729
        this.children.length = i;
5730
        this.markDirty();
5731
        this.length = at;
5732
        return end;
5733
    }
5734
    transferDOM(other) {
5735
        if (!this.dom)
5736
            return;
5737
        this.markDirty();
5738
        other.setDOM(this.dom);
5739
        other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;
5740
        this.prevAttrs = undefined;
5741
        this.dom = null;
5742
    }
5743
    setDeco(attrs) {
5744
        if (!attrsEq(this.attrs, attrs)) {
5745
            if (this.dom) {
5746
                this.prevAttrs = this.attrs;
5747
                this.markDirty();
5748
            }
5749
            this.attrs = attrs;
5750
        }
5751
    }
5752
    append(child, openStart) {
5753
        joinInlineInto(this, child, openStart);
5754
    }
5755
    // Only called when building a line view in ContentBuilder
5756
    addLineDeco(deco) {
5757
        let attrs = deco.spec.attributes, cls = deco.spec.class;
5758
        if (attrs)
5759
            this.attrs = combineAttrs(attrs, this.attrs || {});
5760
        if (cls)
5761
            this.attrs = combineAttrs({ class: cls }, this.attrs || {});
5762
    }
5763
    domAtPos(pos) {
5764
        return inlineDOMAtPos(this, pos);
5765
    }
5766
    reuseDOM(node) {
5767
        if (node.nodeName == "DIV") {
5768
            this.setDOM(node);
5769
            this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
5770
        }
5771
    }
5772
    sync(view, track) {
5773
        var _a;
5774
        if (!this.dom) {
5775
            this.setDOM(document.createElement("div"));
5776
            this.dom.className = "cm-line";
5777
            this.prevAttrs = this.attrs ? null : undefined;
5778
        }
5779
        else if (this.flags & 4 /* ViewFlag.AttrsDirty */) {
5780
            clearAttributes(this.dom);
5781
            this.dom.className = "cm-line";
5782
            this.prevAttrs = this.attrs ? null : undefined;
5783
        }
5784
        if (this.prevAttrs !== undefined) {
5785
            updateAttrs(this.dom, this.prevAttrs, this.attrs);
5786
            this.dom.classList.add("cm-line");
5787
            this.prevAttrs = undefined;
5788
        }
5789
        super.sync(view, track);
5790
        let last = this.dom.lastChild;
5791
        while (last && ContentView.get(last) instanceof MarkView)
5792
            last = last.lastChild;
5793
        if (!last || !this.length ||
5794
            last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false &&
5795
                (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {
5796
            let hack = document.createElement("BR");
5797
            hack.cmIgnore = true;
5798
            this.dom.appendChild(hack);
5799
        }
5800
    }
5801
    measureTextSize() {
5802
        if (this.children.length == 0 || this.length > 20)
5803
            return null;
5804
        let totalWidth = 0, textHeight;
5805
        for (let child of this.children) {
5806
            if (!(child instanceof TextView) || /[^ -~]/.test(child.text))
5807
                return null;
5808
            let rects = clientRectsFor(child.dom);
5809
            if (rects.length != 1)
5810
                return null;
5811
            totalWidth += rects[0].width;
5812
            textHeight = rects[0].height;
5813
        }
5814
        return !totalWidth ? null : {
5815
            lineHeight: this.dom.getBoundingClientRect().height,
5816
            charWidth: totalWidth / this.length,
5817
            textHeight
5818
        };
5819
    }
5820
    coordsAt(pos, side) {
5821
        let rect = coordsInChildren(this, pos, side);
5822
        // Correct rectangle height for empty lines when the returned
5823
        // height is larger than the text height.
5824
        if (!this.children.length && rect && this.parent) {
5825
            let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;
5826
            if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
5827
                let dist = (height - heightOracle.textHeight) / 2;
5828
                return { top: rect.top + dist, bottom: rect.bottom - dist, left: rect.left, right: rect.left };
5829
            }
5830
        }
5831
        return rect;
5832
    }
5833
    become(other) {
5834
        return other instanceof LineView && this.children.length == 0 && other.children.length == 0 &&
5835
            attrsEq(this.attrs, other.attrs) && this.breakAfter == other.breakAfter;
5836
    }
5837
    covers() { return true; }
5838
    static find(docView, pos) {
5839
        for (let i = 0, off = 0; i < docView.children.length; i++) {
5840
            let block = docView.children[i], end = off + block.length;
5841
            if (end >= pos) {
5842
                if (block instanceof LineView)
5843
                    return block;
5844
                if (end > pos)
5845
                    break;
5846
            }
5847
            off = end + block.breakAfter;
5848
        }
5849
        return null;
5850
    }
5851
}
5852
class BlockWidgetView extends ContentView {
5853
    constructor(widget, length, deco) {
5854
        super();
5855
        this.widget = widget;
5856
        this.length = length;
5857
        this.deco = deco;
5858
        this.breakAfter = 0;
5859
        this.prevWidget = null;
5860
    }
5861
    merge(from, to, source, _takeDeco, openStart, openEnd) {
5862
        if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||
5863
            from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5864
            return false;
5865
        this.length = from + (source ? source.length : 0) + (this.length - to);
5866
        return true;
5867
    }
5868
    domAtPos(pos) {
5869
        return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
5870
    }
5871
    split(at) {
5872
        let len = this.length - at;
5873
        this.length = at;
5874
        let end = new BlockWidgetView(this.widget, len, this.deco);
5875
        end.breakAfter = this.breakAfter;
5876
        return end;
5877
    }
5878
    get children() { return noChildren; }
5879
    sync(view) {
5880
        if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5881
            if (this.dom && this.prevWidget)
5882
                this.prevWidget.destroy(this.dom);
5883
            this.prevWidget = null;
5884
            this.setDOM(this.widget.toDOM(view));
5885
            if (!this.widget.editable)
5886
                this.dom.contentEditable = "false";
5887
        }
5888
    }
5889
    get overrideDOMText() {
5890
        return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
5891
    }
5892
    domBoundsAround() { return null; }
5893
    become(other) {
5894
        if (other instanceof BlockWidgetView &&
5895
            other.widget.constructor == this.widget.constructor) {
5896
            if (!other.widget.compare(this.widget))
5897
                this.markDirty(true);
5898
            if (this.dom && !this.prevWidget)
5899
                this.prevWidget = this.widget;
5900
            this.widget = other.widget;
5901
            this.length = other.length;
5902
            this.deco = other.deco;
5903
            this.breakAfter = other.breakAfter;
5904
            return true;
5905
        }
5906
        return false;
5907
    }
5908
    ignoreMutation() { return true; }
5909
    ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5910
    get isEditable() { return false; }
5911
    get isWidget() { return true; }
5912
    coordsAt(pos, side) {
5913
        let custom = this.widget.coordsAt(this.dom, pos, side);
5914
        if (custom)
5915
            return custom;
5916
        if (this.widget instanceof BlockGapWidget)
5917
            return null;
5918
        return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0);
5919
    }
5920
    destroy() {
5921
        super.destroy();
5922
        if (this.dom)
5923
            this.widget.destroy(this.dom);
5924
    }
5925
    covers(side) {
5926
        let { startSide, endSide } = this.deco;
5927
        return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
5928
    }
5929
}
5930
class BlockGapWidget extends WidgetType {
5931
    constructor(height) {
5932
        super();
5933
        this.height = height;
5934
    }
5935
    toDOM() {
5936
        let elt = document.createElement("div");
5937
        elt.className = "cm-gap";
5938
        this.updateDOM(elt);
5939
        return elt;
5940
    }
5941
    eq(other) { return other.height == this.height; }
5942
    updateDOM(elt) {
5943
        elt.style.height = this.height + "px";
5944
        return true;
5945
    }
5946
    get editable() { return true; }
5947
    get estimatedHeight() { return this.height; }
5948
    ignoreEvent() { return false; }
5949
}
5950
 
1 efrain 5951
class ContentBuilder {
5952
    constructor(doc, pos, end, disallowBlockEffectsFor) {
5953
        this.doc = doc;
5954
        this.pos = pos;
5955
        this.end = end;
5956
        this.disallowBlockEffectsFor = disallowBlockEffectsFor;
5957
        this.content = [];
5958
        this.curLine = null;
5959
        this.breakAtStart = 0;
5960
        this.pendingBuffer = 0 /* Buf.No */;
5961
        this.bufferMarks = [];
5962
        // Set to false directly after a widget that covers the position after it
5963
        this.atCursorPos = true;
5964
        this.openStart = -1;
5965
        this.openEnd = -1;
5966
        this.text = "";
5967
        this.textOff = 0;
5968
        this.cursor = doc.iter();
5969
        this.skip = pos;
5970
    }
5971
    posCovered() {
5972
        if (this.content.length == 0)
5973
            return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
5974
        let last = this.content[this.content.length - 1];
5975
        return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);
5976
    }
5977
    getLine() {
5978
        if (!this.curLine) {
5979
            this.content.push(this.curLine = new LineView);
5980
            this.atCursorPos = true;
5981
        }
5982
        return this.curLine;
5983
    }
5984
    flushBuffer(active = this.bufferMarks) {
5985
        if (this.pendingBuffer) {
5986
            this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);
5987
            this.pendingBuffer = 0 /* Buf.No */;
5988
        }
5989
    }
5990
    addBlockWidget(view) {
5991
        this.flushBuffer();
5992
        this.curLine = null;
5993
        this.content.push(view);
5994
    }
5995
    finish(openEnd) {
5996
        if (this.pendingBuffer && openEnd <= this.bufferMarks.length)
5997
            this.flushBuffer();
5998
        else
5999
            this.pendingBuffer = 0 /* Buf.No */;
6000
        if (!this.posCovered() &&
6001
            !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))
6002
            this.getLine();
6003
    }
6004
    buildText(length, active, openStart) {
6005
        while (length > 0) {
6006
            if (this.textOff == this.text.length) {
6007
                let { value, lineBreak, done } = this.cursor.next(this.skip);
6008
                this.skip = 0;
6009
                if (done)
6010
                    throw new Error("Ran out of text content when drawing inline views");
6011
                if (lineBreak) {
6012
                    if (!this.posCovered())
6013
                        this.getLine();
6014
                    if (this.content.length)
6015
                        this.content[this.content.length - 1].breakAfter = 1;
6016
                    else
6017
                        this.breakAtStart = 1;
6018
                    this.flushBuffer();
6019
                    this.curLine = null;
6020
                    this.atCursorPos = true;
6021
                    length--;
6022
                    continue;
6023
                }
6024
                else {
6025
                    this.text = value;
6026
                    this.textOff = 0;
6027
                }
6028
            }
6029
            let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */);
6030
            this.flushBuffer(active.slice(active.length - openStart));
6031
            this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
6032
            this.atCursorPos = true;
6033
            this.textOff += take;
6034
            length -= take;
6035
            openStart = 0;
6036
        }
6037
    }
6038
    span(from, to, active, openStart) {
6039
        this.buildText(to - from, active, openStart);
6040
        this.pos = to;
6041
        if (this.openStart < 0)
6042
            this.openStart = openStart;
6043
    }
6044
    point(from, to, deco, active, openStart, index) {
6045
        if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {
6046
            if (deco.block)
6047
                throw new RangeError("Block decorations may not be specified via plugins");
6048
            if (to > this.doc.lineAt(this.pos).to)
6049
                throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
6050
        }
6051
        let len = to - from;
6052
        if (deco instanceof PointDecoration) {
6053
            if (deco.block) {
6054
                if (deco.startSide > 0 && !this.posCovered())
6055
                    this.getLine();
6056
                this.addBlockWidget(new BlockWidgetView(deco.widget || NullWidget.block, len, deco));
6057
            }
6058
            else {
6059
                let view = WidgetView.create(deco.widget || NullWidget.inline, len, len ? 0 : deco.startSide);
6060
                let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length &&
6061
                    (from < to || deco.startSide > 0);
6062
                let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
6063
                let line = this.getLine();
6064
                if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore && !view.isEditable)
6065
                    this.pendingBuffer = 0 /* Buf.No */;
6066
                this.flushBuffer(active);
6067
                if (cursorBefore) {
6068
                    line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
6069
                    openStart = active.length + Math.max(0, openStart - active.length);
6070
                }
6071
                line.append(wrapMarks(view, active), openStart);
6072
                this.atCursorPos = cursorAfter;
6073
                this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to || openStart > active.length ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */;
6074
                if (this.pendingBuffer)
6075
                    this.bufferMarks = active.slice();
6076
            }
6077
        }
6078
        else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration
6079
            this.getLine().addLineDeco(deco);
6080
        }
6081
        if (len) {
6082
            // Advance the iterator past the replaced content
6083
            if (this.textOff + len <= this.text.length) {
6084
                this.textOff += len;
6085
            }
6086
            else {
6087
                this.skip += len - (this.text.length - this.textOff);
6088
                this.text = "";
6089
                this.textOff = 0;
6090
            }
6091
            this.pos = to;
6092
        }
6093
        if (this.openStart < 0)
6094
            this.openStart = openStart;
6095
    }
6096
    static build(text, from, to, decorations, dynamicDecorationMap) {
6097
        let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);
6098
        builder.openEnd = RangeSet.spans(decorations, from, to, builder);
6099
        if (builder.openStart < 0)
6100
            builder.openStart = builder.openEnd;
6101
        builder.finish(builder.openEnd);
6102
        return builder;
6103
    }
6104
}
6105
function wrapMarks(view, active) {
6106
    for (let mark of active)
6107
        view = new MarkView(mark, [view], view.length);
6108
    return view;
6109
}
6110
class NullWidget extends WidgetType {
6111
    constructor(tag) {
6112
        super();
6113
        this.tag = tag;
6114
    }
6115
    eq(other) { return other.tag == this.tag; }
6116
    toDOM() { return document.createElement(this.tag); }
6117
    updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }
6118
    get isHidden() { return true; }
6119
}
6120
NullWidget.inline = /*@__PURE__*/new NullWidget("span");
6121
NullWidget.block = /*@__PURE__*/new NullWidget("div");
6122
 
6123
/**
6124
Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
6125
*/
6126
var Direction = /*@__PURE__*/(function (Direction) {
6127
    // (These are chosen to match the base levels, in bidi algorithm
6128
    // terms, of spans in that direction.)
6129
    /**
6130
    Left-to-right.
6131
    */
6132
    Direction[Direction["LTR"] = 0] = "LTR";
6133
    /**
6134
    Right-to-left.
6135
    */
6136
    Direction[Direction["RTL"] = 1] = "RTL";
6137
return Direction})(Direction || (Direction = {}));
6138
const LTR = Direction.LTR, RTL = Direction.RTL;
6139
// Decode a string with each type encoded as log2(type)
6140
function dec(str) {
6141
    let result = [];
6142
    for (let i = 0; i < str.length; i++)
6143
        result.push(1 << +str[i]);
6144
    return result;
6145
}
6146
// Character types for codepoints 0 to 0xf8
6147
const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
6148
// Character types for codepoints 0x600 to 0x6f9
6149
const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
6150
const Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];
6151
// There's a lot more in
6152
// https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,
6153
// which are left out to keep code size down.
6154
for (let p of ["()", "[]", "{}"]) {
6155
    let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);
6156
    Brackets[l] = r;
6157
    Brackets[r] = -l;
6158
}
6159
function charType(ch) {
6160
    return ch <= 0xf7 ? LowTypes[ch] :
6161
        0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :
6162
            0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
6163
                0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :
6164
                    0x2000 <= ch && ch <= 0x200c ? 256 /* T.NI */ :
6165
                        0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : 1 /* T.L */;
6166
}
6167
const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
6168
/**
6169
Represents a contiguous range of text that has a single direction
6170
(as in left-to-right or right-to-left).
6171
*/
6172
class BidiSpan {
6173
    /**
6174
    The direction of this span.
6175
    */
6176
    get dir() { return this.level % 2 ? RTL : LTR; }
6177
    /**
6178
    @internal
6179
    */
6180
    constructor(
6181
    /**
6182
    The start of the span (relative to the start of the line).
6183
    */
6184
    from,
6185
    /**
6186
    The end of the span.
6187
    */
6188
    to,
6189
    /**
6190
    The ["bidi
6191
    level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)
6192
    of the span (in this context, 0 means
6193
    left-to-right, 1 means right-to-left, 2 means left-to-right
6194
    number inside right-to-left text).
6195
    */
6196
    level) {
6197
        this.from = from;
6198
        this.to = to;
6199
        this.level = level;
6200
    }
6201
    /**
6202
    @internal
6203
    */
6204
    side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }
6205
    /**
6206
    @internal
6207
    */
6208
    forward(forward, dir) { return forward == (this.dir == dir); }
6209
    /**
6210
    @internal
6211
    */
6212
    static find(order, index, level, assoc) {
6213
        let maybe = -1;
6214
        for (let i = 0; i < order.length; i++) {
6215
            let span = order[i];
6216
            if (span.from <= index && span.to >= index) {
6217
                if (span.level == level)
6218
                    return i;
6219
                // When multiple spans match, if assoc != 0, take the one that
6220
                // covers that side, otherwise take the one with the minimum
6221
                // level.
6222
                if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))
6223
                    maybe = i;
6224
            }
6225
        }
6226
        if (maybe < 0)
6227
            throw new RangeError("Index out of range");
6228
        return maybe;
6229
    }
6230
}
6231
function isolatesEq(a, b) {
6232
    if (a.length != b.length)
6233
        return false;
6234
    for (let i = 0; i < a.length; i++) {
6235
        let iA = a[i], iB = b[i];
6236
        if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
6237
            return false;
6238
    }
6239
    return true;
6240
}
6241
// Reused array of character types
6242
const types = [];
6243
// Fill in the character types (in `types`) from `from` to `to` and
6244
// apply W normalization rules.
6245
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
6246
    for (let iI = 0; iI <= isolates.length; iI++) {
6247
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6248
        let prevType = iI ? 256 /* T.NI */ : outerType;
6249
        // W1. Examine each non-spacing mark (NSM) in the level run, and
6250
        // change the type of the NSM to the type of the previous
6251
        // character. If the NSM is at the start of the level run, it will
6252
        // get the type of sor.
6253
        // W2. Search backwards from each instance of a European number
6254
        // until the first strong type (R, L, AL, or sor) is found. If an
6255
        // AL is found, change the type of the European number to Arabic
6256
        // number.
6257
        // W3. Change all ALs to R.
6258
        // (Left after this: L, R, EN, AN, ET, CS, NI)
6259
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6260
            let type = charType(line.charCodeAt(i));
6261
            if (type == 512 /* T.NSM */)
6262
                type = prev;
6263
            else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)
6264
                type = 16 /* T.AN */;
6265
            types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;
6266
            if (type & 7 /* T.Strong */)
6267
                prevStrong = type;
6268
            prev = type;
6269
        }
6270
        // W5. A sequence of European terminators adjacent to European
6271
        // numbers changes to all European numbers.
6272
        // W6. Otherwise, separators and terminators change to Other
6273
        // Neutral.
6274
        // W7. Search backwards from each instance of a European number
6275
        // until the first strong type (R, L, or sor) is found. If an L is
6276
        // found, then change the type of the European number to L.
6277
        // (Left after this: L, R, EN+AN, NI)
6278
        for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6279
            let type = types[i];
6280
            if (type == 128 /* T.CS */) {
6281
                if (i < to - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */))
6282
                    type = types[i] = prev;
6283
                else
6284
                    types[i] = 256 /* T.NI */;
6285
            }
6286
            else if (type == 64 /* T.ET */) {
6287
                let end = i + 1;
6288
                while (end < to && types[end] == 64 /* T.ET */)
6289
                    end++;
6290
                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 */;
6291
                for (let j = i; j < end; j++)
6292
                    types[j] = replace;
6293
                i = end - 1;
6294
            }
6295
            else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {
6296
                types[i] = 1 /* T.L */;
6297
            }
6298
            prev = type;
6299
            if (type & 7 /* T.Strong */)
6300
                prevStrong = type;
6301
        }
6302
    }
6303
}
6304
// Process brackets throughout a run sequence.
6305
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
6306
    let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;
6307
    for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
6308
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6309
        // N0. Process bracket pairs in an isolating run sequence
6310
        // sequentially in the logical order of the text positions of the
6311
        // opening paired brackets using the logic given below. Within this
6312
        // scope, bidirectional types EN and AN are treated as R.
6313
        for (let i = from, ch, br, type; i < to; i++) {
6314
            // Keeps [startIndex, type, strongSeen] triples for each open
6315
            // bracket on BracketStack.
6316
            if (br = Brackets[ch = line.charCodeAt(i)]) {
6317
                if (br < 0) { // Closing bracket
6318
                    for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6319
                        if (BracketStack[sJ + 1] == -br) {
6320
                            let flags = BracketStack[sJ + 2];
6321
                            let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :
6322
                                !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :
6323
                                    (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;
6324
                            if (type)
6325
                                types[i] = types[BracketStack[sJ]] = type;
6326
                            sI = sJ;
6327
                            break;
6328
                        }
6329
                    }
6330
                }
6331
                else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {
6332
                    break;
6333
                }
6334
                else {
6335
                    BracketStack[sI++] = i;
6336
                    BracketStack[sI++] = ch;
6337
                    BracketStack[sI++] = context;
6338
                }
6339
            }
6340
            else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {
6341
                let embed = type == outerType;
6342
                context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;
6343
                for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6344
                    let cur = BracketStack[sJ + 2];
6345
                    if (cur & 2 /* Bracketed.EmbedInside */)
6346
                        break;
6347
                    if (embed) {
6348
                        BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;
6349
                    }
6350
                    else {
6351
                        if (cur & 4 /* Bracketed.OppositeInside */)
6352
                            break;
6353
                        BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;
6354
                    }
6355
                }
6356
            }
6357
        }
6358
    }
6359
}
6360
function processNeutrals(rFrom, rTo, isolates, outerType) {
6361
    for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
6362
        let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6363
        // N1. A sequence of neutrals takes the direction of the
6364
        // surrounding strong text if the text on both sides has the same
6365
        // direction. European and Arabic numbers act as if they were R in
6366
        // terms of their influence on neutrals. Start-of-level-run (sor)
6367
        // and end-of-level-run (eor) are used at level run boundaries.
6368
        // N2. Any remaining neutrals take the embedding direction.
6369
        // (Left after this: L, R, EN+AN)
6370
        for (let i = from; i < to;) {
6371
            let type = types[i];
6372
            if (type == 256 /* T.NI */) {
6373
                let end = i + 1;
6374
                for (;;) {
6375
                    if (end == to) {
6376
                        if (iI == isolates.length)
6377
                            break;
6378
                        end = isolates[iI++].to;
6379
                        to = iI < isolates.length ? isolates[iI].from : rTo;
6380
                    }
6381
                    else if (types[end] == 256 /* T.NI */) {
6382
                        end++;
6383
                    }
6384
                    else {
6385
                        break;
6386
                    }
6387
                }
6388
                let beforeL = prev == 1 /* T.L */;
6389
                let afterL = (end < rTo ? types[end] : outerType) == 1 /* T.L */;
6390
                let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;
6391
                for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {
6392
                    if (j == fromJ) {
6393
                        j = isolates[--jI].from;
6394
                        fromJ = jI ? isolates[jI - 1].to : rFrom;
6395
                    }
6396
                    types[--j] = replace;
6397
                }
6398
                i = end;
6399
            }
6400
            else {
6401
                prev = type;
6402
                i++;
6403
            }
6404
        }
6405
    }
6406
}
6407
// Find the contiguous ranges of character types in a given range, and
6408
// emit spans for them. Flip the order of the spans as appropriate
6409
// based on the level, and call through to compute the spans for
6410
// isolates at the proper point.
6411
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
6412
    let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;
6413
    if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip
6414
        for (let iCh = from, iI = 0; iCh < to;) {
6415
            // Scan a section of characters in direction ourType, unless
6416
            // there's another type of char right after iCh, in which case
6417
            // we scan a section of other characters (which, if ourType ==
6418
            // T.L, may contain both T.R and T.AN chars).
6419
            let sameDir = true, isNum = false;
6420
            if (iI == isolates.length || iCh < isolates[iI].from) {
6421
                let next = types[iCh];
6422
                if (next != ourType) {
6423
                    sameDir = false;
6424
                    isNum = next == 16 /* T.AN */;
6425
                }
6426
            }
6427
            // Holds an array of isolates to pass to a recursive call if we
6428
            // must recurse (to distinguish T.AN inside an RTL section in
6429
            // LTR text), null if we can emit directly
6430
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6431
            let localLevel = sameDir ? level : level + 1;
6432
            let iScan = iCh;
6433
            run: for (;;) {
6434
                if (iI < isolates.length && iScan == isolates[iI].from) {
6435
                    if (isNum)
6436
                        break run;
6437
                    let iso = isolates[iI];
6438
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
6439
                    if (!sameDir)
6440
                        for (let upto = iso.to, jI = iI + 1;;) {
6441
                            if (upto == to)
6442
                                break run;
6443
                            if (jI < isolates.length && isolates[jI].from == upto)
6444
                                upto = isolates[jI++].to;
6445
                            else if (types[upto] == ourType)
6446
                                break run;
6447
                            else
6448
                                break;
6449
                        }
6450
                    iI++;
6451
                    if (recurse) {
6452
                        recurse.push(iso);
6453
                    }
6454
                    else {
6455
                        if (iso.from > iCh)
6456
                            order.push(new BidiSpan(iCh, iso.from, localLevel));
6457
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6458
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6459
                        iCh = iso.to;
6460
                    }
6461
                    iScan = iso.to;
6462
                }
6463
                else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
6464
                    break;
6465
                }
6466
                else {
6467
                    iScan++;
6468
                }
6469
            }
6470
            if (recurse)
6471
                emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
6472
            else if (iCh < iScan)
6473
                order.push(new BidiSpan(iCh, iScan, localLevel));
6474
            iCh = iScan;
6475
        }
6476
    }
6477
    else {
6478
        // Iterate in reverse to flip the span order. Same code again, but
6479
        // going from the back of the section to the front
6480
        for (let iCh = to, iI = isolates.length; iCh > from;) {
6481
            let sameDir = true, isNum = false;
6482
            if (!iI || iCh > isolates[iI - 1].to) {
6483
                let next = types[iCh - 1];
6484
                if (next != ourType) {
6485
                    sameDir = false;
6486
                    isNum = next == 16 /* T.AN */;
6487
                }
6488
            }
6489
            let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6490
            let localLevel = sameDir ? level : level + 1;
6491
            let iScan = iCh;
6492
            run: for (;;) {
6493
                if (iI && iScan == isolates[iI - 1].to) {
6494
                    if (isNum)
6495
                        break run;
6496
                    let iso = isolates[--iI];
6497
                    // Scan ahead to verify that there is another char in this dir after the isolate(s)
6498
                    if (!sameDir)
6499
                        for (let upto = iso.from, jI = iI;;) {
6500
                            if (upto == from)
6501
                                break run;
6502
                            if (jI && isolates[jI - 1].to == upto)
6503
                                upto = isolates[--jI].from;
6504
                            else if (types[upto - 1] == ourType)
6505
                                break run;
6506
                            else
6507
                                break;
6508
                        }
6509
                    if (recurse) {
6510
                        recurse.push(iso);
6511
                    }
6512
                    else {
6513
                        if (iso.to < iCh)
6514
                            order.push(new BidiSpan(iso.to, iCh, localLevel));
6515
                        let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6516
                        computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6517
                        iCh = iso.from;
6518
                    }
6519
                    iScan = iso.from;
6520
                }
6521
                else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
6522
                    break;
6523
                }
6524
                else {
6525
                    iScan--;
6526
                }
6527
            }
6528
            if (recurse)
6529
                emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
6530
            else if (iScan < iCh)
6531
                order.push(new BidiSpan(iScan, iCh, localLevel));
6532
            iCh = iScan;
6533
        }
6534
    }
6535
}
6536
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
6537
    let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);
6538
    computeCharTypes(line, from, to, isolates, outerType);
6539
    processBracketPairs(line, from, to, isolates, outerType);
6540
    processNeutrals(from, to, isolates, outerType);
6541
    emitSpans(line, from, to, level, baseLevel, isolates, order);
6542
}
6543
function computeOrder(line, direction, isolates) {
6544
    if (!line)
6545
        return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
6546
    if (direction == LTR && !isolates.length && !BidiRE.test(line))
6547
        return trivialOrder(line.length);
6548
    if (isolates.length)
6549
        while (line.length > types.length)
6550
            types[types.length] = 256 /* T.NI */; // Make sure types array has no gaps
6551
    let order = [], level = direction == LTR ? 0 : 1;
6552
    computeSectionOrder(line, level, level, isolates, 0, line.length, order);
6553
    return order;
6554
}
6555
function trivialOrder(length) {
6556
    return [new BidiSpan(0, length, 0)];
6557
}
6558
let movedOver = "";
6559
// This implementation moves strictly visually, without concern for a
6560
// traversal visiting every logical position in the string. It will
6561
// still do so for simple input, but situations like multiple isolates
6562
// with the same level next to each other, or text going against the
6563
// main dir at the end of the line, will make some positions
6564
// unreachable with this motion. Each visible cursor position will
6565
// correspond to the lower-level bidi span that touches it.
6566
//
6567
// The alternative would be to solve an order globally for a given
6568
// line, making sure that it includes every position, but that would
6569
// require associating non-canonical (higher bidi span level)
6570
// positions with a given visual position, which is likely to confuse
6571
// people. (And would generally be a lot more complicated.)
6572
function moveVisually(line, order, dir, start, forward) {
6573
    var _a;
6574
    let startIndex = start.head - line.from;
6575
    let spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);
6576
    let span = order[spanI], spanEnd = span.side(forward, dir);
6577
    // End of span
6578
    if (startIndex == spanEnd) {
6579
        let nextI = spanI += forward ? 1 : -1;
6580
        if (nextI < 0 || nextI >= order.length)
6581
            return null;
6582
        span = order[spanI = nextI];
6583
        startIndex = span.side(!forward, dir);
6584
        spanEnd = span.side(forward, dir);
6585
    }
6586
    let nextIndex = findClusterBreak(line.text, startIndex, span.forward(forward, dir));
6587
    if (nextIndex < span.from || nextIndex > span.to)
6588
        nextIndex = spanEnd;
6589
    movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
6590
    let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
6591
    if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level)
6592
        return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
6593
    return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
6594
}
6595
function autoDirection(text, from, to) {
6596
    for (let i = from; i < to; i++) {
6597
        let type = charType(text.charCodeAt(i));
6598
        if (type == 1 /* T.L */)
6599
            return LTR;
6600
        if (type == 2 /* T.R */ || type == 4 /* T.AL */)
6601
            return RTL;
6602
    }
6603
    return LTR;
6604
}
6605
 
6606
const clickAddsSelectionRange = /*@__PURE__*/Facet.define();
6607
const dragMovesSelection$1 = /*@__PURE__*/Facet.define();
6608
const mouseSelectionStyle = /*@__PURE__*/Facet.define();
6609
const exceptionSink = /*@__PURE__*/Facet.define();
6610
const updateListener = /*@__PURE__*/Facet.define();
6611
const inputHandler$1 = /*@__PURE__*/Facet.define();
6612
const focusChangeEffect = /*@__PURE__*/Facet.define();
1441 ariadna 6613
const clipboardInputFilter = /*@__PURE__*/Facet.define();
6614
const clipboardOutputFilter = /*@__PURE__*/Facet.define();
1 efrain 6615
const perLineTextDirection = /*@__PURE__*/Facet.define({
6616
    combine: values => values.some(x => x)
6617
});
6618
const nativeSelectionHidden = /*@__PURE__*/Facet.define({
6619
    combine: values => values.some(x => x)
6620
});
6621
const scrollHandler = /*@__PURE__*/Facet.define();
6622
class ScrollTarget {
6623
    constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5,
6624
    // This data structure is abused to also store precise scroll
6625
    // snapshots, instead of a `scrollIntoView` request. When this
6626
    // flag is `true`, `range` points at a position in the reference
6627
    // line, `yMargin` holds the difference between the top of that
6628
    // line and the top of the editor, and `xMargin` holds the
6629
    // editor's `scrollLeft`.
6630
    isSnapshot = false) {
6631
        this.range = range;
6632
        this.y = y;
6633
        this.x = x;
6634
        this.yMargin = yMargin;
6635
        this.xMargin = xMargin;
6636
        this.isSnapshot = isSnapshot;
6637
    }
6638
    map(changes) {
6639
        return changes.empty ? this :
6640
            new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
6641
    }
6642
    clip(state) {
6643
        return this.range.to <= state.doc.length ? this :
6644
            new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
6645
    }
6646
}
6647
const scrollIntoView$1 = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) });
1441 ariadna 6648
const setEditContextFormatting = /*@__PURE__*/StateEffect.define();
1 efrain 6649
/**
6650
Log or report an unhandled exception in client code. Should
6651
probably only be used by extension code that allows client code to
6652
provide functions, and calls those functions in a context where an
6653
exception can't be propagated to calling code in a reasonable way
6654
(for example when in an event handler).
6655
 
6656
Either calls a handler registered with
6657
[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
6658
`window.onerror`, if defined, or `console.error` (in which case
6659
it'll pass `context`, when given, as first argument).
6660
*/
6661
function logException(state, exception, context) {
6662
    let handler = state.facet(exceptionSink);
6663
    if (handler.length)
6664
        handler[0](exception);
6665
    else if (window.onerror)
6666
        window.onerror(String(exception), context, undefined, undefined, exception);
6667
    else if (context)
6668
        console.error(context + ":", exception);
6669
    else
6670
        console.error(exception);
6671
}
6672
const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true });
6673
let nextPluginID = 0;
6674
const viewPlugin = /*@__PURE__*/Facet.define();
6675
/**
6676
View plugins associate stateful values with a view. They can
6677
influence the way the content is drawn, and are notified of things
6678
that happen in the view.
6679
*/
6680
class ViewPlugin {
6681
    constructor(
6682
    /**
6683
    @internal
6684
    */
6685
    id,
6686
    /**
6687
    @internal
6688
    */
6689
    create,
6690
    /**
6691
    @internal
6692
    */
6693
    domEventHandlers,
6694
    /**
6695
    @internal
6696
    */
6697
    domEventObservers, buildExtensions) {
6698
        this.id = id;
6699
        this.create = create;
6700
        this.domEventHandlers = domEventHandlers;
6701
        this.domEventObservers = domEventObservers;
6702
        this.extension = buildExtensions(this);
6703
    }
6704
    /**
6705
    Define a plugin from a constructor function that creates the
6706
    plugin's value, given an editor view.
6707
    */
6708
    static define(create, spec) {
6709
        const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
6710
        return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {
6711
            let ext = [viewPlugin.of(plugin)];
6712
            if (deco)
6713
                ext.push(decorations.of(view => {
6714
                    let pluginInst = view.plugin(plugin);
6715
                    return pluginInst ? deco(pluginInst) : Decoration.none;
6716
                }));
6717
            if (provide)
6718
                ext.push(provide(plugin));
6719
            return ext;
6720
        });
6721
    }
6722
    /**
6723
    Create a plugin for a class whose constructor takes a single
6724
    editor view as argument.
6725
    */
6726
    static fromClass(cls, spec) {
6727
        return ViewPlugin.define(view => new cls(view), spec);
6728
    }
6729
}
6730
class PluginInstance {
6731
    constructor(spec) {
6732
        this.spec = spec;
6733
        // When starting an update, all plugins have this field set to the
6734
        // update object, indicating they need to be updated. When finished
6735
        // updating, it is set to `false`. Retrieving a plugin that needs to
6736
        // be updated with `view.plugin` forces an eager update.
6737
        this.mustUpdate = null;
6738
        // This is null when the plugin is initially created, but
6739
        // initialized on the first update.
6740
        this.value = null;
6741
    }
6742
    update(view) {
6743
        if (!this.value) {
6744
            if (this.spec) {
6745
                try {
6746
                    this.value = this.spec.create(view);
6747
                }
6748
                catch (e) {
6749
                    logException(view.state, e, "CodeMirror plugin crashed");
6750
                    this.deactivate();
6751
                }
6752
            }
6753
        }
6754
        else if (this.mustUpdate) {
6755
            let update = this.mustUpdate;
6756
            this.mustUpdate = null;
6757
            if (this.value.update) {
6758
                try {
6759
                    this.value.update(update);
6760
                }
6761
                catch (e) {
6762
                    logException(update.state, e, "CodeMirror plugin crashed");
6763
                    if (this.value.destroy)
6764
                        try {
6765
                            this.value.destroy();
6766
                        }
6767
                        catch (_) { }
6768
                    this.deactivate();
6769
                }
6770
            }
6771
        }
6772
        return this;
6773
    }
6774
    destroy(view) {
6775
        var _a;
6776
        if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {
6777
            try {
6778
                this.value.destroy();
6779
            }
6780
            catch (e) {
6781
                logException(view.state, e, "CodeMirror plugin crashed");
6782
            }
6783
        }
6784
    }
6785
    deactivate() {
6786
        this.spec = this.value = null;
6787
    }
6788
}
6789
const editorAttributes = /*@__PURE__*/Facet.define();
6790
const contentAttributes = /*@__PURE__*/Facet.define();
6791
// Provide decorations
6792
const decorations = /*@__PURE__*/Facet.define();
6793
const outerDecorations = /*@__PURE__*/Facet.define();
6794
const atomicRanges = /*@__PURE__*/Facet.define();
6795
const bidiIsolatedRanges = /*@__PURE__*/Facet.define();
6796
function getIsolatedRanges(view, line) {
6797
    let isolates = view.state.facet(bidiIsolatedRanges);
6798
    if (!isolates.length)
6799
        return isolates;
6800
    let sets = isolates.map(i => i instanceof Function ? i(view) : i);
6801
    let result = [];
6802
    RangeSet.spans(sets, line.from, line.to, {
6803
        point() { },
6804
        span(fromDoc, toDoc, active, open) {
6805
            let from = fromDoc - line.from, to = toDoc - line.from;
6806
            let level = result;
6807
            for (let i = active.length - 1; i >= 0; i--, open--) {
6808
                let direction = active[i].spec.bidiIsolate, update;
6809
                if (direction == null)
6810
                    direction = autoDirection(line.text, from, to);
6811
                if (open > 0 && level.length &&
6812
                    (update = level[level.length - 1]).to == from && update.direction == direction) {
6813
                    update.to = to;
6814
                    level = update.inner;
6815
                }
6816
                else {
6817
                    let add = { from, to, direction, inner: [] };
6818
                    level.push(add);
6819
                    level = add.inner;
6820
                }
6821
            }
6822
        }
6823
    });
6824
    return result;
6825
}
6826
const scrollMargins = /*@__PURE__*/Facet.define();
6827
function getScrollMargins(view) {
6828
    let left = 0, right = 0, top = 0, bottom = 0;
6829
    for (let source of view.state.facet(scrollMargins)) {
6830
        let m = source(view);
6831
        if (m) {
6832
            if (m.left != null)
6833
                left = Math.max(left, m.left);
6834
            if (m.right != null)
6835
                right = Math.max(right, m.right);
6836
            if (m.top != null)
6837
                top = Math.max(top, m.top);
6838
            if (m.bottom != null)
6839
                bottom = Math.max(bottom, m.bottom);
6840
        }
6841
    }
6842
    return { left, right, top, bottom };
6843
}
6844
const styleModule = /*@__PURE__*/Facet.define();
6845
class ChangedRange {
6846
    constructor(fromA, toA, fromB, toB) {
6847
        this.fromA = fromA;
6848
        this.toA = toA;
6849
        this.fromB = fromB;
6850
        this.toB = toB;
6851
    }
6852
    join(other) {
6853
        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));
6854
    }
6855
    addToSet(set) {
6856
        let i = set.length, me = this;
6857
        for (; i > 0; i--) {
6858
            let range = set[i - 1];
6859
            if (range.fromA > me.toA)
6860
                continue;
6861
            if (range.toA < me.fromA)
6862
                break;
6863
            me = me.join(range);
6864
            set.splice(i - 1, 1);
6865
        }
6866
        set.splice(i, 0, me);
6867
        return set;
6868
    }
6869
    static extendWithRanges(diff, ranges) {
6870
        if (ranges.length == 0)
6871
            return diff;
6872
        let result = [];
6873
        for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
6874
            let next = dI == diff.length ? null : diff[dI], off = posA - posB;
6875
            let end = next ? next.fromB : 1e9;
6876
            while (rI < ranges.length && ranges[rI] < end) {
6877
                let from = ranges[rI], to = ranges[rI + 1];
6878
                let fromB = Math.max(posB, from), toB = Math.min(end, to);
6879
                if (fromB <= toB)
6880
                    new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
6881
                if (to > end)
6882
                    break;
6883
                else
6884
                    rI += 2;
6885
            }
6886
            if (!next)
6887
                return result;
6888
            new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
6889
            posA = next.toA;
6890
            posB = next.toB;
6891
        }
6892
    }
6893
}
6894
/**
6895
View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
6896
class, which describe what happened, whenever the view is updated.
6897
*/
6898
class ViewUpdate {
6899
    constructor(
6900
    /**
6901
    The editor view that the update is associated with.
6902
    */
6903
    view,
6904
    /**
6905
    The new editor state.
6906
    */
6907
    state,
6908
    /**
6909
    The transactions involved in the update. May be empty.
6910
    */
6911
    transactions) {
6912
        this.view = view;
6913
        this.state = state;
6914
        this.transactions = transactions;
6915
        /**
6916
        @internal
6917
        */
6918
        this.flags = 0;
6919
        this.startState = view.state;
6920
        this.changes = ChangeSet.empty(this.startState.doc.length);
6921
        for (let tr of transactions)
6922
            this.changes = this.changes.compose(tr.changes);
6923
        let changedRanges = [];
6924
        this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
6925
        this.changedRanges = changedRanges;
6926
    }
6927
    /**
6928
    @internal
6929
    */
6930
    static create(view, state, transactions) {
6931
        return new ViewUpdate(view, state, transactions);
6932
    }
6933
    /**
6934
    Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
6935
    [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
6936
    update.
6937
    */
6938
    get viewportChanged() {
6939
        return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;
6940
    }
6941
    /**
1441 ariadna 6942
    Returns true when
6943
    [`viewportChanged`](https://codemirror.net/6/docs/ref/#view.ViewUpdate.viewportChanged) is true
6944
    and the viewport change is not just the result of mapping it in
6945
    response to document changes.
6946
    */
6947
    get viewportMoved() {
6948
        return (this.flags & 8 /* UpdateFlag.ViewportMoved */) > 0;
6949
    }
6950
    /**
1 efrain 6951
    Indicates whether the height of a block element in the editor
6952
    changed in this update.
6953
    */
6954
    get heightChanged() {
6955
        return (this.flags & 2 /* UpdateFlag.Height */) > 0;
6956
    }
6957
    /**
6958
    Returns true when the document was modified or the size of the
6959
    editor, or elements within the editor, changed.
6960
    */
6961
    get geometryChanged() {
1441 ariadna 6962
        return this.docChanged || (this.flags & (16 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;
1 efrain 6963
    }
6964
    /**
6965
    True when this update indicates a focus change.
6966
    */
6967
    get focusChanged() {
6968
        return (this.flags & 1 /* UpdateFlag.Focus */) > 0;
6969
    }
6970
    /**
6971
    Whether the document changed in this update.
6972
    */
6973
    get docChanged() {
6974
        return !this.changes.empty;
6975
    }
6976
    /**
6977
    Whether the selection was explicitly set in this update.
6978
    */
6979
    get selectionSet() {
6980
        return this.transactions.some(tr => tr.selection);
6981
    }
6982
    /**
6983
    @internal
6984
    */
6985
    get empty() { return this.flags == 0 && this.transactions.length == 0; }
6986
}
6987
 
6988
class DocView extends ContentView {
6989
    get length() { return this.view.state.doc.length; }
6990
    constructor(view) {
6991
        super();
6992
        this.view = view;
6993
        this.decorations = [];
1441 ariadna 6994
        this.dynamicDecorationMap = [false];
1 efrain 6995
        this.domChanged = null;
6996
        this.hasComposition = null;
6997
        this.markedForComposition = new Set;
1441 ariadna 6998
        this.editContextFormatting = Decoration.none;
1 efrain 6999
        this.lastCompositionAfterCursor = false;
7000
        // Track a minimum width for the editor. When measuring sizes in
7001
        // measureVisibleLineHeights, this is updated to point at the width
7002
        // of a given element and its extent in the document. When a change
7003
        // happens in that range, these are reset. That way, once we've seen
7004
        // a line/element of a given length, we keep the editor wide enough
7005
        // to fit at least that element, until it is changed, at which point
7006
        // we forget it again.
7007
        this.minWidth = 0;
7008
        this.minWidthFrom = 0;
7009
        this.minWidthTo = 0;
7010
        // Track whether the DOM selection was set in a lossy way, so that
7011
        // we don't mess it up when reading it back it
7012
        this.impreciseAnchor = null;
7013
        this.impreciseHead = null;
7014
        this.forceSelection = false;
7015
        // Used by the resize observer to ignore resizes that we caused
7016
        // ourselves
7017
        this.lastUpdate = Date.now();
7018
        this.setDOM(view.contentDOM);
7019
        this.children = [new LineView];
7020
        this.children[0].setParent(this);
7021
        this.updateDeco();
7022
        this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);
7023
    }
7024
    // Update the document view to a given state.
7025
    update(update) {
7026
        var _a;
7027
        let changedRanges = update.changedRanges;
7028
        if (this.minWidth > 0 && changedRanges.length) {
7029
            if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
7030
                this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
7031
            }
7032
            else {
7033
                this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
7034
                this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
7035
            }
7036
        }
1441 ariadna 7037
        this.updateEditContextFormatting(update);
1 efrain 7038
        let readCompositionAt = -1;
1441 ariadna 7039
        if (this.view.inputState.composing >= 0 && !this.view.observer.editContext) {
1 efrain 7040
            if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)
7041
                readCompositionAt = this.domChanged.newSel.head;
7042
            else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)
7043
                readCompositionAt = update.state.selection.main.head;
7044
        }
7045
        let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
7046
        this.domChanged = null;
7047
        if (this.hasComposition) {
7048
            this.markedForComposition.clear();
7049
            let { from, to } = this.hasComposition;
7050
            changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))
7051
                .addToSet(changedRanges.slice());
7052
        }
7053
        this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
7054
        // When the DOM nodes around the selection are moved to another
7055
        // parent, Chrome sometimes reports a different selection through
7056
        // getSelection than the one that it actually shows to the user.
7057
        // This forces a selection update when lines are joined to work
7058
        // around that. Issue #54
7059
        if ((browser.ie || browser.chrome) && !composition && update &&
7060
            update.state.doc.lines != update.startState.doc.lines)
7061
            this.forceSelection = true;
7062
        let prevDeco = this.decorations, deco = this.updateDeco();
7063
        let decoDiff = findChangedDeco(prevDeco, deco, update.changes);
7064
        changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
7065
        if (!(this.flags & 7 /* ViewFlag.Dirty */) && changedRanges.length == 0) {
7066
            return false;
7067
        }
7068
        else {
7069
            this.updateInner(changedRanges, update.startState.doc.length, composition);
7070
            if (update.transactions.length)
7071
                this.lastUpdate = Date.now();
7072
            return true;
7073
        }
7074
    }
7075
    // Used by update and the constructor do perform the actual DOM
7076
    // update
7077
    updateInner(changes, oldLength, composition) {
7078
        this.view.viewState.mustMeasureContent = true;
7079
        this.updateChildren(changes, oldLength, composition);
7080
        let { observer } = this.view;
7081
        observer.ignore(() => {
7082
            // Lock the height during redrawing, since Chrome sometimes
7083
            // messes with the scroll position during DOM mutation (though
7084
            // no relayout is triggered and I cannot imagine how it can
7085
            // recompute the scroll position without a layout)
7086
            this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
7087
            this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
7088
            // Chrome will sometimes, when DOM mutations occur directly
7089
            // around the selection, get confused and report a different
7090
            // selection from the one it displays (issue #218). This tries
7091
            // to detect that situation.
7092
            let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;
7093
            this.sync(this.view, track);
1441 ariadna 7094
            this.flags &= -8 /* ViewFlag.Dirty */;
1 efrain 7095
            if (track && (track.written || observer.selectionRange.focusNode != track.node))
7096
                this.forceSelection = true;
7097
            this.dom.style.height = "";
7098
        });
1441 ariadna 7099
        this.markedForComposition.forEach(cView => cView.flags &= -9 /* ViewFlag.Composition */);
1 efrain 7100
        let gaps = [];
7101
        if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)
7102
            for (let child of this.children)
7103
                if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)
7104
                    gaps.push(child.dom);
7105
        observer.updateGaps(gaps);
7106
    }
7107
    updateChildren(changes, oldLength, composition) {
7108
        let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
7109
        let cursor = this.childCursor(oldLength);
7110
        for (let i = ranges.length - 1;; i--) {
7111
            let next = i >= 0 ? ranges[i] : null;
7112
            if (!next)
7113
                break;
7114
            let { fromA, toA, fromB, toB } = next, content, breakAtStart, openStart, openEnd;
7115
            if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
7116
                let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
7117
                let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
7118
                breakAtStart = before.breakAtStart;
7119
                openStart = before.openStart;
7120
                openEnd = after.openEnd;
7121
                let compLine = this.compositionView(composition);
7122
                if (after.breakAtStart) {
7123
                    compLine.breakAfter = 1;
7124
                }
7125
                else if (after.content.length &&
7126
                    compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
7127
                    compLine.breakAfter = after.content[0].breakAfter;
7128
                    after.content.shift();
7129
                }
7130
                if (before.content.length &&
7131
                    compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {
7132
                    before.content.pop();
7133
                }
7134
                content = before.content.concat(compLine).concat(after.content);
7135
            }
7136
            else {
7137
                ({ content, breakAtStart, openStart, openEnd } =
7138
                    ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
7139
            }
7140
            let { i: toI, off: toOff } = cursor.findPos(toA, 1);
7141
            let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
7142
            replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);
7143
        }
7144
        if (composition)
7145
            this.fixCompositionDOM(composition);
7146
    }
1441 ariadna 7147
    updateEditContextFormatting(update) {
7148
        this.editContextFormatting = this.editContextFormatting.map(update.changes);
7149
        for (let tr of update.transactions)
7150
            for (let effect of tr.effects)
7151
                if (effect.is(setEditContextFormatting)) {
7152
                    this.editContextFormatting = effect.value;
7153
                }
7154
    }
1 efrain 7155
    compositionView(composition) {
7156
        let cur = new TextView(composition.text.nodeValue);
7157
        cur.flags |= 8 /* ViewFlag.Composition */;
7158
        for (let { deco } of composition.marks)
7159
            cur = new MarkView(deco, [cur], cur.length);
7160
        let line = new LineView;
7161
        line.append(cur, 0);
7162
        return line;
7163
    }
7164
    fixCompositionDOM(composition) {
7165
        let fix = (dom, cView) => {
7166
            cView.flags |= 8 /* ViewFlag.Composition */ | (cView.children.some(c => c.flags & 7 /* ViewFlag.Dirty */) ? 1 /* ViewFlag.ChildDirty */ : 0);
7167
            this.markedForComposition.add(cView);
7168
            let prev = ContentView.get(dom);
7169
            if (prev && prev != cView)
7170
                prev.dom = null;
7171
            cView.setDOM(dom);
7172
        };
7173
        let pos = this.childPos(composition.range.fromB, 1);
7174
        let cView = this.children[pos.i];
7175
        fix(composition.line, cView);
7176
        for (let i = composition.marks.length - 1; i >= -1; i--) {
7177
            pos = cView.childPos(pos.off, 1);
7178
            cView = cView.children[pos.i];
7179
            fix(i >= 0 ? composition.marks[i].node : composition.text, cView);
7180
        }
7181
    }
7182
    // Sync the DOM selection to this.state.selection
7183
    updateSelection(mustRead = false, fromPointer = false) {
7184
        if (mustRead || !this.view.observer.selectionRange.focusNode)
7185
            this.view.observer.readSelectionRange();
7186
        let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;
1441 ariadna 7187
        let selectionNotFocus = !focused && !(this.view.state.facet(editable) || this.dom.tabIndex > -1) &&
1 efrain 7188
            hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
7189
        if (!(focused || fromPointer || selectionNotFocus))
7190
            return;
7191
        let force = this.forceSelection;
7192
        this.forceSelection = false;
7193
        let main = this.view.state.selection.main;
7194
        let anchor = this.moveToLine(this.domAtPos(main.anchor));
7195
        let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
7196
        // Always reset on Firefox when next to an uneditable node to
7197
        // avoid invisible cursor bugs (#111)
7198
        if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
7199
            let dummy = document.createTextNode("");
7200
            this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
7201
            anchor = head = new DOMPos(dummy, 0);
7202
            force = true;
7203
        }
7204
        let domSel = this.view.observer.selectionRange;
7205
        // If the selection is already here, or in an equivalent position, don't touch it
7206
        if (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||
7207
            !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
7208
            this.view.observer.ignore(() => {
7209
                // Chrome Android will hide the virtual keyboard when tapping
7210
                // inside an uneditable node, and not bring it back when we
7211
                // move the cursor to its proper position. This tries to
7212
                // restore the keyboard by cycling focus.
7213
                if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) &&
7214
                    inUneditable(domSel.focusNode, this.dom)) {
7215
                    this.dom.blur();
7216
                    this.dom.focus({ preventScroll: true });
7217
                }
7218
                let rawSel = getSelection(this.view.root);
7219
                if (!rawSel) ;
7220
                else if (main.empty) {
7221
                    // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076
7222
                    if (browser.gecko) {
7223
                        let nextTo = nextToUneditable(anchor.node, anchor.offset);
7224
                        if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {
7225
                            let text = (nextTo == 1 /* NextTo.Before */ ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
7226
                            if (text)
7227
                                anchor = new DOMPos(text.node, text.offset);
7228
                        }
7229
                    }
7230
                    rawSel.collapse(anchor.node, anchor.offset);
7231
                    if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)
7232
                        rawSel.caretBidiLevel = main.bidiLevel;
7233
                }
7234
                else if (rawSel.extend) {
7235
                    // Selection.extend can be used to create an 'inverted' selection
7236
                    // (one where the focus is before the anchor), but not all
7237
                    // browsers support it yet.
7238
                    rawSel.collapse(anchor.node, anchor.offset);
7239
                    // Safari will ignore the call above when the editor is
7240
                    // hidden, and then raise an error on the call to extend
7241
                    // (#940).
7242
                    try {
7243
                        rawSel.extend(head.node, head.offset);
7244
                    }
7245
                    catch (_) { }
7246
                }
7247
                else {
7248
                    // Primitive (IE) way
7249
                    let range = document.createRange();
7250
                    if (main.anchor > main.head)
7251
                        [anchor, head] = [head, anchor];
7252
                    range.setEnd(head.node, head.offset);
7253
                    range.setStart(anchor.node, anchor.offset);
7254
                    rawSel.removeAllRanges();
7255
                    rawSel.addRange(range);
7256
                }
7257
                if (selectionNotFocus && this.view.root.activeElement == this.dom) {
7258
                    this.dom.blur();
7259
                    if (activeElt)
7260
                        activeElt.focus();
7261
                }
7262
            });
7263
            this.view.observer.setSelectionRange(anchor, head);
7264
        }
7265
        this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
7266
        this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
7267
    }
7268
    // If a zero-length widget is inserted next to the cursor during
7269
    // composition, avoid moving it across it and disrupting the
7270
    // composition.
7271
    suppressWidgetCursorChange(sel, cursor) {
7272
        return this.hasComposition && cursor.empty &&
7273
            isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) &&
7274
            this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
7275
    }
7276
    enforceCursorAssoc() {
7277
        if (this.hasComposition)
7278
            return;
7279
        let { view } = this, cursor = view.state.selection.main;
7280
        let sel = getSelection(view.root);
7281
        let { anchorNode, anchorOffset } = view.observer.selectionRange;
7282
        if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
7283
            return;
7284
        let line = LineView.find(this, cursor.head);
7285
        if (!line)
7286
            return;
7287
        let lineStart = line.posAtStart;
7288
        if (cursor.head == lineStart || cursor.head == lineStart + line.length)
7289
            return;
7290
        let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
7291
        if (!before || !after || before.bottom > after.top)
7292
            return;
7293
        let dom = this.domAtPos(cursor.head + cursor.assoc);
7294
        sel.collapse(dom.node, dom.offset);
7295
        sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
7296
        // This can go wrong in corner cases like single-character lines,
7297
        // so check and reset if necessary.
7298
        view.observer.readSelectionRange();
7299
        let newRange = view.observer.selectionRange;
7300
        if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
7301
            sel.collapse(anchorNode, anchorOffset);
7302
    }
7303
    // If a position is in/near a block widget, move it to a nearby text
7304
    // line, since we don't want the cursor inside a block widget.
7305
    moveToLine(pos) {
7306
        // Block widgets will return positions before/after them, which
7307
        // are thus directly in the document DOM element.
7308
        let dom = this.dom, newPos;
7309
        if (pos.node != dom)
7310
            return pos;
7311
        for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {
7312
            let view = ContentView.get(dom.childNodes[i]);
7313
            if (view instanceof LineView)
7314
                newPos = view.domAtPos(0);
7315
        }
7316
        for (let i = pos.offset - 1; !newPos && i >= 0; i--) {
7317
            let view = ContentView.get(dom.childNodes[i]);
7318
            if (view instanceof LineView)
7319
                newPos = view.domAtPos(view.length);
7320
        }
7321
        return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;
7322
    }
7323
    nearest(dom) {
7324
        for (let cur = dom; cur;) {
7325
            let domView = ContentView.get(cur);
7326
            if (domView && domView.rootView == this)
7327
                return domView;
7328
            cur = cur.parentNode;
7329
        }
7330
        return null;
7331
    }
7332
    posFromDOM(node, offset) {
7333
        let view = this.nearest(node);
7334
        if (!view)
7335
            throw new RangeError("Trying to find position for a DOM position outside of the document");
7336
        return view.localPosFromDOM(node, offset) + view.posAtStart;
7337
    }
7338
    domAtPos(pos) {
7339
        let { i, off } = this.childCursor().findPos(pos, -1);
7340
        for (; i < this.children.length - 1;) {
7341
            let child = this.children[i];
7342
            if (off < child.length || child instanceof LineView)
7343
                break;
7344
            i++;
7345
            off = 0;
7346
        }
7347
        return this.children[i].domAtPos(off);
7348
    }
7349
    coordsAt(pos, side) {
7350
        let best = null, bestPos = 0;
7351
        for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {
7352
            let child = this.children[i], end = off - child.breakAfter, start = end - child.length;
7353
            if (end < pos)
7354
                break;
7355
            if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) &&
7356
                (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
7357
                best = child;
7358
                bestPos = start;
7359
            }
1441 ariadna 7360
            else if (best && start == pos && end == pos && child instanceof BlockWidgetView && Math.abs(side) < 2) {
7361
                if (child.deco.startSide < 0)
7362
                    break;
7363
                else if (i)
7364
                    best = null;
7365
            }
1 efrain 7366
            off = start;
7367
        }
7368
        return best ? best.coordsAt(pos - bestPos, side) : null;
7369
    }
7370
    coordsForChar(pos) {
7371
        let { i, off } = this.childPos(pos, 1), child = this.children[i];
7372
        if (!(child instanceof LineView))
7373
            return null;
7374
        while (child.children.length) {
7375
            let { i, off: childOff } = child.childPos(off, 1);
7376
            for (;; i++) {
7377
                if (i == child.children.length)
7378
                    return null;
7379
                if ((child = child.children[i]).length)
7380
                    break;
7381
            }
7382
            off = childOff;
7383
        }
7384
        if (!(child instanceof TextView))
7385
            return null;
7386
        let end = findClusterBreak(child.text, off);
7387
        if (end == off)
7388
            return null;
7389
        let rects = textRange(child.dom, off, end).getClientRects();
7390
        for (let i = 0; i < rects.length; i++) {
7391
            let rect = rects[i];
7392
            if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
7393
                return rect;
7394
        }
7395
        return null;
7396
    }
7397
    measureVisibleLineHeights(viewport) {
7398
        let result = [], { from, to } = viewport;
7399
        let contentWidth = this.view.contentDOM.clientWidth;
7400
        let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
7401
        let widest = -1, ltr = this.view.textDirection == Direction.LTR;
7402
        for (let pos = 0, i = 0; i < this.children.length; i++) {
7403
            let child = this.children[i], end = pos + child.length;
7404
            if (end > to)
7405
                break;
7406
            if (pos >= from) {
7407
                let childRect = child.dom.getBoundingClientRect();
7408
                result.push(childRect.height);
7409
                if (isWider) {
7410
                    let last = child.dom.lastChild;
7411
                    let rects = last ? clientRectsFor(last) : [];
7412
                    if (rects.length) {
7413
                        let rect = rects[rects.length - 1];
7414
                        let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
7415
                        if (width > widest) {
7416
                            widest = width;
7417
                            this.minWidth = contentWidth;
7418
                            this.minWidthFrom = pos;
7419
                            this.minWidthTo = end;
7420
                        }
7421
                    }
7422
                }
7423
            }
7424
            pos = end + child.breakAfter;
7425
        }
7426
        return result;
7427
    }
7428
    textDirectionAt(pos) {
7429
        let { i } = this.childPos(pos, 1);
7430
        return getComputedStyle(this.children[i].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
7431
    }
7432
    measureTextSize() {
7433
        for (let child of this.children) {
7434
            if (child instanceof LineView) {
7435
                let measure = child.measureTextSize();
7436
                if (measure)
7437
                    return measure;
7438
            }
7439
        }
7440
        // If no workable line exists, force a layout of a measurable element
7441
        let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
7442
        dummy.className = "cm-line";
7443
        dummy.style.width = "99999px";
7444
        dummy.style.position = "absolute";
7445
        dummy.textContent = "abc def ghi jkl mno pqr stu";
7446
        this.view.observer.ignore(() => {
7447
            this.dom.appendChild(dummy);
7448
            let rect = clientRectsFor(dummy.firstChild)[0];
7449
            lineHeight = dummy.getBoundingClientRect().height;
7450
            charWidth = rect ? rect.width / 27 : 7;
7451
            textHeight = rect ? rect.height : lineHeight;
7452
            dummy.remove();
7453
        });
7454
        return { lineHeight, charWidth, textHeight };
7455
    }
7456
    childCursor(pos = this.length) {
7457
        // Move back to start of last element when possible, so that
7458
        // `ChildCursor.findPos` doesn't have to deal with the edge case
7459
        // of being after the last element.
7460
        let i = this.children.length;
7461
        if (i)
7462
            pos -= this.children[--i].length;
7463
        return new ChildCursor(this.children, pos, i);
7464
    }
7465
    computeBlockGapDeco() {
7466
        let deco = [], vs = this.view.viewState;
7467
        for (let pos = 0, i = 0;; i++) {
7468
            let next = i == vs.viewports.length ? null : vs.viewports[i];
7469
            let end = next ? next.from - 1 : this.length;
7470
            if (end > pos) {
7471
                let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
7472
                deco.push(Decoration.replace({
7473
                    widget: new BlockGapWidget(height),
7474
                    block: true,
7475
                    inclusive: true,
7476
                    isBlockGap: true,
7477
                }).range(pos, end));
7478
            }
7479
            if (!next)
7480
                break;
7481
            pos = next.to + 1;
7482
        }
7483
        return Decoration.set(deco);
7484
    }
7485
    updateDeco() {
1441 ariadna 7486
        let i = 1;
1 efrain 7487
        let allDeco = this.view.state.facet(decorations).map(d => {
7488
            let dynamic = this.dynamicDecorationMap[i++] = typeof d == "function";
7489
            return dynamic ? d(this.view) : d;
7490
        });
7491
        let dynamicOuter = false, outerDeco = this.view.state.facet(outerDecorations).map((d, i) => {
7492
            let dynamic = typeof d == "function";
7493
            if (dynamic)
7494
                dynamicOuter = true;
7495
            return dynamic ? d(this.view) : d;
7496
        });
7497
        if (outerDeco.length) {
7498
            this.dynamicDecorationMap[i++] = dynamicOuter;
7499
            allDeco.push(RangeSet.join(outerDeco));
7500
        }
7501
        this.decorations = [
1441 ariadna 7502
            this.editContextFormatting,
1 efrain 7503
            ...allDeco,
7504
            this.computeBlockGapDeco(),
7505
            this.view.viewState.lineGapDeco
7506
        ];
7507
        while (i < this.decorations.length)
7508
            this.dynamicDecorationMap[i++] = false;
7509
        return this.decorations;
7510
    }
7511
    scrollIntoView(target) {
7512
        if (target.isSnapshot) {
7513
            let ref = this.view.viewState.lineBlockAt(target.range.head);
7514
            this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
7515
            this.view.scrollDOM.scrollLeft = target.xMargin;
7516
            return;
7517
        }
7518
        for (let handler of this.view.state.facet(scrollHandler)) {
7519
            try {
7520
                if (handler(this.view, target.range, target))
7521
                    return true;
7522
            }
7523
            catch (e) {
7524
                logException(this.view.state, e, "scroll handler");
7525
            }
7526
        }
7527
        let { range } = target;
7528
        let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
7529
        if (!rect)
7530
            return;
7531
        if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
7532
            rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),
7533
                right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };
7534
        let margins = getScrollMargins(this.view);
7535
        let targetRect = {
7536
            left: rect.left - margins.left, top: rect.top - margins.top,
7537
            right: rect.right + margins.right, bottom: rect.bottom + margins.bottom
7538
        };
7539
        let { offsetWidth, offsetHeight } = this.view.scrollDOM;
7540
        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);
7541
    }
7542
}
7543
function betweenUneditable(pos) {
7544
    return pos.node.nodeType == 1 && pos.node.firstChild &&
7545
        (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") &&
7546
        (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
7547
}
7548
function findCompositionNode(view, headPos) {
7549
    let sel = view.observer.selectionRange;
7550
    if (!sel.focusNode)
7551
        return null;
7552
    let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
7553
    let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
7554
    let textNode = textBefore || textAfter;
7555
    if (textAfter && textBefore && textAfter.node != textBefore.node) {
7556
        let descAfter = ContentView.get(textAfter.node);
7557
        if (!descAfter || descAfter instanceof TextView && descAfter.text != textAfter.node.nodeValue) {
7558
            textNode = textAfter;
7559
        }
7560
        else if (view.docView.lastCompositionAfterCursor) {
7561
            let descBefore = ContentView.get(textBefore.node);
7562
            if (!(!descBefore || descBefore instanceof TextView && descBefore.text != textBefore.node.nodeValue))
7563
                textNode = textAfter;
7564
        }
7565
    }
7566
    view.docView.lastCompositionAfterCursor = textNode != textBefore;
7567
    if (!textNode)
7568
        return null;
7569
    let from = headPos - textNode.offset;
7570
    return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
7571
}
7572
function findCompositionRange(view, changes, headPos) {
7573
    let found = findCompositionNode(view, headPos);
7574
    if (!found)
7575
        return null;
7576
    let { node: textNode, from, to } = found, text = textNode.nodeValue;
7577
    // Don't try to preserve multi-line compositions
7578
    if (/[\n\r]/.test(text))
7579
        return null;
7580
    if (view.state.doc.sliceString(found.from, found.to) != text)
7581
        return null;
7582
    let inv = changes.invertedDesc;
7583
    let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
7584
    let marks = [];
7585
    for (let parent = textNode.parentNode;; parent = parent.parentNode) {
7586
        let parentView = ContentView.get(parent);
7587
        if (parentView instanceof MarkView)
7588
            marks.push({ node: parent, deco: parentView.mark });
7589
        else if (parentView instanceof LineView || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM)
7590
            return { range, text: textNode, marks, line: parent };
7591
        else if (parent != view.contentDOM)
7592
            marks.push({ node: parent, deco: new MarkDecoration({
7593
                    inclusive: true,
7594
                    attributes: getAttrs$1(parent),
7595
                    tagName: parent.tagName.toLowerCase()
7596
                }) });
7597
        else
7598
            return null;
7599
    }
7600
}
7601
function nextToUneditable(node, offset) {
7602
    if (node.nodeType != 1)
7603
        return 0;
7604
    return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) |
7605
        (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0);
7606
}
7607
let DecorationComparator$1 = class DecorationComparator {
7608
    constructor() {
7609
        this.changes = [];
7610
    }
7611
    compareRange(from, to) { addRange(from, to, this.changes); }
7612
    comparePoint(from, to) { addRange(from, to, this.changes); }
1441 ariadna 7613
    boundChange(pos) { addRange(pos, pos, this.changes); }
1 efrain 7614
};
7615
function findChangedDeco(a, b, diff) {
7616
    let comp = new DecorationComparator$1;
7617
    RangeSet.compare(a, b, diff, comp);
7618
    return comp.changes;
7619
}
7620
function inUneditable(node, inside) {
7621
    for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {
7622
        if (cur.nodeType == 1 && cur.contentEditable == 'false') {
7623
            return true;
7624
        }
7625
    }
7626
    return false;
7627
}
7628
function touchesComposition(changes, composition) {
7629
    let touched = false;
7630
    if (composition)
7631
        changes.iterChangedRanges((from, to) => {
7632
            if (from < composition.to && to > composition.from)
7633
                touched = true;
7634
        });
7635
    return touched;
7636
}
7637
 
7638
function groupAt(state, pos, bias = 1) {
7639
    let categorize = state.charCategorizer(pos);
7640
    let line = state.doc.lineAt(pos), linePos = pos - line.from;
7641
    if (line.length == 0)
7642
        return EditorSelection.cursor(pos);
7643
    if (linePos == 0)
7644
        bias = 1;
7645
    else if (linePos == line.length)
7646
        bias = -1;
7647
    let from = linePos, to = linePos;
7648
    if (bias < 0)
7649
        from = findClusterBreak(line.text, linePos, false);
7650
    else
7651
        to = findClusterBreak(line.text, linePos);
7652
    let cat = categorize(line.text.slice(from, to));
7653
    while (from > 0) {
7654
        let prev = findClusterBreak(line.text, from, false);
7655
        if (categorize(line.text.slice(prev, from)) != cat)
7656
            break;
7657
        from = prev;
7658
    }
7659
    while (to < line.length) {
7660
        let next = findClusterBreak(line.text, to);
7661
        if (categorize(line.text.slice(to, next)) != cat)
7662
            break;
7663
        to = next;
7664
    }
7665
    return EditorSelection.range(from + line.from, to + line.from);
7666
}
7667
// Search the DOM for the {node, offset} position closest to the given
7668
// coordinates. Very inefficient and crude, but can usually be avoided
7669
// by calling caret(Position|Range)FromPoint instead.
7670
function getdx(x, rect) {
7671
    return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
7672
}
7673
function getdy(y, rect) {
7674
    return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
7675
}
7676
function yOverlap(a, b) {
7677
    return a.top < b.bottom - 1 && a.bottom > b.top + 1;
7678
}
7679
function upTop(rect, top) {
7680
    return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
7681
}
7682
function upBot(rect, bottom) {
7683
    return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;
7684
}
7685
function domPosAtCoords(parent, x, y) {
7686
    let closest, closestRect, closestX, closestY, closestOverlap = false;
7687
    let above, below, aboveRect, belowRect;
7688
    for (let child = parent.firstChild; child; child = child.nextSibling) {
7689
        let rects = clientRectsFor(child);
7690
        for (let i = 0; i < rects.length; i++) {
7691
            let rect = rects[i];
7692
            if (closestRect && yOverlap(closestRect, rect))
7693
                rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
7694
            let dx = getdx(x, rect), dy = getdy(y, rect);
7695
            if (dx == 0 && dy == 0)
7696
                return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);
7697
            if (!closest || closestY > dy || closestY == dy && closestX > dx) {
7698
                closest = child;
7699
                closestRect = rect;
7700
                closestX = dx;
7701
                closestY = dy;
7702
                let side = dy ? (y < rect.top ? -1 : 1) : dx ? (x < rect.left ? -1 : 1) : 0;
7703
                closestOverlap = !side || (side > 0 ? i < rects.length - 1 : i > 0);
7704
            }
7705
            if (dx == 0) {
7706
                if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
7707
                    above = child;
7708
                    aboveRect = rect;
7709
                }
7710
                else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
7711
                    below = child;
7712
                    belowRect = rect;
7713
                }
7714
            }
7715
            else if (aboveRect && yOverlap(aboveRect, rect)) {
7716
                aboveRect = upBot(aboveRect, rect.bottom);
7717
            }
7718
            else if (belowRect && yOverlap(belowRect, rect)) {
7719
                belowRect = upTop(belowRect, rect.top);
7720
            }
7721
        }
7722
    }
7723
    if (aboveRect && aboveRect.bottom >= y) {
7724
        closest = above;
7725
        closestRect = aboveRect;
7726
    }
7727
    else if (belowRect && belowRect.top <= y) {
7728
        closest = below;
7729
        closestRect = belowRect;
7730
    }
7731
    if (!closest)
7732
        return { node: parent, offset: 0 };
7733
    let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
7734
    if (closest.nodeType == 3)
7735
        return domPosInText(closest, clipX, y);
7736
    if (closestOverlap && closest.contentEditable != "false")
7737
        return domPosAtCoords(closest, clipX, y);
7738
    let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +
7739
        (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
7740
    return { node: parent, offset };
7741
}
7742
function domPosInText(node, x, y) {
7743
    let len = node.nodeValue.length;
7744
    let closestOffset = -1, closestDY = 1e9, generalSide = 0;
7745
    for (let i = 0; i < len; i++) {
7746
        let rects = textRange(node, i, i + 1).getClientRects();
7747
        for (let j = 0; j < rects.length; j++) {
7748
            let rect = rects[j];
7749
            if (rect.top == rect.bottom)
7750
                continue;
7751
            if (!generalSide)
7752
                generalSide = x - rect.left;
7753
            let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
7754
            if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {
7755
                let right = x >= (rect.left + rect.right) / 2, after = right;
7756
                if (browser.chrome || browser.gecko) {
7757
                    // Check for RTL on browsers that support getting client
7758
                    // rects for empty ranges.
7759
                    let rectBefore = textRange(node, i).getBoundingClientRect();
7760
                    if (rectBefore.left == rect.right)
7761
                        after = !right;
7762
                }
7763
                if (dy <= 0)
7764
                    return { node, offset: i + (after ? 1 : 0) };
7765
                closestOffset = i + (after ? 1 : 0);
7766
                closestDY = dy;
7767
            }
7768
        }
7769
    }
7770
    return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };
7771
}
7772
function posAtCoords(view, coords, precise, bias = -1) {
7773
    var _a, _b;
7774
    let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;
7775
    let block, { docHeight } = view.viewState;
7776
    let { x, y } = coords, yOffset = y - docTop;
7777
    if (yOffset < 0)
7778
        return 0;
7779
    if (yOffset > docHeight)
7780
        return view.state.doc.length;
7781
    // Scan for a text block near the queried y position
7782
    for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {
7783
        block = view.elementAtHeight(yOffset);
7784
        if (block.type == BlockType.Text)
7785
            break;
7786
        for (;;) {
7787
            // Move the y position out of this block
7788
            yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
7789
            if (yOffset >= 0 && yOffset <= docHeight)
7790
                break;
7791
            // If the document consists entirely of replaced widgets, we
7792
            // won't find a text block, so return 0
7793
            if (bounced)
7794
                return precise ? null : 0;
7795
            bounced = true;
7796
            bias = -bias;
7797
        }
7798
    }
7799
    y = docTop + yOffset;
7800
    let lineStart = block.from;
7801
    // If this is outside of the rendered viewport, we can't determine a position
7802
    if (lineStart < view.viewport.from)
7803
        return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7804
    if (lineStart > view.viewport.to)
7805
        return view.viewport.to == view.state.doc.length ? view.state.doc.length :
7806
            precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7807
    // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not
7808
    let doc = view.dom.ownerDocument;
7809
    let root = view.root.elementFromPoint ? view.root : doc;
7810
    let element = root.elementFromPoint(x, y);
7811
    if (element && !view.contentDOM.contains(element))
7812
        element = null;
7813
    // If the element is unexpected, clip x at the sides of the content area and try again
7814
    if (!element) {
7815
        x = Math.max(content.left + 1, Math.min(content.right - 1, x));
7816
        element = root.elementFromPoint(x, y);
7817
        if (element && !view.contentDOM.contains(element))
7818
            element = null;
7819
    }
7820
    // There's visible editor content under the point, so we can try
7821
    // using caret(Position|Range)FromPoint as a shortcut
7822
    let node, offset = -1;
7823
    if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) {
7824
        if (doc.caretPositionFromPoint) {
7825
            let pos = doc.caretPositionFromPoint(x, y);
7826
            if (pos)
7827
                ({ offsetNode: node, offset } = pos);
7828
        }
7829
        else if (doc.caretRangeFromPoint) {
7830
            let range = doc.caretRangeFromPoint(x, y);
7831
            if (range) {
7832
                ({ startContainer: node, startOffset: offset } = range);
7833
                if (!view.contentDOM.contains(node) ||
7834
                    browser.safari && isSuspiciousSafariCaretResult(node, offset, x) ||
7835
                    browser.chrome && isSuspiciousChromeCaretResult(node, offset, x))
7836
                    node = undefined;
7837
            }
7838
        }
1441 ariadna 7839
        // Chrome will return offsets into <input> elements without child
7840
        // nodes, which will lead to a null deref below, so clip the
7841
        // offset to the node size.
7842
        if (node)
7843
            offset = Math.min(maxOffset(node), offset);
1 efrain 7844
    }
7845
    // No luck, do our own (potentially expensive) search
7846
    if (!node || !view.docView.dom.contains(node)) {
7847
        let line = LineView.find(view.docView, lineStart);
7848
        if (!line)
7849
            return yOffset > block.top + block.height / 2 ? block.to : block.from;
7850
        ({ node, offset } = domPosAtCoords(line.dom, x, y));
7851
    }
7852
    let nearest = view.docView.nearest(node);
7853
    if (!nearest)
7854
        return null;
7855
    if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
7856
        let rect = nearest.dom.getBoundingClientRect();
7857
        return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2
7858
            ? nearest.posAtStart : nearest.posAtEnd;
7859
    }
7860
    else {
7861
        return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
7862
    }
7863
}
7864
function posAtCoordsImprecise(view, contentRect, block, x, y) {
7865
    let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
7866
    if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
7867
        let textHeight = view.viewState.heightOracle.textHeight;
7868
        let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
7869
        into += line * view.viewState.heightOracle.lineLength;
7870
    }
7871
    let content = view.state.sliceDoc(block.from, block.to);
7872
    return block.from + findColumn(content, into, view.state.tabSize);
7873
}
7874
// In case of a high line height, Safari's caretRangeFromPoint treats
7875
// the space between lines as belonging to the last character of the
7876
// line before. This is used to detect such a result so that it can be
7877
// ignored (issue #401).
7878
function isSuspiciousSafariCaretResult(node, offset, x) {
7879
    let len;
7880
    if (node.nodeType != 3 || offset != (len = node.nodeValue.length))
7881
        return false;
7882
    for (let next = node.nextSibling; next; next = next.nextSibling)
7883
        if (next.nodeType != 1 || next.nodeName != "BR")
7884
            return false;
7885
    return textRange(node, len - 1, len).getBoundingClientRect().left > x;
7886
}
7887
// Chrome will move positions between lines to the start of the next line
7888
function isSuspiciousChromeCaretResult(node, offset, x) {
7889
    if (offset != 0)
7890
        return false;
7891
    for (let cur = node;;) {
7892
        let parent = cur.parentNode;
7893
        if (!parent || parent.nodeType != 1 || parent.firstChild != cur)
7894
            return false;
7895
        if (parent.classList.contains("cm-line"))
7896
            break;
7897
        cur = parent;
7898
    }
7899
    let rect = node.nodeType == 1 ? node.getBoundingClientRect()
7900
        : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();
7901
    return x - rect.left > 5;
7902
}
7903
function blockAt(view, pos) {
7904
    let line = view.lineBlockAt(pos);
7905
    if (Array.isArray(line.type))
7906
        for (let l of line.type) {
7907
            if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text))
7908
                return l;
7909
        }
7910
    return line;
7911
}
7912
function moveToLineBoundary(view, start, forward, includeWrap) {
7913
    let line = blockAt(view, start.head);
7914
    let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null
7915
        : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
7916
    if (coords) {
7917
        let editorRect = view.dom.getBoundingClientRect();
7918
        let direction = view.textDirectionAt(line.from);
7919
        let pos = view.posAtCoords({ x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
7920
            y: (coords.top + coords.bottom) / 2 });
7921
        if (pos != null)
7922
            return EditorSelection.cursor(pos, forward ? -1 : 1);
7923
    }
7924
    return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
7925
}
7926
function moveByChar(view, start, forward, by) {
7927
    let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
7928
    let direction = view.textDirectionAt(line.from);
7929
    for (let cur = start, check = null;;) {
7930
        let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;
7931
        if (!next) {
7932
            if (line.number == (forward ? view.state.doc.lines : 1))
7933
                return cur;
7934
            char = "\n";
7935
            line = view.state.doc.line(line.number + (forward ? 1 : -1));
7936
            spans = view.bidiSpans(line);
7937
            next = view.visualLineSide(line, !forward);
7938
        }
7939
        if (!check) {
7940
            if (!by)
7941
                return next;
7942
            check = by(char);
7943
        }
7944
        else if (!check(char)) {
7945
            return cur;
7946
        }
7947
        cur = next;
7948
    }
7949
}
7950
function byGroup(view, pos, start) {
7951
    let categorize = view.state.charCategorizer(pos);
7952
    let cat = categorize(start);
7953
    return (next) => {
7954
        let nextCat = categorize(next);
7955
        if (cat == CharCategory.Space)
7956
            cat = nextCat;
7957
        return cat == nextCat;
7958
    };
7959
}
7960
function moveVertically(view, start, forward, distance) {
7961
    let startPos = start.head, dir = forward ? 1 : -1;
7962
    if (startPos == (forward ? view.state.doc.length : 0))
7963
        return EditorSelection.cursor(startPos, start.assoc);
7964
    let goal = start.goalColumn, startY;
7965
    let rect = view.contentDOM.getBoundingClientRect();
7966
    let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
7967
    if (startCoords) {
7968
        if (goal == null)
7969
            goal = startCoords.left - rect.left;
7970
        startY = dir < 0 ? startCoords.top : startCoords.bottom;
7971
    }
7972
    else {
7973
        let line = view.viewState.lineBlockAt(startPos);
7974
        if (goal == null)
7975
            goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
7976
        startY = (dir < 0 ? line.top : line.bottom) + docTop;
7977
    }
7978
    let resolvedGoal = rect.left + goal;
7979
    let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);
7980
    for (let extra = 0;; extra += 10) {
7981
        let curY = startY + (dist + extra) * dir;
7982
        let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
7983
        if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
7984
            let charRect = view.docView.coordsForChar(pos);
7985
            let assoc = !charRect || curY < charRect.top ? -1 : 1;
7986
            return EditorSelection.cursor(pos, assoc, undefined, goal);
7987
        }
7988
    }
7989
}
7990
function skipAtomicRanges(atoms, pos, bias) {
7991
    for (;;) {
7992
        let moved = 0;
7993
        for (let set of atoms) {
7994
            set.between(pos - 1, pos + 1, (from, to, value) => {
7995
                if (pos > from && pos < to) {
7996
                    let side = moved || bias || (pos - from < to - pos ? -1 : 1);
7997
                    pos = side < 0 ? from : to;
7998
                    moved = side;
7999
                }
8000
            });
8001
        }
8002
        if (!moved)
8003
            return pos;
8004
    }
8005
}
8006
function skipAtoms(view, oldPos, pos) {
8007
    let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
8008
    return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
8009
}
8010
 
1441 ariadna 8011
const LineBreakPlaceholder = "\uffff";
8012
class DOMReader {
8013
    constructor(points, state) {
8014
        this.points = points;
8015
        this.text = "";
8016
        this.lineSeparator = state.facet(EditorState.lineSeparator);
8017
    }
8018
    append(text) {
8019
        this.text += text;
8020
    }
8021
    lineBreak() {
8022
        this.text += LineBreakPlaceholder;
8023
    }
8024
    readRange(start, end) {
8025
        if (!start)
8026
            return this;
8027
        let parent = start.parentNode;
8028
        for (let cur = start;;) {
8029
            this.findPointBefore(parent, cur);
8030
            let oldLen = this.text.length;
8031
            this.readNode(cur);
8032
            let next = cur.nextSibling;
8033
            if (next == end)
8034
                break;
8035
            let view = ContentView.get(cur), nextView = ContentView.get(next);
8036
            if (view && nextView ? view.breakAfter :
8037
                (view ? view.breakAfter : isBlockElement(cur)) ||
8038
                    (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore) && this.text.length > oldLen))
8039
                this.lineBreak();
8040
            cur = next;
8041
        }
8042
        this.findPointBefore(parent, end);
8043
        return this;
8044
    }
8045
    readTextNode(node) {
8046
        let text = node.nodeValue;
8047
        for (let point of this.points)
8048
            if (point.node == node)
8049
                point.pos = this.text.length + Math.min(point.offset, text.length);
8050
        for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
8051
            let nextBreak = -1, breakSize = 1, m;
8052
            if (this.lineSeparator) {
8053
                nextBreak = text.indexOf(this.lineSeparator, off);
8054
                breakSize = this.lineSeparator.length;
8055
            }
8056
            else if (m = re.exec(text)) {
8057
                nextBreak = m.index;
8058
                breakSize = m[0].length;
8059
            }
8060
            this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
8061
            if (nextBreak < 0)
8062
                break;
8063
            this.lineBreak();
8064
            if (breakSize > 1)
8065
                for (let point of this.points)
8066
                    if (point.node == node && point.pos > this.text.length)
8067
                        point.pos -= breakSize - 1;
8068
            off = nextBreak + breakSize;
8069
        }
8070
    }
8071
    readNode(node) {
8072
        if (node.cmIgnore)
8073
            return;
8074
        let view = ContentView.get(node);
8075
        let fromView = view && view.overrideDOMText;
8076
        if (fromView != null) {
8077
            this.findPointInside(node, fromView.length);
8078
            for (let i = fromView.iter(); !i.next().done;) {
8079
                if (i.lineBreak)
8080
                    this.lineBreak();
8081
                else
8082
                    this.append(i.value);
8083
            }
8084
        }
8085
        else if (node.nodeType == 3) {
8086
            this.readTextNode(node);
8087
        }
8088
        else if (node.nodeName == "BR") {
8089
            if (node.nextSibling)
8090
                this.lineBreak();
8091
        }
8092
        else if (node.nodeType == 1) {
8093
            this.readRange(node.firstChild, null);
8094
        }
8095
    }
8096
    findPointBefore(node, next) {
8097
        for (let point of this.points)
8098
            if (point.node == node && node.childNodes[point.offset] == next)
8099
                point.pos = this.text.length;
8100
    }
8101
    findPointInside(node, length) {
8102
        for (let point of this.points)
8103
            if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
8104
                point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
8105
    }
8106
}
8107
function isAtEnd(parent, node, offset) {
8108
    for (;;) {
8109
        if (!node || offset < maxOffset(node))
8110
            return false;
8111
        if (node == parent)
8112
            return true;
8113
        offset = domIndex(node) + 1;
8114
        node = node.parentNode;
8115
    }
8116
}
8117
class DOMPoint {
8118
    constructor(node, offset) {
8119
        this.node = node;
8120
        this.offset = offset;
8121
        this.pos = -1;
8122
    }
8123
}
8124
 
8125
class DOMChange {
8126
    constructor(view, start, end, typeOver) {
8127
        this.typeOver = typeOver;
8128
        this.bounds = null;
8129
        this.text = "";
8130
        this.domChanged = start > -1;
8131
        let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
8132
        if (view.state.readOnly && start > -1) {
8133
            // Ignore changes when the editor is read-only
8134
            this.newSel = null;
8135
        }
8136
        else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
8137
            let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
8138
            let reader = new DOMReader(selPoints, view.state);
8139
            reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
8140
            this.text = reader.text;
8141
            this.newSel = selectionFromPoints(selPoints, this.bounds.from);
8142
        }
8143
        else {
8144
            let domSel = view.observer.selectionRange;
8145
            let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||
8146
                !contains(view.contentDOM, domSel.focusNode)
8147
                ? view.state.selection.main.head
8148
                : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
8149
            let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||
8150
                !contains(view.contentDOM, domSel.anchorNode)
8151
                ? view.state.selection.main.anchor
8152
                : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
8153
            // iOS will refuse to select the block gaps when doing
8154
            // select-all.
8155
            // Chrome will put the selection *inside* them, confusing
8156
            // posFromDOM
8157
            let vp = view.viewport;
8158
            if ((browser.ios || browser.chrome) && view.state.selection.main.empty && head != anchor &&
8159
                (vp.from > 0 || vp.to < view.state.doc.length)) {
8160
                let from = Math.min(head, anchor), to = Math.max(head, anchor);
8161
                let offFrom = vp.from - from, offTo = vp.to - to;
8162
                if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
8163
                    head = 0;
8164
                    anchor = view.state.doc.length;
8165
                }
8166
            }
8167
            this.newSel = EditorSelection.single(anchor, head);
8168
        }
8169
    }
8170
}
8171
function applyDOMChange(view, domChange) {
8172
    let change;
8173
    let { newSel } = domChange, sel = view.state.selection.main;
8174
    let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
8175
    if (domChange.bounds) {
8176
        let { from, to } = domChange.bounds;
8177
        let preferredPos = sel.from, preferredSide = null;
8178
        // Prefer anchoring to end when Backspace is pressed (or, on
8179
        // Android, when something was deleted)
8180
        if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
8181
            preferredPos = sel.to;
8182
            preferredSide = "end";
8183
        }
8184
        let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
8185
        if (diff) {
8186
            // Chrome inserts two newlines when pressing shift-enter at the
8187
            // end of a line. DomChange drops one of those.
8188
            if (browser.chrome && lastKey == 13 &&
8189
                diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
8190
                diff.toB--;
8191
            change = { from: from + diff.from, to: from + diff.toA,
8192
                insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };
8193
        }
8194
    }
8195
    else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
8196
        newSel = null;
8197
    }
8198
    if (!change && !newSel)
8199
        return false;
8200
    if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
8201
        // Heuristic to notice typing over a selected character
8202
        change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
8203
    }
8204
    else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&
8205
        /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
8206
        // Detect insert-period-on-double-space Mac and Android behavior,
8207
        // and transform it into a regular space insert.
8208
        if (newSel && change.insert.length == 2)
8209
            newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
8210
        change = { from: change.from, to: change.to, insert: Text.of([change.insert.toString().replace(".", " ")]) };
8211
    }
8212
    else if (change && change.from >= sel.from && change.to <= sel.to &&
8213
        (change.from != sel.from || change.to != sel.to) &&
8214
        (sel.to - sel.from) - (change.to - change.from) <= 4) {
8215
        // If the change is inside the selection and covers most of it,
8216
        // assume it is a selection replace (with identical characters at
8217
        // the start/end not included in the diff)
8218
        change = {
8219
            from: sel.from, to: sel.to,
8220
            insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
8221
        };
8222
    }
8223
    else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&
8224
        change.insert.toString() == "\n " && view.lineWrapping) {
8225
        // In Chrome, if you insert a space at the start of a wrapped
8226
        // line, it will actually insert a newline and a space, causing a
8227
        // bogus new line to be created in CodeMirror (#968)
8228
        if (newSel)
8229
            newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
8230
        change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
8231
    }
8232
    if (change) {
8233
        return applyDOMChangeInner(view, change, newSel, lastKey);
8234
    }
8235
    else if (newSel && !newSel.main.eq(sel)) {
8236
        let scrollIntoView = false, userEvent = "select";
8237
        if (view.inputState.lastSelectionTime > Date.now() - 50) {
8238
            if (view.inputState.lastSelectionOrigin == "select")
8239
                scrollIntoView = true;
8240
            userEvent = view.inputState.lastSelectionOrigin;
8241
        }
8242
        view.dispatch({ selection: newSel, scrollIntoView, userEvent });
8243
        return true;
8244
    }
8245
    else {
8246
        return false;
8247
    }
8248
}
8249
function applyDOMChangeInner(view, change, newSel, lastKey = -1) {
8250
    if (browser.ios && view.inputState.flushIOSKey(change))
8251
        return true;
8252
    let sel = view.state.selection.main;
8253
    // Android browsers don't fire reasonable key events for enter,
8254
    // backspace, or delete. So this detects changes that look like
8255
    // they're caused by those keys, and reinterprets them as key
8256
    // events. (Some of these keys are also handled by beforeinput
8257
    // events and the pendingAndroidKey mechanism, but that's not
8258
    // reliable in all situations.)
8259
    if (browser.android &&
8260
        ((change.to == sel.to &&
8261
            // GBoard will sometimes remove a space it just inserted
8262
            // after a completion when you press enter
8263
            (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") &&
8264
            change.insert.length == 1 && change.insert.lines == 2 &&
8265
            dispatchKey(view.contentDOM, "Enter", 13)) ||
8266
            ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||
8267
                lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&
8268
                dispatchKey(view.contentDOM, "Backspace", 8)) ||
8269
            (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&
8270
                dispatchKey(view.contentDOM, "Delete", 46))))
8271
        return true;
8272
    let text = change.insert.toString();
8273
    if (view.inputState.composing >= 0)
8274
        view.inputState.composing++;
8275
    let defaultTr;
8276
    let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
8277
    if (!view.state.facet(inputHandler$1).some(h => h(view, change.from, change.to, text, defaultInsert)))
8278
        view.dispatch(defaultInsert());
8279
    return true;
8280
}
8281
function applyDefaultInsert(view, change, newSel) {
8282
    let tr, startState = view.state, sel = startState.selection.main;
8283
    if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&
8284
        (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&
8285
        view.inputState.composing < 0) {
8286
        let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
8287
        let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
8288
        tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));
8289
    }
8290
    else {
8291
        let changes = startState.changes(change);
8292
        let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;
8293
        // Try to apply a composition change to all cursors
8294
        if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 &&
8295
            change.to <= sel.to && change.to >= sel.to - 10) {
8296
            let replaced = view.state.sliceDoc(change.from, change.to);
8297
            let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
8298
            if (composition) {
8299
                let dLen = change.insert.length - (change.to - change.from);
8300
                compositionRange = { from: composition.from, to: composition.to - dLen };
8301
            }
8302
            else {
8303
                compositionRange = view.state.doc.lineAt(sel.head);
8304
            }
8305
            let offset = sel.to - change.to, size = sel.to - sel.from;
8306
            tr = startState.changeByRange(range => {
8307
                if (range.from == sel.from && range.to == sel.to)
8308
                    return { changes, range: mainSel || range.map(changes) };
8309
                let to = range.to - offset, from = to - replaced.length;
8310
                if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced ||
8311
                    // Unfortunately, there's no way to make multiple
8312
                    // changes in the same node work without aborting
8313
                    // composition, so cursors in the composition range are
8314
                    // ignored.
8315
                    range.to >= compositionRange.from && range.from <= compositionRange.to)
8316
                    return { range };
8317
                let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;
8318
                return {
8319
                    changes: rangeChanges,
8320
                    range: !mainSel ? range.map(rangeChanges) :
8321
                        EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
8322
                };
8323
            });
8324
        }
8325
        else {
8326
            tr = {
8327
                changes,
8328
                selection: mainSel && startState.selection.replaceRange(mainSel)
8329
            };
8330
        }
8331
    }
8332
    let userEvent = "input.type";
8333
    if (view.composing ||
8334
        view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
8335
        view.inputState.compositionPendingChange = false;
8336
        userEvent += ".compose";
8337
        if (view.inputState.compositionFirstChange) {
8338
            userEvent += ".start";
8339
            view.inputState.compositionFirstChange = false;
8340
        }
8341
    }
8342
    return startState.update(tr, { userEvent, scrollIntoView: true });
8343
}
8344
function findDiff(a, b, preferredPos, preferredSide) {
8345
    let minLen = Math.min(a.length, b.length);
8346
    let from = 0;
8347
    while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
8348
        from++;
8349
    if (from == minLen && a.length == b.length)
8350
        return null;
8351
    let toA = a.length, toB = b.length;
8352
    while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
8353
        toA--;
8354
        toB--;
8355
    }
8356
    if (preferredSide == "end") {
8357
        let adjust = Math.max(0, from - Math.min(toA, toB));
8358
        preferredPos -= toA + adjust - from;
8359
    }
8360
    if (toA < from && a.length < b.length) {
8361
        let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
8362
        from -= move;
8363
        toB = from + (toB - toA);
8364
        toA = from;
8365
    }
8366
    else if (toB < from) {
8367
        let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
8368
        from -= move;
8369
        toA = from + (toA - toB);
8370
        toB = from;
8371
    }
8372
    return { from, toA, toB };
8373
}
8374
function selectionPoints(view) {
8375
    let result = [];
8376
    if (view.root.activeElement != view.contentDOM)
8377
        return result;
8378
    let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
8379
    if (anchorNode) {
8380
        result.push(new DOMPoint(anchorNode, anchorOffset));
8381
        if (focusNode != anchorNode || focusOffset != anchorOffset)
8382
            result.push(new DOMPoint(focusNode, focusOffset));
8383
    }
8384
    return result;
8385
}
8386
function selectionFromPoints(points, base) {
8387
    if (points.length == 0)
8388
        return null;
8389
    let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
8390
    return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null;
8391
}
8392
 
1 efrain 8393
class InputState {
8394
    setSelectionOrigin(origin) {
8395
        this.lastSelectionOrigin = origin;
8396
        this.lastSelectionTime = Date.now();
8397
    }
8398
    constructor(view) {
8399
        this.view = view;
8400
        this.lastKeyCode = 0;
8401
        this.lastKeyTime = 0;
8402
        this.lastTouchTime = 0;
8403
        this.lastFocusTime = 0;
8404
        this.lastScrollTop = 0;
8405
        this.lastScrollLeft = 0;
8406
        // On iOS, some keys need to have their default behavior happen
8407
        // (after which we retroactively handle them and reset the DOM) to
8408
        // avoid messing up the virtual keyboard state.
8409
        this.pendingIOSKey = undefined;
1441 ariadna 8410
        /**
8411
        When enabled (>-1), tab presses are not given to key handlers,
8412
        leaving the browser's default behavior. If >0, the mode expires
8413
        at that timestamp, and any other keypress clears it.
8414
        Esc enables temporary tab focus mode for two seconds when not
8415
        otherwise handled.
8416
        */
8417
        this.tabFocusMode = -1;
1 efrain 8418
        this.lastSelectionOrigin = null;
8419
        this.lastSelectionTime = 0;
8420
        this.lastContextMenu = 0;
8421
        this.scrollHandlers = [];
8422
        this.handlers = Object.create(null);
8423
        // -1 means not in a composition. Otherwise, this counts the number
8424
        // of changes made during the composition. The count is used to
8425
        // avoid treating the start state of the composition, before any
8426
        // changes have been made, as part of the composition.
8427
        this.composing = -1;
8428
        // Tracks whether the next change should be marked as starting the
8429
        // composition (null means no composition, true means next is the
8430
        // first, false means first has already been marked for this
8431
        // composition)
8432
        this.compositionFirstChange = null;
8433
        // End time of the previous composition
8434
        this.compositionEndedAt = 0;
8435
        // Used in a kludge to detect when an Enter keypress should be
8436
        // considered part of the composition on Safari, which fires events
8437
        // in the wrong order
8438
        this.compositionPendingKey = false;
8439
        // Used to categorize changes as part of a composition, even when
8440
        // the mutation events fire shortly after the compositionend event
8441
        this.compositionPendingChange = false;
8442
        this.mouseSelection = null;
8443
        // When a drag from the editor is active, this points at the range
8444
        // being dragged.
8445
        this.draggedContent = null;
8446
        this.handleEvent = this.handleEvent.bind(this);
8447
        this.notifiedFocused = view.hasFocus;
8448
        // On Safari adding an input event handler somehow prevents an
8449
        // issue where the composition vanishes when you press enter.
8450
        if (browser.safari)
8451
            view.contentDOM.addEventListener("input", () => null);
8452
        if (browser.gecko)
8453
            firefoxCopyCutHack(view.contentDOM.ownerDocument);
8454
    }
8455
    handleEvent(event) {
8456
        if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
8457
            return;
8458
        if (event.type == "keydown" && this.keydown(event))
8459
            return;
1441 ariadna 8460
        if (this.view.updateState != 0 /* UpdateState.Idle */)
8461
            Promise.resolve().then(() => this.runHandlers(event.type, event));
8462
        else
8463
            this.runHandlers(event.type, event);
1 efrain 8464
    }
8465
    runHandlers(type, event) {
8466
        let handlers = this.handlers[type];
8467
        if (handlers) {
8468
            for (let observer of handlers.observers)
8469
                observer(this.view, event);
8470
            for (let handler of handlers.handlers) {
8471
                if (event.defaultPrevented)
8472
                    break;
8473
                if (handler(this.view, event)) {
8474
                    event.preventDefault();
8475
                    break;
8476
                }
8477
            }
8478
        }
8479
    }
8480
    ensureHandlers(plugins) {
8481
        let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
8482
        for (let type in handlers)
8483
            if (type != "scroll") {
8484
                let passive = !handlers[type].handlers.length;
8485
                let exists = prev[type];
8486
                if (exists && passive != !exists.handlers.length) {
8487
                    dom.removeEventListener(type, this.handleEvent);
8488
                    exists = null;
8489
                }
8490
                if (!exists)
8491
                    dom.addEventListener(type, this.handleEvent, { passive });
8492
            }
8493
        for (let type in prev)
8494
            if (type != "scroll" && !handlers[type])
8495
                dom.removeEventListener(type, this.handleEvent);
8496
        this.handlers = handlers;
8497
    }
8498
    keydown(event) {
8499
        // Must always run, even if a custom handler handled the event
8500
        this.lastKeyCode = event.keyCode;
8501
        this.lastKeyTime = Date.now();
1441 ariadna 8502
        if (event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode))
1 efrain 8503
            return true;
1441 ariadna 8504
        if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
8505
            this.tabFocusMode = -1;
1 efrain 8506
        // Chrome for Android usually doesn't fire proper key events, but
8507
        // occasionally does, usually surrounded by a bunch of complicated
8508
        // composition changes. When an enter or backspace key event is
8509
        // seen, hold off on handling DOM events for a bit, and then
8510
        // dispatch it.
8511
        if (browser.android && browser.chrome && !event.synthetic &&
8512
            (event.keyCode == 13 || event.keyCode == 8)) {
8513
            this.view.observer.delayAndroidKey(event.key, event.keyCode);
8514
            return true;
8515
        }
8516
        // Preventing the default behavior of Enter on iOS makes the
8517
        // virtual keyboard get stuck in the wrong (lowercase)
8518
        // state. So we let it go through, and then, in
8519
        // applyDOMChange, notify key handlers of it and reset to
8520
        // the state they produce.
8521
        let pending;
8522
        if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&
8523
            ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||
8524
                EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
8525
            this.pendingIOSKey = pending || event;
8526
            setTimeout(() => this.flushIOSKey(), 250);
8527
            return true;
8528
        }
8529
        if (event.keyCode != 229)
8530
            this.view.observer.forceFlush();
8531
        return false;
8532
    }
8533
    flushIOSKey(change) {
8534
        let key = this.pendingIOSKey;
8535
        if (!key)
8536
            return false;
8537
        // This looks like an autocorrection before Enter
8538
        if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()))
8539
            return false;
8540
        this.pendingIOSKey = undefined;
8541
        return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : undefined);
8542
    }
8543
    ignoreDuringComposition(event) {
8544
        if (!/^key/.test(event.type))
8545
            return false;
8546
        if (this.composing > 0)
8547
            return true;
8548
        // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
8549
        // On some input method editors (IMEs), the Enter key is used to
8550
        // confirm character selection. On Safari, when Enter is pressed,
8551
        // compositionend and keydown events are sometimes emitted in the
8552
        // wrong order. The key event should still be ignored, even when
8553
        // it happens after the compositionend event.
8554
        if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
8555
            this.compositionPendingKey = false;
8556
            return true;
8557
        }
8558
        return false;
8559
    }
8560
    startMouseSelection(mouseSelection) {
8561
        if (this.mouseSelection)
8562
            this.mouseSelection.destroy();
8563
        this.mouseSelection = mouseSelection;
8564
    }
8565
    update(update) {
1441 ariadna 8566
        this.view.observer.update(update);
1 efrain 8567
        if (this.mouseSelection)
8568
            this.mouseSelection.update(update);
8569
        if (this.draggedContent && update.docChanged)
8570
            this.draggedContent = this.draggedContent.map(update.changes);
8571
        if (update.transactions.length)
8572
            this.lastKeyCode = this.lastSelectionTime = 0;
8573
    }
8574
    destroy() {
8575
        if (this.mouseSelection)
8576
            this.mouseSelection.destroy();
8577
    }
8578
}
8579
function bindHandler(plugin, handler) {
8580
    return (view, event) => {
8581
        try {
8582
            return handler.call(plugin, event, view);
8583
        }
8584
        catch (e) {
8585
            logException(view.state, e);
8586
        }
8587
    };
8588
}
8589
function computeHandlers(plugins) {
8590
    let result = Object.create(null);
8591
    function record(type) {
8592
        return result[type] || (result[type] = { observers: [], handlers: [] });
8593
    }
8594
    for (let plugin of plugins) {
8595
        let spec = plugin.spec;
8596
        if (spec && spec.domEventHandlers)
8597
            for (let type in spec.domEventHandlers) {
8598
                let f = spec.domEventHandlers[type];
8599
                if (f)
8600
                    record(type).handlers.push(bindHandler(plugin.value, f));
8601
            }
8602
        if (spec && spec.domEventObservers)
8603
            for (let type in spec.domEventObservers) {
8604
                let f = spec.domEventObservers[type];
8605
                if (f)
8606
                    record(type).observers.push(bindHandler(plugin.value, f));
8607
            }
8608
    }
8609
    for (let type in handlers)
8610
        record(type).handlers.push(handlers[type]);
8611
    for (let type in observers)
8612
        record(type).observers.push(observers[type]);
8613
    return result;
8614
}
8615
const PendingKeys = [
8616
    { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
8617
    { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
8618
    { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
8619
    { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
8620
];
8621
const EmacsyPendingKeys = "dthko";
8622
// Key codes for modifier keys
8623
const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
8624
const dragScrollMargin = 6;
8625
function dragScrollSpeed(dist) {
8626
    return Math.max(0, dist) * 0.7 + 8;
8627
}
8628
function dist(a, b) {
8629
    return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
8630
}
8631
class MouseSelection {
8632
    constructor(view, startEvent, style, mustSelect) {
8633
        this.view = view;
8634
        this.startEvent = startEvent;
8635
        this.style = style;
8636
        this.mustSelect = mustSelect;
8637
        this.scrollSpeed = { x: 0, y: 0 };
8638
        this.scrolling = -1;
8639
        this.lastEvent = startEvent;
1441 ariadna 8640
        this.scrollParents = scrollableParents(view.contentDOM);
1 efrain 8641
        this.atoms = view.state.facet(atomicRanges).map(f => f(view));
8642
        let doc = view.contentDOM.ownerDocument;
8643
        doc.addEventListener("mousemove", this.move = this.move.bind(this));
8644
        doc.addEventListener("mouseup", this.up = this.up.bind(this));
8645
        this.extend = startEvent.shiftKey;
8646
        this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
8647
        this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
8648
    }
8649
    start(event) {
8650
        // When clicking outside of the selection, immediately apply the
8651
        // effect of starting the selection
8652
        if (this.dragging === false)
8653
            this.select(event);
8654
    }
8655
    move(event) {
8656
        if (event.buttons == 0)
8657
            return this.destroy();
8658
        if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
8659
            return;
8660
        this.select(this.lastEvent = event);
8661
        let sx = 0, sy = 0;
1441 ariadna 8662
        let left = 0, top = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight;
8663
        if (this.scrollParents.x)
8664
            ({ left, right } = this.scrollParents.x.getBoundingClientRect());
8665
        if (this.scrollParents.y)
8666
            ({ top, bottom } = this.scrollParents.y.getBoundingClientRect());
1 efrain 8667
        let margins = getScrollMargins(this.view);
1441 ariadna 8668
        if (event.clientX - margins.left <= left + dragScrollMargin)
8669
            sx = -dragScrollSpeed(left - event.clientX);
8670
        else if (event.clientX + margins.right >= right - dragScrollMargin)
8671
            sx = dragScrollSpeed(event.clientX - right);
8672
        if (event.clientY - margins.top <= top + dragScrollMargin)
8673
            sy = -dragScrollSpeed(top - event.clientY);
8674
        else if (event.clientY + margins.bottom >= bottom - dragScrollMargin)
8675
            sy = dragScrollSpeed(event.clientY - bottom);
1 efrain 8676
        this.setScrollSpeed(sx, sy);
8677
    }
8678
    up(event) {
8679
        if (this.dragging == null)
8680
            this.select(this.lastEvent);
8681
        if (!this.dragging)
8682
            event.preventDefault();
8683
        this.destroy();
8684
    }
8685
    destroy() {
8686
        this.setScrollSpeed(0, 0);
8687
        let doc = this.view.contentDOM.ownerDocument;
8688
        doc.removeEventListener("mousemove", this.move);
8689
        doc.removeEventListener("mouseup", this.up);
8690
        this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
8691
    }
8692
    setScrollSpeed(sx, sy) {
8693
        this.scrollSpeed = { x: sx, y: sy };
8694
        if (sx || sy) {
8695
            if (this.scrolling < 0)
8696
                this.scrolling = setInterval(() => this.scroll(), 50);
8697
        }
8698
        else if (this.scrolling > -1) {
8699
            clearInterval(this.scrolling);
8700
            this.scrolling = -1;
8701
        }
8702
    }
8703
    scroll() {
1441 ariadna 8704
        let { x, y } = this.scrollSpeed;
8705
        if (x && this.scrollParents.x) {
8706
            this.scrollParents.x.scrollLeft += x;
8707
            x = 0;
1 efrain 8708
        }
1441 ariadna 8709
        if (y && this.scrollParents.y) {
8710
            this.scrollParents.y.scrollTop += y;
8711
            y = 0;
1 efrain 8712
        }
1441 ariadna 8713
        if (x || y)
8714
            this.view.win.scrollBy(x, y);
1 efrain 8715
        if (this.dragging === false)
8716
            this.select(this.lastEvent);
8717
    }
8718
    skipAtoms(sel) {
8719
        let ranges = null;
8720
        for (let i = 0; i < sel.ranges.length; i++) {
8721
            let range = sel.ranges[i], updated = null;
8722
            if (range.empty) {
8723
                let pos = skipAtomicRanges(this.atoms, range.from, 0);
8724
                if (pos != range.from)
8725
                    updated = EditorSelection.cursor(pos, -1);
8726
            }
8727
            else {
8728
                let from = skipAtomicRanges(this.atoms, range.from, -1);
8729
                let to = skipAtomicRanges(this.atoms, range.to, 1);
8730
                if (from != range.from || to != range.to)
8731
                    updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
8732
            }
8733
            if (updated) {
8734
                if (!ranges)
8735
                    ranges = sel.ranges.slice();
8736
                ranges[i] = updated;
8737
            }
8738
        }
8739
        return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
8740
    }
8741
    select(event) {
8742
        let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
8743
        if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
8744
            this.view.dispatch({
8745
                selection,
8746
                userEvent: "select.pointer"
8747
            });
8748
        this.mustSelect = false;
8749
    }
8750
    update(update) {
1441 ariadna 8751
        if (update.transactions.some(tr => tr.isUserEvent("input.type")))
8752
            this.destroy();
8753
        else if (this.style.update(update))
1 efrain 8754
            setTimeout(() => this.select(this.lastEvent), 20);
8755
    }
8756
}
8757
function addsSelectionRange(view, event) {
8758
    let facet = view.state.facet(clickAddsSelectionRange);
8759
    return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
8760
}
8761
function dragMovesSelection(view, event) {
8762
    let facet = view.state.facet(dragMovesSelection$1);
8763
    return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
8764
}
8765
function isInPrimarySelection(view, event) {
8766
    let { main } = view.state.selection;
8767
    if (main.empty)
8768
        return false;
8769
    // On boundary clicks, check whether the coordinates are inside the
8770
    // selection's client rectangles
8771
    let sel = getSelection(view.root);
8772
    if (!sel || sel.rangeCount == 0)
8773
        return true;
8774
    let rects = sel.getRangeAt(0).getClientRects();
8775
    for (let i = 0; i < rects.length; i++) {
8776
        let rect = rects[i];
8777
        if (rect.left <= event.clientX && rect.right >= event.clientX &&
8778
            rect.top <= event.clientY && rect.bottom >= event.clientY)
8779
            return true;
8780
    }
8781
    return false;
8782
}
8783
function eventBelongsToEditor(view, event) {
8784
    if (!event.bubbles)
8785
        return true;
8786
    if (event.defaultPrevented)
8787
        return false;
8788
    for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)
8789
        if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))
8790
            return false;
8791
    return true;
8792
}
8793
const handlers = /*@__PURE__*/Object.create(null);
8794
const observers = /*@__PURE__*/Object.create(null);
8795
// This is very crude, but unfortunately both these browsers _pretend_
8796
// that they have a clipboard API—all the objects and methods are
8797
// there, they just don't work, and they are hard to test.
8798
const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
8799
    (browser.ios && browser.webkit_version < 604);
8800
function capturePaste(view) {
8801
    let parent = view.dom.parentNode;
8802
    if (!parent)
8803
        return;
8804
    let target = parent.appendChild(document.createElement("textarea"));
8805
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8806
    target.focus();
8807
    setTimeout(() => {
8808
        view.focus();
8809
        target.remove();
8810
        doPaste(view, target.value);
8811
    }, 50);
8812
}
1441 ariadna 8813
function textFilter(state, facet, text) {
8814
    for (let filter of state.facet(facet))
8815
        text = filter(text, state);
8816
    return text;
8817
}
1 efrain 8818
function doPaste(view, input) {
1441 ariadna 8819
    input = textFilter(view.state, clipboardInputFilter, input);
1 efrain 8820
    let { state } = view, changes, i = 1, text = state.toText(input);
8821
    let byLine = text.lines == state.selection.ranges.length;
8822
    let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();
8823
    if (linewise) {
8824
        let lastLine = -1;
8825
        changes = state.changeByRange(range => {
8826
            let line = state.doc.lineAt(range.from);
8827
            if (line.from == lastLine)
8828
                return { range };
8829
            lastLine = line.from;
8830
            let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);
8831
            return { changes: { from: line.from, insert },
8832
                range: EditorSelection.cursor(range.from + insert.length) };
8833
        });
8834
    }
8835
    else if (byLine) {
8836
        changes = state.changeByRange(range => {
8837
            let line = text.line(i++);
8838
            return { changes: { from: range.from, to: range.to, insert: line.text },
8839
                range: EditorSelection.cursor(range.from + line.length) };
8840
        });
8841
    }
8842
    else {
8843
        changes = state.replaceSelection(text);
8844
    }
8845
    view.dispatch(changes, {
8846
        userEvent: "input.paste",
8847
        scrollIntoView: true
8848
    });
8849
}
8850
observers.scroll = view => {
8851
    view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
8852
    view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
8853
};
8854
handlers.keydown = (view, event) => {
8855
    view.inputState.setSelectionOrigin("select");
1441 ariadna 8856
    if (event.keyCode == 27 && view.inputState.tabFocusMode != 0)
8857
        view.inputState.tabFocusMode = Date.now() + 2000;
1 efrain 8858
    return false;
8859
};
8860
observers.touchstart = (view, e) => {
8861
    view.inputState.lastTouchTime = Date.now();
8862
    view.inputState.setSelectionOrigin("select.pointer");
8863
};
8864
observers.touchmove = view => {
8865
    view.inputState.setSelectionOrigin("select.pointer");
8866
};
8867
handlers.mousedown = (view, event) => {
8868
    view.observer.flush();
8869
    if (view.inputState.lastTouchTime > Date.now() - 2000)
8870
        return false; // Ignore touch interaction
8871
    let style = null;
8872
    for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
8873
        style = makeStyle(view, event);
8874
        if (style)
8875
            break;
8876
    }
8877
    if (!style && event.button == 0)
8878
        style = basicMouseSelection(view, event);
8879
    if (style) {
8880
        let mustFocus = !view.hasFocus;
8881
        view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
8882
        if (mustFocus)
1441 ariadna 8883
            view.observer.ignore(() => {
8884
                focusPreventScroll(view.contentDOM);
8885
                let active = view.root.activeElement;
8886
                if (active && !active.contains(view.contentDOM))
8887
                    active.blur();
8888
            });
1 efrain 8889
        let mouseSel = view.inputState.mouseSelection;
8890
        if (mouseSel) {
8891
            mouseSel.start(event);
8892
            return mouseSel.dragging === false;
8893
        }
8894
    }
8895
    return false;
8896
};
8897
function rangeForClick(view, pos, bias, type) {
8898
    if (type == 1) { // Single click
8899
        return EditorSelection.cursor(pos, bias);
8900
    }
8901
    else if (type == 2) { // Double click
8902
        return groupAt(view.state, pos, bias);
8903
    }
8904
    else { // Triple click
8905
        let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
8906
        let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
8907
        if (to < view.state.doc.length && to == line.to)
8908
            to++;
8909
        return EditorSelection.range(from, to);
8910
    }
8911
}
1441 ariadna 8912
let inside = (x, y, rect) => y >= rect.top && y <= rect.bottom && x >= rect.left && x <= rect.right;
1 efrain 8913
// Try to determine, for the given coordinates, associated with the
8914
// given position, whether they are related to the element before or
8915
// the element after the position.
8916
function findPositionSide(view, pos, x, y) {
8917
    let line = LineView.find(view.docView, pos);
8918
    if (!line)
8919
        return 1;
8920
    let off = pos - line.posAtStart;
8921
    // Line boundaries point into the line
8922
    if (off == 0)
8923
        return 1;
8924
    if (off == line.length)
8925
        return -1;
8926
    // Positions on top of an element point at that element
8927
    let before = line.coordsAt(off, -1);
8928
    if (before && inside(x, y, before))
8929
        return -1;
8930
    let after = line.coordsAt(off, 1);
8931
    if (after && inside(x, y, after))
8932
        return 1;
8933
    // This is probably a line wrap point. Pick before if the point is
1441 ariadna 8934
    // above its bottom.
8935
    return before && before.bottom >= y ? -1 : 1;
1 efrain 8936
}
8937
function queryPos(view, event) {
8938
    let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
8939
    return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };
8940
}
8941
const BadMouseDetail = browser.ie && browser.ie_version <= 11;
8942
let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
8943
function getClickType(event) {
8944
    if (!BadMouseDetail)
8945
        return event.detail;
8946
    let last = lastMouseDown, lastTime = lastMouseDownTime;
8947
    lastMouseDown = event;
8948
    lastMouseDownTime = Date.now();
8949
    return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
8950
        Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;
8951
}
8952
function basicMouseSelection(view, event) {
8953
    let start = queryPos(view, event), type = getClickType(event);
8954
    let startSel = view.state.selection;
8955
    return {
8956
        update(update) {
8957
            if (update.docChanged) {
8958
                start.pos = update.changes.mapPos(start.pos);
8959
                startSel = startSel.map(update.changes);
8960
            }
8961
        },
8962
        get(event, extend, multiple) {
8963
            let cur = queryPos(view, event), removed;
8964
            let range = rangeForClick(view, cur.pos, cur.bias, type);
8965
            if (start.pos != cur.pos && !extend) {
8966
                let startRange = rangeForClick(view, start.pos, start.bias, type);
8967
                let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
8968
                range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
8969
            }
8970
            if (extend)
8971
                return startSel.replaceRange(startSel.main.extend(range.from, range.to));
8972
            else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))
8973
                return removed;
8974
            else if (multiple)
8975
                return startSel.addRange(range);
8976
            else
8977
                return EditorSelection.create([range]);
8978
        }
8979
    };
8980
}
8981
function removeRangeAround(sel, pos) {
8982
    for (let i = 0; i < sel.ranges.length; i++) {
8983
        let { from, to } = sel.ranges[i];
8984
        if (from <= pos && to >= pos)
8985
            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));
8986
    }
8987
    return null;
8988
}
8989
handlers.dragstart = (view, event) => {
8990
    let { selection: { main: range } } = view.state;
8991
    if (event.target.draggable) {
8992
        let cView = view.docView.nearest(event.target);
8993
        if (cView && cView.isWidget) {
8994
            let from = cView.posAtStart, to = from + cView.length;
8995
            if (from >= range.to || to <= range.from)
8996
                range = EditorSelection.range(from, to);
8997
        }
8998
    }
8999
    let { inputState } = view;
9000
    if (inputState.mouseSelection)
9001
        inputState.mouseSelection.dragging = true;
9002
    inputState.draggedContent = range;
9003
    if (event.dataTransfer) {
1441 ariadna 9004
        event.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to)));
1 efrain 9005
        event.dataTransfer.effectAllowed = "copyMove";
9006
    }
9007
    return false;
9008
};
9009
handlers.dragend = view => {
9010
    view.inputState.draggedContent = null;
9011
    return false;
9012
};
9013
function dropText(view, event, text, direct) {
1441 ariadna 9014
    text = textFilter(view.state, clipboardInputFilter, text);
1 efrain 9015
    if (!text)
9016
        return;
9017
    let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
9018
    let { draggedContent } = view.inputState;
9019
    let del = direct && draggedContent && dragMovesSelection(view, event)
9020
        ? { from: draggedContent.from, to: draggedContent.to } : null;
9021
    let ins = { from: dropPos, insert: text };
9022
    let changes = view.state.changes(del ? [del, ins] : ins);
9023
    view.focus();
9024
    view.dispatch({
9025
        changes,
9026
        selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
9027
        userEvent: del ? "move.drop" : "input.drop"
9028
    });
9029
    view.inputState.draggedContent = null;
9030
}
9031
handlers.drop = (view, event) => {
9032
    if (!event.dataTransfer)
9033
        return false;
9034
    if (view.state.readOnly)
9035
        return true;
9036
    let files = event.dataTransfer.files;
9037
    if (files && files.length) { // For a file drop, read the file's text.
9038
        let text = Array(files.length), read = 0;
9039
        let finishFile = () => {
9040
            if (++read == files.length)
9041
                dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
9042
        };
9043
        for (let i = 0; i < files.length; i++) {
9044
            let reader = new FileReader;
9045
            reader.onerror = finishFile;
9046
            reader.onload = () => {
9047
                if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
9048
                    text[i] = reader.result;
9049
                finishFile();
9050
            };
9051
            reader.readAsText(files[i]);
9052
        }
9053
        return true;
9054
    }
9055
    else {
9056
        let text = event.dataTransfer.getData("Text");
9057
        if (text) {
9058
            dropText(view, event, text, true);
9059
            return true;
9060
        }
9061
    }
9062
    return false;
9063
};
9064
handlers.paste = (view, event) => {
9065
    if (view.state.readOnly)
9066
        return true;
9067
    view.observer.flush();
9068
    let data = brokenClipboardAPI ? null : event.clipboardData;
9069
    if (data) {
9070
        doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"));
9071
        return true;
9072
    }
9073
    else {
9074
        capturePaste(view);
9075
        return false;
9076
    }
9077
};
9078
function captureCopy(view, text) {
9079
    // The extra wrapper is somehow necessary on IE/Edge to prevent the
9080
    // content from being mangled when it is put onto the clipboard
9081
    let parent = view.dom.parentNode;
9082
    if (!parent)
9083
        return;
9084
    let target = parent.appendChild(document.createElement("textarea"));
9085
    target.style.cssText = "position: fixed; left: -10000px; top: 10px";
9086
    target.value = text;
9087
    target.focus();
9088
    target.selectionEnd = text.length;
9089
    target.selectionStart = 0;
9090
    setTimeout(() => {
9091
        target.remove();
9092
        view.focus();
9093
    }, 50);
9094
}
9095
function copiedRange(state) {
9096
    let content = [], ranges = [], linewise = false;
9097
    for (let range of state.selection.ranges)
9098
        if (!range.empty) {
9099
            content.push(state.sliceDoc(range.from, range.to));
9100
            ranges.push(range);
9101
        }
9102
    if (!content.length) {
9103
        // Nothing selected, do a line-wise copy
9104
        let upto = -1;
9105
        for (let { from } of state.selection.ranges) {
9106
            let line = state.doc.lineAt(from);
9107
            if (line.number > upto) {
9108
                content.push(line.text);
9109
                ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
9110
            }
9111
            upto = line.number;
9112
        }
9113
        linewise = true;
9114
    }
1441 ariadna 9115
    return { text: textFilter(state, clipboardOutputFilter, content.join(state.lineBreak)), ranges, linewise };
1 efrain 9116
}
9117
let lastLinewiseCopy = null;
9118
handlers.copy = handlers.cut = (view, event) => {
9119
    let { text, ranges, linewise } = copiedRange(view.state);
9120
    if (!text && !linewise)
9121
        return false;
9122
    lastLinewiseCopy = linewise ? text : null;
9123
    if (event.type == "cut" && !view.state.readOnly)
9124
        view.dispatch({
9125
            changes: ranges,
9126
            scrollIntoView: true,
9127
            userEvent: "delete.cut"
9128
        });
9129
    let data = brokenClipboardAPI ? null : event.clipboardData;
9130
    if (data) {
9131
        data.clearData();
9132
        data.setData("text/plain", text);
9133
        return true;
9134
    }
9135
    else {
9136
        captureCopy(view, text);
9137
        return false;
9138
    }
9139
};
9140
const isFocusChange = /*@__PURE__*/Annotation.define();
9141
function focusChangeTransaction(state, focus) {
9142
    let effects = [];
9143
    for (let getEffect of state.facet(focusChangeEffect)) {
9144
        let effect = getEffect(state, focus);
9145
        if (effect)
9146
            effects.push(effect);
9147
    }
9148
    return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
9149
}
9150
function updateForFocusChange(view) {
9151
    setTimeout(() => {
9152
        let focus = view.hasFocus;
9153
        if (focus != view.inputState.notifiedFocused) {
9154
            let tr = focusChangeTransaction(view.state, focus);
9155
            if (tr)
9156
                view.dispatch(tr);
9157
            else
9158
                view.update([]);
9159
        }
9160
    }, 10);
9161
}
9162
observers.focus = view => {
9163
    view.inputState.lastFocusTime = Date.now();
9164
    // When focusing reset the scroll position, move it back to where it was
9165
    if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
9166
        view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
9167
        view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
9168
    }
9169
    updateForFocusChange(view);
9170
};
9171
observers.blur = view => {
9172
    view.observer.clearSelectionRange();
9173
    updateForFocusChange(view);
9174
};
9175
observers.compositionstart = observers.compositionupdate = view => {
1441 ariadna 9176
    if (view.observer.editContext)
9177
        return; // Composition handled by edit context
1 efrain 9178
    if (view.inputState.compositionFirstChange == null)
9179
        view.inputState.compositionFirstChange = true;
9180
    if (view.inputState.composing < 0) {
9181
        // FIXME possibly set a timeout to clear it again on Android
9182
        view.inputState.composing = 0;
9183
    }
9184
};
9185
observers.compositionend = view => {
1441 ariadna 9186
    if (view.observer.editContext)
9187
        return; // Composition handled by edit context
1 efrain 9188
    view.inputState.composing = -1;
9189
    view.inputState.compositionEndedAt = Date.now();
9190
    view.inputState.compositionPendingKey = true;
9191
    view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
9192
    view.inputState.compositionFirstChange = null;
9193
    if (browser.chrome && browser.android) {
9194
        // Delay flushing for a bit on Android because it'll often fire a
9195
        // bunch of contradictory changes in a row at end of compositon
9196
        view.observer.flushSoon();
9197
    }
9198
    else if (view.inputState.compositionPendingChange) {
9199
        // If we found pending records, schedule a flush.
9200
        Promise.resolve().then(() => view.observer.flush());
9201
    }
9202
    else {
9203
        // Otherwise, make sure that, if no changes come in soon, the
9204
        // composition view is cleared.
9205
        setTimeout(() => {
9206
            if (view.inputState.composing < 0 && view.docView.hasComposition)
9207
                view.update([]);
9208
        }, 50);
9209
    }
9210
};
9211
observers.contextmenu = view => {
9212
    view.inputState.lastContextMenu = Date.now();
9213
};
9214
handlers.beforeinput = (view, event) => {
1441 ariadna 9215
    var _a, _b;
9216
    // In EditContext mode, we must handle insertReplacementText events
9217
    // directly, to make spell checking corrections work
9218
    if (event.inputType == "insertReplacementText" && view.observer.editContext) {
9219
        let text = (_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.getData("text/plain"), ranges = event.getTargetRanges();
9220
        if (text && ranges.length) {
9221
            let r = ranges[0];
9222
            let from = view.posAtDOM(r.startContainer, r.startOffset), to = view.posAtDOM(r.endContainer, r.endOffset);
9223
            applyDOMChangeInner(view, { from, to, insert: view.state.toText(text) }, null);
9224
            return true;
9225
        }
9226
    }
1 efrain 9227
    // Because Chrome Android doesn't fire useful key events, use
9228
    // beforeinput to detect backspace (and possibly enter and delete,
9229
    // but those usually don't even seem to fire beforeinput events at
9230
    // the moment) and fake a key event for it.
9231
    //
9232
    // (preventDefault on beforeinput, though supported in the spec,
9233
    // seems to do nothing at all on Chrome).
9234
    let pending;
9235
    if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
9236
        view.observer.delayAndroidKey(pending.key, pending.keyCode);
9237
        if (pending.key == "Backspace" || pending.key == "Delete") {
1441 ariadna 9238
            let startViewHeight = ((_b = window.visualViewport) === null || _b === void 0 ? void 0 : _b.height) || 0;
1 efrain 9239
            setTimeout(() => {
9240
                var _a;
9241
                // Backspacing near uneditable nodes on Chrome Android sometimes
9242
                // closes the virtual keyboard. This tries to crudely detect
9243
                // that and refocus to get it back.
9244
                if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {
9245
                    view.contentDOM.blur();
9246
                    view.focus();
9247
                }
9248
            }, 100);
9249
        }
9250
    }
9251
    if (browser.ios && event.inputType == "deleteContentForward") {
9252
        // For some reason, DOM changes (and beforeinput) happen _before_
9253
        // the key event for ctrl-d on iOS when using an external
9254
        // keyboard.
9255
        view.observer.flushSoon();
9256
    }
9257
    // Safari will occasionally forget to fire compositionend at the end of a dead-key composition
9258
    if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) {
9259
        setTimeout(() => observers.compositionend(view, event), 20);
9260
    }
9261
    return false;
9262
};
9263
const appliedFirefoxHack = /*@__PURE__*/new Set;
9264
// In Firefox, when cut/copy handlers are added to the document, that
9265
// somehow avoids a bug where those events aren't fired when the
9266
// selection is empty. See https://github.com/codemirror/dev/issues/1082
9267
// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961
9268
function firefoxCopyCutHack(doc) {
9269
    if (!appliedFirefoxHack.has(doc)) {
9270
        appliedFirefoxHack.add(doc);
9271
        doc.addEventListener("copy", () => { });
9272
        doc.addEventListener("cut", () => { });
9273
    }
9274
}
9275
 
9276
const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
1441 ariadna 9277
// Used to track, during updateHeight, if any actual heights changed
9278
let heightChangeFlag = false;
9279
function clearHeightChangeFlag() { heightChangeFlag = false; }
1 efrain 9280
class HeightOracle {
9281
    constructor(lineWrapping) {
9282
        this.lineWrapping = lineWrapping;
9283
        this.doc = Text.empty;
9284
        this.heightSamples = {};
9285
        this.lineHeight = 14; // The height of an entire line (line-height)
9286
        this.charWidth = 7;
9287
        this.textHeight = 14; // The height of the actual font (font-size)
9288
        this.lineLength = 30;
9289
    }
9290
    heightForGap(from, to) {
9291
        let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
9292
        if (this.lineWrapping)
9293
            lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));
9294
        return this.lineHeight * lines;
9295
    }
9296
    heightForLine(length) {
9297
        if (!this.lineWrapping)
9298
            return this.lineHeight;
9299
        let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
9300
        return lines * this.lineHeight;
9301
    }
9302
    setDoc(doc) { this.doc = doc; return this; }
9303
    mustRefreshForWrapping(whiteSpace) {
9304
        return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;
9305
    }
9306
    mustRefreshForHeights(lineHeights) {
9307
        let newHeight = false;
9308
        for (let i = 0; i < lineHeights.length; i++) {
9309
            let h = lineHeights[i];
9310
            if (h < 0) {
9311
                i++;
9312
            }
9313
            else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels
9314
                newHeight = true;
9315
                this.heightSamples[Math.floor(h * 10)] = true;
9316
            }
9317
        }
9318
        return newHeight;
9319
    }
9320
    refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
9321
        let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
9322
        let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
9323
        this.lineWrapping = lineWrapping;
9324
        this.lineHeight = lineHeight;
9325
        this.charWidth = charWidth;
9326
        this.textHeight = textHeight;
9327
        this.lineLength = lineLength;
9328
        if (changed) {
9329
            this.heightSamples = {};
9330
            for (let i = 0; i < knownHeights.length; i++) {
9331
                let h = knownHeights[i];
9332
                if (h < 0)
9333
                    i++;
9334
                else
9335
                    this.heightSamples[Math.floor(h * 10)] = true;
9336
            }
9337
        }
9338
        return changed;
9339
    }
9340
}
9341
// This object is used by `updateHeight` to make DOM measurements
9342
// arrive at the right nides. The `heights` array is a sequence of
9343
// block heights, starting from position `from`.
9344
class MeasuredHeights {
9345
    constructor(from, heights) {
9346
        this.from = from;
9347
        this.heights = heights;
9348
        this.index = 0;
9349
    }
9350
    get more() { return this.index < this.heights.length; }
9351
}
9352
/**
9353
Record used to represent information about a block-level element
9354
in the editor view.
9355
*/
9356
class BlockInfo {
9357
    /**
9358
    @internal
9359
    */
9360
    constructor(
9361
    /**
9362
    The start of the element in the document.
9363
    */
9364
    from,
9365
    /**
9366
    The length of the element.
9367
    */
9368
    length,
9369
    /**
9370
    The top position of the element (relative to the top of the
9371
    document).
9372
    */
9373
    top,
9374
    /**
9375
    Its height.
9376
    */
9377
    height,
9378
    /**
9379
    @internal Weird packed field that holds an array of children
9380
    for composite blocks, a decoration for block widgets, and a
9381
    number indicating the amount of widget-create line breaks for
9382
    text blocks.
9383
    */
9384
    _content) {
9385
        this.from = from;
9386
        this.length = length;
9387
        this.top = top;
9388
        this.height = height;
9389
        this._content = _content;
9390
    }
9391
    /**
9392
    The type of element this is. When querying lines, this may be
9393
    an array of all the blocks that make up the line.
9394
    */
9395
    get type() {
9396
        return typeof this._content == "number" ? BlockType.Text :
9397
            Array.isArray(this._content) ? this._content : this._content.type;
9398
    }
9399
    /**
9400
    The end of the element as a document position.
9401
    */
9402
    get to() { return this.from + this.length; }
9403
    /**
9404
    The bottom position of the element.
9405
    */
9406
    get bottom() { return this.top + this.height; }
9407
    /**
9408
    If this is a widget block, this will return the widget
9409
    associated with it.
9410
    */
9411
    get widget() {
9412
        return this._content instanceof PointDecoration ? this._content.widget : null;
9413
    }
9414
    /**
9415
    If this is a textblock, this holds the number of line breaks
9416
    that appear in widgets inside the block.
9417
    */
9418
    get widgetLineBreaks() {
9419
        return typeof this._content == "number" ? this._content : 0;
9420
    }
9421
    /**
9422
    @internal
9423
    */
9424
    join(other) {
9425
        let content = (Array.isArray(this._content) ? this._content : [this])
9426
            .concat(Array.isArray(other._content) ? other._content : [other]);
9427
        return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);
9428
    }
9429
}
9430
var QueryType$1 = /*@__PURE__*/(function (QueryType) {
9431
    QueryType[QueryType["ByPos"] = 0] = "ByPos";
9432
    QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
9433
    QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
9434
return QueryType})(QueryType$1 || (QueryType$1 = {}));
9435
const Epsilon = 1e-3;
9436
class HeightMap {
9437
    constructor(length, // The number of characters covered
9438
    height, // Height of this part of the document
9439
    flags = 2 /* Flag.Outdated */) {
9440
        this.length = length;
9441
        this.height = height;
9442
        this.flags = flags;
9443
    }
9444
    get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }
1441 ariadna 9445
    set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & -3 /* Flag.Outdated */); }
9446
    setHeight(height) {
1 efrain 9447
        if (this.height != height) {
9448
            if (Math.abs(this.height - height) > Epsilon)
1441 ariadna 9449
                heightChangeFlag = true;
1 efrain 9450
            this.height = height;
9451
        }
9452
    }
9453
    // Base case is to replace a leaf node, which simply builds a tree
9454
    // from the new nodes and returns that (HeightMapBranch and
9455
    // HeightMapGap override this to actually use from/to)
9456
    replace(_from, _to, nodes) {
9457
        return HeightMap.of(nodes);
9458
    }
9459
    // Again, these are base cases, and are overridden for branch and gap nodes.
9460
    decomposeLeft(_to, result) { result.push(this); }
9461
    decomposeRight(_from, result) { result.push(this); }
9462
    applyChanges(decorations, oldDoc, oracle, changes) {
9463
        let me = this, doc = oracle.doc;
9464
        for (let i = changes.length - 1; i >= 0; i--) {
9465
            let { fromA, toA, fromB, toB } = changes[i];
9466
            let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
9467
            let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
9468
            toB += end.to - toA;
9469
            toA = end.to;
9470
            while (i > 0 && start.from <= changes[i - 1].toA) {
9471
                fromA = changes[i - 1].fromA;
9472
                fromB = changes[i - 1].fromB;
9473
                i--;
9474
                if (fromA < start.from)
9475
                    start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
9476
            }
9477
            fromB += start.from - fromA;
9478
            fromA = start.from;
9479
            let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);
1441 ariadna 9480
            me = replace(me, me.replace(fromA, toA, nodes));
1 efrain 9481
        }
9482
        return me.updateHeight(oracle, 0);
9483
    }
9484
    static empty() { return new HeightMapText(0, 0); }
9485
    // nodes uses null values to indicate the position of line breaks.
9486
    // There are never line breaks at the start or end of the array, or
9487
    // two line breaks next to each other, and the array isn't allowed
9488
    // to be empty (same restrictions as return value from the builder).
9489
    static of(nodes) {
9490
        if (nodes.length == 1)
9491
            return nodes[0];
9492
        let i = 0, j = nodes.length, before = 0, after = 0;
9493
        for (;;) {
9494
            if (i == j) {
9495
                if (before > after * 2) {
9496
                    let split = nodes[i - 1];
9497
                    if (split.break)
9498
                        nodes.splice(--i, 1, split.left, null, split.right);
9499
                    else
9500
                        nodes.splice(--i, 1, split.left, split.right);
9501
                    j += 1 + split.break;
9502
                    before -= split.size;
9503
                }
9504
                else if (after > before * 2) {
9505
                    let split = nodes[j];
9506
                    if (split.break)
9507
                        nodes.splice(j, 1, split.left, null, split.right);
9508
                    else
9509
                        nodes.splice(j, 1, split.left, split.right);
9510
                    j += 2 + split.break;
9511
                    after -= split.size;
9512
                }
9513
                else {
9514
                    break;
9515
                }
9516
            }
9517
            else if (before < after) {
9518
                let next = nodes[i++];
9519
                if (next)
9520
                    before += next.size;
9521
            }
9522
            else {
9523
                let next = nodes[--j];
9524
                if (next)
9525
                    after += next.size;
9526
            }
9527
        }
9528
        let brk = 0;
9529
        if (nodes[i - 1] == null) {
9530
            brk = 1;
9531
            i--;
9532
        }
9533
        else if (nodes[i] == null) {
9534
            brk = 1;
9535
            j++;
9536
        }
9537
        return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
9538
    }
9539
}
1441 ariadna 9540
function replace(old, val) {
9541
    if (old == val)
9542
        return old;
9543
    if (old.constructor != val.constructor)
9544
        heightChangeFlag = true;
9545
    return val;
9546
}
1 efrain 9547
HeightMap.prototype.size = 1;
9548
class HeightMapBlock extends HeightMap {
9549
    constructor(length, height, deco) {
9550
        super(length, height);
9551
        this.deco = deco;
9552
    }
9553
    blockAt(_height, _oracle, top, offset) {
9554
        return new BlockInfo(offset, this.length, top, this.height, this.deco || 0);
9555
    }
9556
    lineAt(_value, _type, oracle, top, offset) {
9557
        return this.blockAt(0, oracle, top, offset);
9558
    }
9559
    forEachLine(from, to, oracle, top, offset, f) {
9560
        if (from <= offset + this.length && to >= offset)
9561
            f(this.blockAt(0, oracle, top, offset));
9562
    }
9563
    updateHeight(oracle, offset = 0, _force = false, measured) {
9564
        if (measured && measured.from <= offset && measured.more)
1441 ariadna 9565
            this.setHeight(measured.heights[measured.index++]);
1 efrain 9566
        this.outdated = false;
9567
        return this;
9568
    }
9569
    toString() { return `block(${this.length})`; }
9570
}
9571
class HeightMapText extends HeightMapBlock {
9572
    constructor(length, height) {
9573
        super(length, height, null);
9574
        this.collapsed = 0; // Amount of collapsed content in the line
9575
        this.widgetHeight = 0; // Maximum inline widget height
9576
        this.breaks = 0; // Number of widget-introduced line breaks on the line
9577
    }
9578
    blockAt(_height, _oracle, top, offset) {
9579
        return new BlockInfo(offset, this.length, top, this.height, this.breaks);
9580
    }
9581
    replace(_from, _to, nodes) {
9582
        let node = nodes[0];
9583
        if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&
9584
            Math.abs(this.length - node.length) < 10) {
9585
            if (node instanceof HeightMapGap)
9586
                node = new HeightMapText(node.length, this.height);
9587
            else
9588
                node.height = this.height;
9589
            if (!this.outdated)
9590
                node.outdated = false;
9591
            return node;
9592
        }
9593
        else {
9594
            return HeightMap.of(nodes);
9595
        }
9596
    }
9597
    updateHeight(oracle, offset = 0, force = false, measured) {
9598
        if (measured && measured.from <= offset && measured.more)
1441 ariadna 9599
            this.setHeight(measured.heights[measured.index++]);
1 efrain 9600
        else if (force || this.outdated)
1441 ariadna 9601
            this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +
1 efrain 9602
                this.breaks * oracle.lineHeight);
9603
        this.outdated = false;
9604
        return this;
9605
    }
9606
    toString() {
9607
        return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
9608
    }
9609
}
9610
class HeightMapGap extends HeightMap {
9611
    constructor(length) { super(length, 0); }
9612
    heightMetrics(oracle, offset) {
9613
        let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
9614
        let lines = lastLine - firstLine + 1;
9615
        let perLine, perChar = 0;
9616
        if (oracle.lineWrapping) {
9617
            let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
9618
            perLine = totalPerLine / lines;
9619
            if (this.length > lines + 1)
9620
                perChar = (this.height - totalPerLine) / (this.length - lines - 1);
9621
        }
9622
        else {
9623
            perLine = this.height / lines;
9624
        }
9625
        return { firstLine, lastLine, perLine, perChar };
9626
    }
9627
    blockAt(height, oracle, top, offset) {
9628
        let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9629
        if (oracle.lineWrapping) {
9630
            let guess = offset + (height < oracle.lineHeight ? 0
9631
                : Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length));
9632
            let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
9633
            let lineTop = Math.max(top, height - lineHeight / 2);
9634
            return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
9635
        }
9636
        else {
9637
            let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));
9638
            let { from, length } = oracle.doc.line(firstLine + line);
9639
            return new BlockInfo(from, length, top + perLine * line, perLine, 0);
9640
        }
9641
    }
9642
    lineAt(value, type, oracle, top, offset) {
9643
        if (type == QueryType$1.ByHeight)
9644
            return this.blockAt(value, oracle, top, offset);
9645
        if (type == QueryType$1.ByPosNoHeight) {
9646
            let { from, to } = oracle.doc.lineAt(value);
9647
            return new BlockInfo(from, to - from, 0, 0, 0);
9648
        }
9649
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9650
        let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
9651
        let linesAbove = line.number - firstLine;
9652
        let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
9653
        return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);
9654
    }
9655
    forEachLine(from, to, oracle, top, offset, f) {
9656
        from = Math.max(from, offset);
9657
        to = Math.min(to, offset + this.length);
9658
        let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9659
        for (let pos = from, lineTop = top; pos <= to;) {
9660
            let line = oracle.doc.lineAt(pos);
9661
            if (pos == from) {
9662
                let linesAbove = line.number - firstLine;
9663
                lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
9664
            }
9665
            let lineHeight = perLine + perChar * line.length;
9666
            f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
9667
            lineTop += lineHeight;
9668
            pos = line.to + 1;
9669
        }
9670
    }
9671
    replace(from, to, nodes) {
9672
        let after = this.length - to;
9673
        if (after > 0) {
9674
            let last = nodes[nodes.length - 1];
9675
            if (last instanceof HeightMapGap)
9676
                nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
9677
            else
9678
                nodes.push(null, new HeightMapGap(after - 1));
9679
        }
9680
        if (from > 0) {
9681
            let first = nodes[0];
9682
            if (first instanceof HeightMapGap)
9683
                nodes[0] = new HeightMapGap(from + first.length);
9684
            else
9685
                nodes.unshift(new HeightMapGap(from - 1), null);
9686
        }
9687
        return HeightMap.of(nodes);
9688
    }
9689
    decomposeLeft(to, result) {
9690
        result.push(new HeightMapGap(to - 1), null);
9691
    }
9692
    decomposeRight(from, result) {
9693
        result.push(null, new HeightMapGap(this.length - from - 1));
9694
    }
9695
    updateHeight(oracle, offset = 0, force = false, measured) {
9696
        let end = offset + this.length;
9697
        if (measured && measured.from <= offset + this.length && measured.more) {
9698
            // Fill in part of this gap with measured lines. We know there
9699
            // can't be widgets or collapsed ranges in those lines, because
9700
            // they would already have been added to the heightmap (gaps
9701
            // only contain plain text).
9702
            let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
9703
            if (measured.from > offset)
9704
                nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
9705
            while (pos <= end && measured.more) {
9706
                let len = oracle.doc.lineAt(pos).length;
9707
                if (nodes.length)
9708
                    nodes.push(null);
9709
                let height = measured.heights[measured.index++];
9710
                if (singleHeight == -1)
9711
                    singleHeight = height;
9712
                else if (Math.abs(height - singleHeight) >= Epsilon)
9713
                    singleHeight = -2;
9714
                let line = new HeightMapText(len, height);
9715
                line.outdated = false;
9716
                nodes.push(line);
9717
                pos += len + 1;
9718
            }
9719
            if (pos <= end)
9720
                nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
9721
            let result = HeightMap.of(nodes);
9722
            if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||
9723
                Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
1441 ariadna 9724
                heightChangeFlag = true;
9725
            return replace(this, result);
1 efrain 9726
        }
9727
        else if (force || this.outdated) {
1441 ariadna 9728
            this.setHeight(oracle.heightForGap(offset, offset + this.length));
1 efrain 9729
            this.outdated = false;
9730
        }
9731
        return this;
9732
    }
9733
    toString() { return `gap(${this.length})`; }
9734
}
9735
class HeightMapBranch extends HeightMap {
9736
    constructor(left, brk, right) {
9737
        super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));
9738
        this.left = left;
9739
        this.right = right;
9740
        this.size = left.size + right.size;
9741
    }
9742
    get break() { return this.flags & 1 /* Flag.Break */; }
9743
    blockAt(height, oracle, top, offset) {
9744
        let mid = top + this.left.height;
9745
        return height < mid ? this.left.blockAt(height, oracle, top, offset)
9746
            : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
9747
    }
9748
    lineAt(value, type, oracle, top, offset) {
9749
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9750
        let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset;
9751
        let base = left ? this.left.lineAt(value, type, oracle, top, offset)
9752
            : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
9753
        if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))
9754
            return base;
9755
        let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos;
9756
        if (left)
9757
            return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
9758
        else
9759
            return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);
9760
    }
9761
    forEachLine(from, to, oracle, top, offset, f) {
9762
        let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9763
        if (this.break) {
9764
            if (from < rightOffset)
9765
                this.left.forEachLine(from, to, oracle, top, offset, f);
9766
            if (to >= rightOffset)
9767
                this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
9768
        }
9769
        else {
9770
            let mid = this.lineAt(rightOffset, QueryType$1.ByPos, oracle, top, offset);
9771
            if (from < mid.from)
9772
                this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);
9773
            if (mid.to >= from && mid.from <= to)
9774
                f(mid);
9775
            if (to > mid.to)
9776
                this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
9777
        }
9778
    }
9779
    replace(from, to, nodes) {
9780
        let rightStart = this.left.length + this.break;
9781
        if (to < rightStart)
9782
            return this.balanced(this.left.replace(from, to, nodes), this.right);
9783
        if (from > this.left.length)
9784
            return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
9785
        let result = [];
9786
        if (from > 0)
9787
            this.decomposeLeft(from, result);
9788
        let left = result.length;
9789
        for (let node of nodes)
9790
            result.push(node);
9791
        if (from > 0)
9792
            mergeGaps(result, left - 1);
9793
        if (to < this.length) {
9794
            let right = result.length;
9795
            this.decomposeRight(to, result);
9796
            mergeGaps(result, right);
9797
        }
9798
        return HeightMap.of(result);
9799
    }
9800
    decomposeLeft(to, result) {
9801
        let left = this.left.length;
9802
        if (to <= left)
9803
            return this.left.decomposeLeft(to, result);
9804
        result.push(this.left);
9805
        if (this.break) {
9806
            left++;
9807
            if (to >= left)
9808
                result.push(null);
9809
        }
9810
        if (to > left)
9811
            this.right.decomposeLeft(to - left, result);
9812
    }
9813
    decomposeRight(from, result) {
9814
        let left = this.left.length, right = left + this.break;
9815
        if (from >= right)
9816
            return this.right.decomposeRight(from - right, result);
9817
        if (from < left)
9818
            this.left.decomposeRight(from, result);
9819
        if (this.break && from < right)
9820
            result.push(null);
9821
        result.push(this.right);
9822
    }
9823
    balanced(left, right) {
9824
        if (left.size > 2 * right.size || right.size > 2 * left.size)
9825
            return HeightMap.of(this.break ? [left, null, right] : [left, right]);
1441 ariadna 9826
        this.left = replace(this.left, left);
9827
        this.right = replace(this.right, right);
9828
        this.setHeight(left.height + right.height);
1 efrain 9829
        this.outdated = left.outdated || right.outdated;
9830
        this.size = left.size + right.size;
9831
        this.length = left.length + this.break + right.length;
9832
        return this;
9833
    }
9834
    updateHeight(oracle, offset = 0, force = false, measured) {
9835
        let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
9836
        if (measured && measured.from <= offset + left.length && measured.more)
9837
            rebalance = left = left.updateHeight(oracle, offset, force, measured);
9838
        else
9839
            left.updateHeight(oracle, offset, force);
9840
        if (measured && measured.from <= rightStart + right.length && measured.more)
9841
            rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
9842
        else
9843
            right.updateHeight(oracle, rightStart, force);
9844
        if (rebalance)
9845
            return this.balanced(left, right);
9846
        this.height = this.left.height + this.right.height;
9847
        this.outdated = false;
9848
        return this;
9849
    }
9850
    toString() { return this.left + (this.break ? " " : "-") + this.right; }
9851
}
9852
function mergeGaps(nodes, around) {
9853
    let before, after;
9854
    if (nodes[around] == null &&
9855
        (before = nodes[around - 1]) instanceof HeightMapGap &&
9856
        (after = nodes[around + 1]) instanceof HeightMapGap)
9857
        nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
9858
}
9859
const relevantWidgetHeight = 5;
9860
class NodeBuilder {
9861
    constructor(pos, oracle) {
9862
        this.pos = pos;
9863
        this.oracle = oracle;
9864
        this.nodes = [];
9865
        this.lineStart = -1;
9866
        this.lineEnd = -1;
9867
        this.covering = null;
9868
        this.writtenTo = pos;
9869
    }
9870
    get isCovered() {
9871
        return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
9872
    }
9873
    span(_from, to) {
9874
        if (this.lineStart > -1) {
9875
            let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
9876
            if (last instanceof HeightMapText)
9877
                last.length += end - this.pos;
9878
            else if (end > this.pos || !this.isCovered)
9879
                this.nodes.push(new HeightMapText(end - this.pos, -1));
9880
            this.writtenTo = end;
9881
            if (to > end) {
9882
                this.nodes.push(null);
9883
                this.writtenTo++;
9884
                this.lineStart = -1;
9885
            }
9886
        }
9887
        this.pos = to;
9888
    }
9889
    point(from, to, deco) {
9890
        if (from < to || deco.heightRelevant) {
9891
            let height = deco.widget ? deco.widget.estimatedHeight : 0;
9892
            let breaks = deco.widget ? deco.widget.lineBreaks : 0;
9893
            if (height < 0)
9894
                height = this.oracle.lineHeight;
9895
            let len = to - from;
9896
            if (deco.block) {
9897
                this.addBlock(new HeightMapBlock(len, height, deco));
9898
            }
9899
            else if (len || breaks || height >= relevantWidgetHeight) {
9900
                this.addLineDeco(height, breaks, len);
9901
            }
9902
        }
9903
        else if (to > from) {
9904
            this.span(from, to);
9905
        }
9906
        if (this.lineEnd > -1 && this.lineEnd < this.pos)
9907
            this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
9908
    }
9909
    enterLine() {
9910
        if (this.lineStart > -1)
9911
            return;
9912
        let { from, to } = this.oracle.doc.lineAt(this.pos);
9913
        this.lineStart = from;
9914
        this.lineEnd = to;
9915
        if (this.writtenTo < from) {
9916
            if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
9917
                this.nodes.push(this.blankContent(this.writtenTo, from - 1));
9918
            this.nodes.push(null);
9919
        }
9920
        if (this.pos > from)
9921
            this.nodes.push(new HeightMapText(this.pos - from, -1));
9922
        this.writtenTo = this.pos;
9923
    }
9924
    blankContent(from, to) {
9925
        let gap = new HeightMapGap(to - from);
9926
        if (this.oracle.doc.lineAt(from).to == to)
9927
            gap.flags |= 4 /* Flag.SingleLine */;
9928
        return gap;
9929
    }
9930
    ensureLine() {
9931
        this.enterLine();
9932
        let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
9933
        if (last instanceof HeightMapText)
9934
            return last;
9935
        let line = new HeightMapText(0, -1);
9936
        this.nodes.push(line);
9937
        return line;
9938
    }
9939
    addBlock(block) {
9940
        this.enterLine();
9941
        let deco = block.deco;
9942
        if (deco && deco.startSide > 0 && !this.isCovered)
9943
            this.ensureLine();
9944
        this.nodes.push(block);
9945
        this.writtenTo = this.pos = this.pos + block.length;
9946
        if (deco && deco.endSide > 0)
9947
            this.covering = block;
9948
    }
9949
    addLineDeco(height, breaks, length) {
9950
        let line = this.ensureLine();
9951
        line.length += length;
9952
        line.collapsed += length;
9953
        line.widgetHeight = Math.max(line.widgetHeight, height);
9954
        line.breaks += breaks;
9955
        this.writtenTo = this.pos = this.pos + length;
9956
    }
9957
    finish(from) {
9958
        let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
9959
        if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
9960
            this.nodes.push(new HeightMapText(0, -1));
9961
        else if (this.writtenTo < this.pos || last == null)
9962
            this.nodes.push(this.blankContent(this.writtenTo, this.pos));
9963
        let pos = from;
9964
        for (let node of this.nodes) {
9965
            if (node instanceof HeightMapText)
9966
                node.updateHeight(this.oracle, pos);
9967
            pos += node ? node.length : 1;
9968
        }
9969
        return this.nodes;
9970
    }
9971
    // Always called with a region that on both sides either stretches
9972
    // to a line break or the end of the document.
9973
    // The returned array uses null to indicate line breaks, but never
9974
    // starts or ends in a line break, or has multiple line breaks next
9975
    // to each other.
9976
    static build(oracle, decorations, from, to) {
9977
        let builder = new NodeBuilder(from, oracle);
9978
        RangeSet.spans(decorations, from, to, builder, 0);
9979
        return builder.finish(from);
9980
    }
9981
}
9982
function heightRelevantDecoChanges(a, b, diff) {
9983
    let comp = new DecorationComparator;
9984
    RangeSet.compare(a, b, diff, comp, 0);
9985
    return comp.changes;
9986
}
9987
class DecorationComparator {
9988
    constructor() {
9989
        this.changes = [];
9990
    }
9991
    compareRange() { }
9992
    comparePoint(from, to, a, b) {
9993
        if (from < to || a && a.heightRelevant || b && b.heightRelevant)
9994
            addRange(from, to, this.changes, 5);
9995
    }
9996
}
9997
 
9998
function visiblePixelRange(dom, paddingTop) {
9999
    let rect = dom.getBoundingClientRect();
10000
    let doc = dom.ownerDocument, win = doc.defaultView || window;
10001
    let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
10002
    let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
10003
    for (let parent = dom.parentNode; parent && parent != doc.body;) {
10004
        if (parent.nodeType == 1) {
10005
            let elt = parent;
10006
            let style = window.getComputedStyle(elt);
10007
            if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&
10008
                style.overflow != "visible") {
10009
                let parentRect = elt.getBoundingClientRect();
10010
                left = Math.max(left, parentRect.left);
10011
                right = Math.min(right, parentRect.right);
10012
                top = Math.max(top, parentRect.top);
1441 ariadna 10013
                bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom);
1 efrain 10014
            }
10015
            parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
10016
        }
10017
        else if (parent.nodeType == 11) { // Shadow root
10018
            parent = parent.host;
10019
        }
10020
        else {
10021
            break;
10022
        }
10023
    }
10024
    return { left: left - rect.left, right: Math.max(left, right) - rect.left,
10025
        top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };
10026
}
1441 ariadna 10027
function inWindow(elt) {
10028
    let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window;
10029
    return rect.left < win.innerWidth && rect.right > 0 &&
10030
        rect.top < win.innerHeight && rect.bottom > 0;
10031
}
1 efrain 10032
function fullPixelRange(dom, paddingTop) {
10033
    let rect = dom.getBoundingClientRect();
10034
    return { left: 0, right: rect.right - rect.left,
10035
        top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };
10036
}
10037
// Line gaps are placeholder widgets used to hide pieces of overlong
10038
// lines within the viewport, as a kludge to keep the editor
10039
// responsive when a ridiculously long line is loaded into it.
10040
class LineGap {
1441 ariadna 10041
    constructor(from, to, size, displaySize) {
1 efrain 10042
        this.from = from;
10043
        this.to = to;
10044
        this.size = size;
1441 ariadna 10045
        this.displaySize = displaySize;
1 efrain 10046
    }
10047
    static same(a, b) {
10048
        if (a.length != b.length)
10049
            return false;
10050
        for (let i = 0; i < a.length; i++) {
10051
            let gA = a[i], gB = b[i];
10052
            if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
10053
                return false;
10054
        }
10055
        return true;
10056
    }
10057
    draw(viewState, wrapping) {
10058
        return Decoration.replace({
1441 ariadna 10059
            widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
1 efrain 10060
        }).range(this.from, this.to);
10061
    }
10062
}
10063
class LineGapWidget extends WidgetType {
10064
    constructor(size, vertical) {
10065
        super();
10066
        this.size = size;
10067
        this.vertical = vertical;
10068
    }
10069
    eq(other) { return other.size == this.size && other.vertical == this.vertical; }
10070
    toDOM() {
10071
        let elt = document.createElement("div");
10072
        if (this.vertical) {
10073
            elt.style.height = this.size + "px";
10074
        }
10075
        else {
10076
            elt.style.width = this.size + "px";
10077
            elt.style.height = "2px";
10078
            elt.style.display = "inline-block";
10079
        }
10080
        return elt;
10081
    }
10082
    get estimatedHeight() { return this.vertical ? this.size : -1; }
10083
}
10084
class ViewState {
10085
    constructor(state) {
10086
        this.state = state;
10087
        // These are contentDOM-local coordinates
10088
        this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
10089
        this.inView = true;
10090
        this.paddingTop = 0; // Padding above the document, scaled
10091
        this.paddingBottom = 0; // Padding below the document, scaled
10092
        this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width
10093
        this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height
10094
        this.editorHeight = 0; // scrollDOM.clientHeight, unscaled
10095
        this.editorWidth = 0; // scrollDOM.clientWidth, unscaled
10096
        this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled
1441 ariadna 10097
        this.scrolledToBottom = false;
1 efrain 10098
        // The CSS-transformation scale of the editor (transformed size /
10099
        // concrete size)
10100
        this.scaleX = 1;
10101
        this.scaleY = 1;
10102
        // The vertical position (document-relative) to which to anchor the
10103
        // scroll position. -1 means anchor to the end of the document.
10104
        this.scrollAnchorPos = 0;
10105
        // The height at the anchor position. Set by the DOM update phase.
10106
        // -1 means no height available.
10107
        this.scrollAnchorHeight = -1;
10108
        // See VP.MaxDOMHeight
10109
        this.scaler = IdScaler;
10110
        this.scrollTarget = null;
10111
        // Briefly set to true when printing, to disable viewport limiting
10112
        this.printing = false;
10113
        // Flag set when editor content was redrawn, so that the next
10114
        // measure stage knows it must read DOM layout
10115
        this.mustMeasureContent = true;
10116
        this.defaultTextDirection = Direction.LTR;
10117
        this.visibleRanges = [];
10118
        // Cursor 'assoc' is only significant when the cursor is on a line
10119
        // wrap point, where it must stick to the character that it is
10120
        // associated with. Since browsers don't provide a reasonable
10121
        // interface to set or query this, when a selection is set that
10122
        // might cause this to be significant, this flag is set. The next
10123
        // measure phase will check whether the cursor is on a line-wrapping
10124
        // boundary and, if so, reset it to make sure it is positioned in
10125
        // the right place.
10126
        this.mustEnforceCursorAssoc = false;
10127
        let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping");
10128
        this.heightOracle = new HeightOracle(guessWrapping);
10129
        this.stateDeco = state.facet(decorations).filter(d => typeof d != "function");
10130
        this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
1441 ariadna 10131
        for (let i = 0; i < 2; i++) {
10132
            this.viewport = this.getViewport(0, null);
10133
            if (!this.updateForViewport())
10134
                break;
10135
        }
1 efrain 10136
        this.updateViewportLines();
10137
        this.lineGaps = this.ensureLineGaps([]);
10138
        this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));
10139
        this.computeVisibleRanges();
10140
    }
10141
    updateForViewport() {
10142
        let viewports = [this.viewport], { main } = this.state.selection;
10143
        for (let i = 0; i <= 1; i++) {
10144
            let pos = i ? main.head : main.anchor;
10145
            if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
10146
                let { from, to } = this.lineBlockAt(pos);
10147
                viewports.push(new Viewport(from, to));
10148
            }
10149
        }
10150
        this.viewports = viewports.sort((a, b) => a.from - b.from);
1441 ariadna 10151
        return this.updateScaler();
10152
    }
10153
    updateScaler() {
10154
        let scaler = this.scaler;
1 efrain 10155
        this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :
10156
            new BigScaler(this.heightOracle, this.heightMap, this.viewports);
1441 ariadna 10157
        return scaler.eq(this.scaler) ? 0 : 2 /* UpdateFlag.Height */;
1 efrain 10158
    }
10159
    updateViewportLines() {
10160
        this.viewportLines = [];
10161
        this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
1441 ariadna 10162
            this.viewportLines.push(scaleBlock(block, this.scaler));
1 efrain 10163
        });
10164
    }
10165
    update(update, scrollTarget = null) {
10166
        this.state = update.state;
10167
        let prevDeco = this.stateDeco;
10168
        this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function");
10169
        let contentChanges = update.changedRanges;
10170
        let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
10171
        let prevHeight = this.heightMap.height;
10172
        let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
1441 ariadna 10173
        clearHeightChangeFlag();
1 efrain 10174
        this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
1441 ariadna 10175
        if (this.heightMap.height != prevHeight || heightChangeFlag)
1 efrain 10176
            update.flags |= 2 /* UpdateFlag.Height */;
10177
        if (scrollAnchor) {
10178
            this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
10179
            this.scrollAnchorHeight = scrollAnchor.top;
10180
        }
10181
        else {
10182
            this.scrollAnchorPos = -1;
10183
            this.scrollAnchorHeight = this.heightMap.height;
10184
        }
10185
        let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
10186
        if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||
10187
            !this.viewportIsAppropriate(viewport))
10188
            viewport = this.getViewport(0, scrollTarget);
1441 ariadna 10189
        let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to;
1 efrain 10190
        this.viewport = viewport;
1441 ariadna 10191
        update.flags |= this.updateForViewport();
10192
        if (viewportChange || !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */))
1 efrain 10193
            this.updateViewportLines();
10194
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
10195
            this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
1441 ariadna 10196
        update.flags |= this.computeVisibleRanges(update.changes);
1 efrain 10197
        if (scrollTarget)
10198
            this.scrollTarget = scrollTarget;
10199
        if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&
10200
            update.state.selection.main.empty && update.state.selection.main.assoc &&
10201
            !update.state.facet(nativeSelectionHidden))
10202
            this.mustEnforceCursorAssoc = true;
10203
    }
10204
    measure(view) {
10205
        let dom = view.contentDOM, style = window.getComputedStyle(dom);
10206
        let oracle = this.heightOracle;
10207
        let whiteSpace = style.whiteSpace;
10208
        this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
10209
        let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
10210
        let domRect = dom.getBoundingClientRect();
10211
        let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
10212
        this.contentDOMHeight = domRect.height;
10213
        this.mustMeasureContent = false;
10214
        let result = 0, bias = 0;
10215
        if (domRect.width && domRect.height) {
10216
            let { scaleX, scaleY } = getScale(dom, domRect);
10217
            if (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 ||
10218
                scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) {
10219
                this.scaleX = scaleX;
10220
                this.scaleY = scaleY;
1441 ariadna 10221
                result |= 16 /* UpdateFlag.Geometry */;
1 efrain 10222
                refresh = measureContent = true;
10223
            }
10224
        }
10225
        // Vertical padding
10226
        let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
10227
        let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
10228
        if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
10229
            this.paddingTop = paddingTop;
10230
            this.paddingBottom = paddingBottom;
1441 ariadna 10231
            result |= 16 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;
1 efrain 10232
        }
10233
        if (this.editorWidth != view.scrollDOM.clientWidth) {
10234
            if (oracle.lineWrapping)
10235
                measureContent = true;
10236
            this.editorWidth = view.scrollDOM.clientWidth;
1441 ariadna 10237
            result |= 16 /* UpdateFlag.Geometry */;
1 efrain 10238
        }
10239
        let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
10240
        if (this.scrollTop != scrollTop) {
10241
            this.scrollAnchorHeight = -1;
10242
            this.scrollTop = scrollTop;
10243
        }
10244
        this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
10245
        // Pixel viewport
10246
        let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
10247
        let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
10248
        this.pixelViewport = pixelViewport;
10249
        let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
10250
        if (inView != this.inView) {
10251
            this.inView = inView;
10252
            if (inView)
10253
                measureContent = true;
10254
        }
1441 ariadna 10255
        if (!this.inView && !this.scrollTarget && !inWindow(view.dom))
1 efrain 10256
            return 0;
10257
        let contentWidth = domRect.width;
10258
        if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
10259
            this.contentDOMWidth = domRect.width;
10260
            this.editorHeight = view.scrollDOM.clientHeight;
1441 ariadna 10261
            result |= 16 /* UpdateFlag.Geometry */;
1 efrain 10262
        }
10263
        if (measureContent) {
10264
            let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
10265
            if (oracle.mustRefreshForHeights(lineHeights))
10266
                refresh = true;
10267
            if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
10268
                let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
10269
                refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
10270
                if (refresh) {
10271
                    view.docView.minWidth = 0;
1441 ariadna 10272
                    result |= 16 /* UpdateFlag.Geometry */;
1 efrain 10273
                }
10274
            }
10275
            if (dTop > 0 && dBottom > 0)
10276
                bias = Math.max(dTop, dBottom);
10277
            else if (dTop < 0 && dBottom < 0)
10278
                bias = Math.min(dTop, dBottom);
1441 ariadna 10279
            clearHeightChangeFlag();
1 efrain 10280
            for (let vp of this.viewports) {
10281
                let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
10282
                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));
10283
            }
1441 ariadna 10284
            if (heightChangeFlag)
1 efrain 10285
                result |= 2 /* UpdateFlag.Height */;
10286
        }
10287
        let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||
10288
            this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||
10289
                this.scrollTarget.range.head > this.viewport.to);
1441 ariadna 10290
        if (viewportChange) {
10291
            if (result & 2 /* UpdateFlag.Height */)
10292
                result |= this.updateScaler();
1 efrain 10293
            this.viewport = this.getViewport(bias, this.scrollTarget);
1441 ariadna 10294
            result |= this.updateForViewport();
10295
        }
1 efrain 10296
        if ((result & 2 /* UpdateFlag.Height */) || viewportChange)
10297
            this.updateViewportLines();
10298
        if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
10299
            this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
10300
        result |= this.computeVisibleRanges();
10301
        if (this.mustEnforceCursorAssoc) {
10302
            this.mustEnforceCursorAssoc = false;
10303
            // This is done in the read stage, because moving the selection
10304
            // to a line end is going to trigger a layout anyway, so it
10305
            // can't be a pure write. It should be rare that it does any
10306
            // writing.
10307
            view.docView.enforceCursorAssoc();
10308
        }
10309
        return result;
10310
    }
10311
    get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }
10312
    get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }
10313
    getViewport(bias, scrollTarget) {
10314
        // This will divide VP.Margin between the top and the
10315
        // bottom, depending on the bias (the change in viewport position
10316
        // since the last update). It'll hold a number between 0 and 1
10317
        let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));
10318
        let map = this.heightMap, oracle = this.heightOracle;
10319
        let { visibleTop, visibleBottom } = this;
10320
        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);
10321
        // If scrollTarget is given, make sure the viewport includes that position
10322
        if (scrollTarget) {
10323
            let { head } = scrollTarget.range;
10324
            if (head < viewport.from || head > viewport.to) {
10325
                let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
10326
                let block = map.lineAt(head, QueryType$1.ByPos, oracle, 0, 0), topPos;
10327
                if (scrollTarget.y == "center")
10328
                    topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
10329
                else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
10330
                    topPos = block.top;
10331
                else
10332
                    topPos = block.bottom - viewHeight;
10333
                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);
10334
            }
10335
        }
10336
        return viewport;
10337
    }
10338
    mapViewport(viewport, changes) {
10339
        let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
10340
        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);
10341
    }
10342
    // Checks if a given viewport covers the visible part of the
10343
    // document and not too much beyond that.
10344
    viewportIsAppropriate({ from, to }, bias = 0) {
10345
        if (!this.inView)
10346
            return true;
10347
        let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0);
10348
        let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0);
10349
        let { visibleTop, visibleBottom } = this;
10350
        return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&
10351
            (to == this.state.doc.length ||
10352
                bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&
10353
            (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);
10354
    }
10355
    mapLineGaps(gaps, changes) {
10356
        if (!gaps.length || changes.empty)
10357
            return gaps;
10358
        let mapped = [];
10359
        for (let gap of gaps)
10360
            if (!changes.touchesRange(gap.from, gap.to))
1441 ariadna 10361
                mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize));
1 efrain 10362
        return mapped;
10363
    }
10364
    // Computes positions in the viewport where the start or end of a
10365
    // line should be hidden, trying to reuse existing line gaps when
10366
    // appropriate to avoid unneccesary redraws.
10367
    // Uses crude character-counting for the positioning and sizing,
10368
    // since actual DOM coordinates aren't always available and
10369
    // predictable. Relies on generous margins (see LG.Margin) to hide
10370
    // the artifacts this might produce from the user.
10371
    ensureLineGaps(current, mayMeasure) {
10372
        let wrapping = this.heightOracle.lineWrapping;
10373
        let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;
10374
        // The non-wrapping logic won't work at all in predominantly right-to-left text.
10375
        if (this.defaultTextDirection != Direction.LTR && !wrapping)
10376
            return [];
10377
        let gaps = [];
10378
        let addGap = (from, to, line, structure) => {
10379
            if (to - from < halfMargin)
10380
                return;
10381
            let sel = this.state.selection.main, avoid = [sel.from];
10382
            if (!sel.empty)
10383
                avoid.push(sel.to);
10384
            for (let pos of avoid) {
10385
                if (pos > from && pos < to) {
10386
                    addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);
10387
                    addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);
10388
                    return;
10389
                }
10390
            }
10391
            let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&
10392
                Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&
10393
                !avoid.some(pos => gap.from < pos && gap.to > pos));
10394
            if (!gap) {
10395
                // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping
10396
                if (to < line.to && mayMeasure && wrapping &&
10397
                    mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
10398
                    let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
10399
                    if (lineStart > from)
10400
                        to = lineStart;
10401
                }
1441 ariadna 10402
                let size = this.gapSize(line, from, to, structure);
10403
                let displaySize = wrapping || size < 2000000 /* VP.MaxHorizGap */ ? size : 2000000 /* VP.MaxHorizGap */;
10404
                gap = new LineGap(from, to, size, displaySize);
1 efrain 10405
            }
10406
            gaps.push(gap);
10407
        };
1441 ariadna 10408
        let checkLine = (line) => {
10409
            if (line.length < doubleMargin || line.type != BlockType.Text)
10410
                return;
1 efrain 10411
            let structure = lineStructure(line.from, line.to, this.stateDeco);
10412
            if (structure.total < doubleMargin)
1441 ariadna 10413
                return;
1 efrain 10414
            let target = this.scrollTarget ? this.scrollTarget.range.head : null;
10415
            let viewFrom, viewTo;
10416
            if (wrapping) {
10417
                let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;
10418
                let top, bot;
10419
                if (target != null) {
10420
                    let targetFrac = findFraction(structure, target);
10421
                    let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
10422
                    top = targetFrac - spaceFrac;
10423
                    bot = targetFrac + spaceFrac;
10424
                }
10425
                else {
10426
                    top = (this.visibleTop - line.top - marginHeight) / line.height;
10427
                    bot = (this.visibleBottom - line.top + marginHeight) / line.height;
10428
                }
10429
                viewFrom = findPosition(structure, top);
10430
                viewTo = findPosition(structure, bot);
10431
            }
10432
            else {
10433
                let totalWidth = structure.total * this.heightOracle.charWidth;
10434
                let marginWidth = margin * this.heightOracle.charWidth;
1441 ariadna 10435
                let horizOffset = 0;
10436
                if (totalWidth > 2000000 /* VP.MaxHorizGap */)
10437
                    for (let old of current) {
10438
                        if (old.from >= line.from && old.from < line.to && old.size != old.displaySize &&
10439
                            old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left)
10440
                            horizOffset = old.size - old.displaySize;
10441
                    }
10442
                let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset;
1 efrain 10443
                let left, right;
10444
                if (target != null) {
10445
                    let targetFrac = findFraction(structure, target);
1441 ariadna 10446
                    let spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth;
1 efrain 10447
                    left = targetFrac - spaceFrac;
10448
                    right = targetFrac + spaceFrac;
10449
                }
10450
                else {
1441 ariadna 10451
                    left = (pxLeft - marginWidth) / totalWidth;
10452
                    right = (pxRight + marginWidth) / totalWidth;
1 efrain 10453
                }
10454
                viewFrom = findPosition(structure, left);
10455
                viewTo = findPosition(structure, right);
10456
            }
10457
            if (viewFrom > line.from)
10458
                addGap(line.from, viewFrom, line, structure);
10459
            if (viewTo < line.to)
10460
                addGap(viewTo, line.to, line, structure);
1441 ariadna 10461
        };
10462
        for (let line of this.viewportLines) {
10463
            if (Array.isArray(line.type))
10464
                line.type.forEach(checkLine);
10465
            else
10466
                checkLine(line);
1 efrain 10467
        }
10468
        return gaps;
10469
    }
10470
    gapSize(line, from, to, structure) {
10471
        let fraction = findFraction(structure, to) - findFraction(structure, from);
10472
        if (this.heightOracle.lineWrapping) {
10473
            return line.height * fraction;
10474
        }
10475
        else {
10476
            return structure.total * this.heightOracle.charWidth * fraction;
10477
        }
10478
    }
10479
    updateLineGaps(gaps) {
10480
        if (!LineGap.same(gaps, this.lineGaps)) {
10481
            this.lineGaps = gaps;
10482
            this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
10483
        }
10484
    }
1441 ariadna 10485
    computeVisibleRanges(changes) {
1 efrain 10486
        let deco = this.stateDeco;
10487
        if (this.lineGaps.length)
10488
            deco = deco.concat(this.lineGapDeco);
10489
        let ranges = [];
10490
        RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
10491
            span(from, to) { ranges.push({ from, to }); },
10492
            point() { }
10493
        }, 20);
1441 ariadna 10494
        let changed = 0;
10495
        if (ranges.length != this.visibleRanges.length) {
10496
            changed = 8 /* UpdateFlag.ViewportMoved */ | 4 /* UpdateFlag.Viewport */;
10497
        }
10498
        else {
10499
            for (let i = 0; i < ranges.length && !(changed & 8 /* UpdateFlag.ViewportMoved */); i++) {
10500
                let old = this.visibleRanges[i], nw = ranges[i];
10501
                if (old.from != nw.from || old.to != nw.to) {
10502
                    changed |= 4 /* UpdateFlag.Viewport */;
10503
                    if (!(changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to))
10504
                        changed |= 8 /* UpdateFlag.ViewportMoved */;
10505
                }
10506
            }
10507
        }
1 efrain 10508
        this.visibleRanges = ranges;
1441 ariadna 10509
        return changed;
1 efrain 10510
    }
10511
    lineBlockAt(pos) {
1441 ariadna 10512
        return (pos >= this.viewport.from && pos <= this.viewport.to &&
10513
            this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||
1 efrain 10514
            scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.heightOracle, 0, 0), this.scaler);
10515
    }
10516
    lineBlockAtHeight(height) {
1441 ariadna 10517
        return (height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom &&
10518
            this.viewportLines.find(l => l.top <= height && l.bottom >= height)) ||
10519
            scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.heightOracle, 0, 0), this.scaler);
1 efrain 10520
    }
10521
    scrollAnchorAt(scrollTop) {
10522
        let block = this.lineBlockAtHeight(scrollTop + 8);
10523
        return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
10524
    }
10525
    elementAtHeight(height) {
10526
        return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
10527
    }
10528
    get docHeight() {
10529
        return this.scaler.toDOM(this.heightMap.height);
10530
    }
10531
    get contentHeight() {
10532
        return this.docHeight + this.paddingTop + this.paddingBottom;
10533
    }
10534
}
10535
class Viewport {
10536
    constructor(from, to) {
10537
        this.from = from;
10538
        this.to = to;
10539
    }
10540
}
10541
function lineStructure(from, to, stateDeco) {
10542
    let ranges = [], pos = from, total = 0;
10543
    RangeSet.spans(stateDeco, from, to, {
10544
        span() { },
10545
        point(from, to) {
10546
            if (from > pos) {
10547
                ranges.push({ from: pos, to: from });
10548
                total += from - pos;
10549
            }
10550
            pos = to;
10551
        }
10552
    }, 20); // We're only interested in collapsed ranges of a significant size
10553
    if (pos < to) {
10554
        ranges.push({ from: pos, to });
10555
        total += to - pos;
10556
    }
10557
    return { total, ranges };
10558
}
10559
function findPosition({ total, ranges }, ratio) {
10560
    if (ratio <= 0)
10561
        return ranges[0].from;
10562
    if (ratio >= 1)
10563
        return ranges[ranges.length - 1].to;
10564
    let dist = Math.floor(total * ratio);
10565
    for (let i = 0;; i++) {
10566
        let { from, to } = ranges[i], size = to - from;
10567
        if (dist <= size)
10568
            return from + dist;
10569
        dist -= size;
10570
    }
10571
}
10572
function findFraction(structure, pos) {
10573
    let counted = 0;
10574
    for (let { from, to } of structure.ranges) {
10575
        if (pos <= to) {
10576
            counted += pos - from;
10577
            break;
10578
        }
10579
        counted += to - from;
10580
    }
10581
    return counted / structure.total;
10582
}
10583
function find(array, f) {
10584
    for (let val of array)
10585
        if (f(val))
10586
            return val;
10587
    return undefined;
10588
}
10589
// Don't scale when the document height is within the range of what
10590
// the DOM can handle.
10591
const IdScaler = {
10592
    toDOM(n) { return n; },
10593
    fromDOM(n) { return n; },
1441 ariadna 10594
    scale: 1,
10595
    eq(other) { return other == this; }
1 efrain 10596
};
10597
// When the height is too big (> VP.MaxDOMHeight), scale down the
10598
// regions outside the viewports so that the total height is
10599
// VP.MaxDOMHeight.
10600
class BigScaler {
10601
    constructor(oracle, heightMap, viewports) {
10602
        let vpHeight = 0, base = 0, domBase = 0;
10603
        this.viewports = viewports.map(({ from, to }) => {
10604
            let top = heightMap.lineAt(from, QueryType$1.ByPos, oracle, 0, 0).top;
10605
            let bottom = heightMap.lineAt(to, QueryType$1.ByPos, oracle, 0, 0).bottom;
10606
            vpHeight += bottom - top;
10607
            return { from, to, top, bottom, domTop: 0, domBottom: 0 };
10608
        });
10609
        this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);
10610
        for (let obj of this.viewports) {
10611
            obj.domTop = domBase + (obj.top - base) * this.scale;
10612
            domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
10613
            base = obj.bottom;
10614
        }
10615
    }
10616
    toDOM(n) {
10617
        for (let i = 0, base = 0, domBase = 0;; i++) {
10618
            let vp = i < this.viewports.length ? this.viewports[i] : null;
10619
            if (!vp || n < vp.top)
10620
                return domBase + (n - base) * this.scale;
10621
            if (n <= vp.bottom)
10622
                return vp.domTop + (n - vp.top);
10623
            base = vp.bottom;
10624
            domBase = vp.domBottom;
10625
        }
10626
    }
10627
    fromDOM(n) {
10628
        for (let i = 0, base = 0, domBase = 0;; i++) {
10629
            let vp = i < this.viewports.length ? this.viewports[i] : null;
10630
            if (!vp || n < vp.domTop)
10631
                return base + (n - domBase) / this.scale;
10632
            if (n <= vp.domBottom)
10633
                return vp.top + (n - vp.domTop);
10634
            base = vp.bottom;
10635
            domBase = vp.domBottom;
10636
        }
10637
    }
1441 ariadna 10638
    eq(other) {
10639
        if (!(other instanceof BigScaler))
10640
            return false;
10641
        return this.scale == other.scale && this.viewports.length == other.viewports.length &&
10642
            this.viewports.every((vp, i) => vp.from == other.viewports[i].from && vp.to == other.viewports[i].to);
10643
    }
1 efrain 10644
}
10645
function scaleBlock(block, scaler) {
10646
    if (scaler.scale == 1)
10647
        return block;
10648
    let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
10649
    return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);
10650
}
10651
 
10652
const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") });
10653
const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 });
10654
const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName();
10655
const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
10656
function buildTheme(main, spec, scopes) {
10657
    return new StyleModule(spec, {
10658
        finish(sel) {
10659
            return /&/.test(sel) ? sel.replace(/&\w*/, m => {
10660
                if (m == "&")
10661
                    return main;
10662
                if (!scopes || !scopes[m])
10663
                    throw new RangeError(`Unsupported selector: ${m}`);
10664
                return scopes[m];
10665
            }) : main + " " + sel;
10666
        }
10667
    });
10668
}
10669
const baseTheme$1$3 = /*@__PURE__*/buildTheme("." + baseThemeID, {
10670
    "&": {
10671
        position: "relative !important",
10672
        boxSizing: "border-box",
10673
        "&.cm-focused": {
10674
            // Provide a simple default outline to make sure a focused
10675
            // editor is visually distinct. Can't leave the default behavior
10676
            // because that will apply to the content element, which is
10677
            // inside the scrollable container and doesn't include the
10678
            // gutters. We also can't use an 'auto' outline, since those
10679
            // are, for some reason, drawn behind the element content, which
10680
            // will cause things like the active line background to cover
10681
            // the outline (#297).
10682
            outline: "1px dotted #212121"
10683
        },
10684
        display: "flex !important",
10685
        flexDirection: "column"
10686
    },
10687
    ".cm-scroller": {
10688
        display: "flex !important",
10689
        alignItems: "flex-start !important",
10690
        fontFamily: "monospace",
10691
        lineHeight: 1.4,
10692
        height: "100%",
10693
        overflowX: "auto",
10694
        position: "relative",
1441 ariadna 10695
        zIndex: 0,
10696
        overflowAnchor: "none",
1 efrain 10697
    },
10698
    ".cm-content": {
10699
        margin: 0,
10700
        flexGrow: 2,
10701
        flexShrink: 0,
10702
        display: "block",
10703
        whiteSpace: "pre",
10704
        wordWrap: "normal", // https://github.com/codemirror/dev/issues/456
10705
        boxSizing: "border-box",
10706
        minHeight: "100%",
10707
        padding: "4px 0",
10708
        outline: "none",
10709
        "&[contenteditable=true]": {
10710
            WebkitUserModify: "read-write-plaintext-only",
10711
        }
10712
    },
10713
    ".cm-lineWrapping": {
10714
        whiteSpace_fallback: "pre-wrap", // For IE
10715
        whiteSpace: "break-spaces",
10716
        wordBreak: "break-word", // For Safari, which doesn't support overflow-wrap: anywhere
10717
        overflowWrap: "anywhere",
10718
        flexShrink: 1
10719
    },
10720
    "&light .cm-content": { caretColor: "black" },
10721
    "&dark .cm-content": { caretColor: "white" },
10722
    ".cm-line": {
10723
        display: "block",
10724
        padding: "0 2px 0 6px"
10725
    },
10726
    ".cm-layer": {
10727
        position: "absolute",
10728
        left: 0,
10729
        top: 0,
10730
        contain: "size style",
10731
        "& > *": {
10732
            position: "absolute"
10733
        }
10734
    },
10735
    "&light .cm-selectionBackground": {
10736
        background: "#d9d9d9"
10737
    },
10738
    "&dark .cm-selectionBackground": {
10739
        background: "#222"
10740
    },
10741
    "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10742
        background: "#d7d4f0"
10743
    },
10744
    "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10745
        background: "#233"
10746
    },
10747
    ".cm-cursorLayer": {
10748
        pointerEvents: "none"
10749
    },
10750
    "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
10751
        animation: "steps(1) cm-blink 1.2s infinite"
10752
    },
10753
    // Two animations defined so that we can switch between them to
10754
    // restart the animation without forcing another style
10755
    // recomputation.
10756
    "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10757
    "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10758
    ".cm-cursor, .cm-dropCursor": {
10759
        borderLeft: "1.2px solid black",
10760
        marginLeft: "-0.6px",
10761
        pointerEvents: "none",
10762
    },
10763
    ".cm-cursor": {
10764
        display: "none"
10765
    },
10766
    "&dark .cm-cursor": {
1441 ariadna 10767
        borderLeftColor: "#ddd"
1 efrain 10768
    },
10769
    ".cm-dropCursor": {
10770
        position: "absolute"
10771
    },
10772
    "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
10773
        display: "block"
10774
    },
10775
    ".cm-iso": {
10776
        unicodeBidi: "isolate"
10777
    },
10778
    ".cm-announced": {
10779
        position: "fixed",
10780
        top: "-10000px"
10781
    },
10782
    "@media print": {
10783
        ".cm-announced": { display: "none" }
10784
    },
10785
    "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
10786
    "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
10787
    "&light .cm-specialChar": { color: "red" },
10788
    "&dark .cm-specialChar": { color: "#f78" },
10789
    ".cm-gutters": {
10790
        flexShrink: 0,
10791
        display: "flex",
10792
        height: "100%",
10793
        boxSizing: "border-box",
10794
        insetInlineStart: 0,
10795
        zIndex: 200
10796
    },
10797
    "&light .cm-gutters": {
10798
        backgroundColor: "#f5f5f5",
10799
        color: "#6c6c6c",
10800
        borderRight: "1px solid #ddd"
10801
    },
10802
    "&dark .cm-gutters": {
10803
        backgroundColor: "#333338",
10804
        color: "#ccc"
10805
    },
10806
    ".cm-gutter": {
10807
        display: "flex !important", // Necessary -- prevents margin collapsing
10808
        flexDirection: "column",
10809
        flexShrink: 0,
10810
        boxSizing: "border-box",
10811
        minHeight: "100%",
10812
        overflow: "hidden"
10813
    },
10814
    ".cm-gutterElement": {
10815
        boxSizing: "border-box"
10816
    },
10817
    ".cm-lineNumbers .cm-gutterElement": {
10818
        padding: "0 3px 0 5px",
10819
        minWidth: "20px",
10820
        textAlign: "right",
10821
        whiteSpace: "nowrap"
10822
    },
10823
    "&light .cm-activeLineGutter": {
10824
        backgroundColor: "#e2f2ff"
10825
    },
10826
    "&dark .cm-activeLineGutter": {
10827
        backgroundColor: "#222227"
10828
    },
10829
    ".cm-panels": {
10830
        boxSizing: "border-box",
10831
        position: "sticky",
10832
        left: 0,
1441 ariadna 10833
        right: 0,
10834
        zIndex: 300
1 efrain 10835
    },
10836
    "&light .cm-panels": {
10837
        backgroundColor: "#f5f5f5",
10838
        color: "black"
10839
    },
10840
    "&light .cm-panels-top": {
10841
        borderBottom: "1px solid #ddd"
10842
    },
10843
    "&light .cm-panels-bottom": {
10844
        borderTop: "1px solid #ddd"
10845
    },
10846
    "&dark .cm-panels": {
10847
        backgroundColor: "#333338",
10848
        color: "white"
10849
    },
10850
    ".cm-tab": {
10851
        display: "inline-block",
10852
        overflow: "hidden",
10853
        verticalAlign: "bottom"
10854
    },
10855
    ".cm-widgetBuffer": {
10856
        verticalAlign: "text-top",
10857
        height: "1em",
10858
        width: 0,
10859
        display: "inline"
10860
    },
10861
    ".cm-placeholder": {
10862
        color: "#888",
10863
        display: "inline-block",
10864
        verticalAlign: "top",
10865
    },
1441 ariadna 10866
    ".cm-highlightSpace": {
10867
        backgroundImage: "radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",
10868
        backgroundPosition: "center",
1 efrain 10869
    },
10870
    ".cm-highlightTab": {
10871
        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>')`,
10872
        backgroundSize: "auto 100%",
10873
        backgroundPosition: "right 90%",
10874
        backgroundRepeat: "no-repeat"
10875
    },
10876
    ".cm-trailingSpace": {
10877
        backgroundColor: "#ff332255"
10878
    },
10879
    ".cm-button": {
10880
        verticalAlign: "middle",
10881
        color: "inherit",
10882
        fontSize: "70%",
10883
        padding: ".2em 1em",
10884
        borderRadius: "1px"
10885
    },
10886
    "&light .cm-button": {
10887
        backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
10888
        border: "1px solid #888",
10889
        "&:active": {
10890
            backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
10891
        }
10892
    },
10893
    "&dark .cm-button": {
10894
        backgroundImage: "linear-gradient(#393939, #111)",
10895
        border: "1px solid #888",
10896
        "&:active": {
10897
            backgroundImage: "linear-gradient(#111, #333)"
10898
        }
10899
    },
10900
    ".cm-textfield": {
10901
        verticalAlign: "middle",
10902
        color: "inherit",
10903
        fontSize: "70%",
10904
        border: "1px solid silver",
10905
        padding: ".2em .5em"
10906
    },
10907
    "&light .cm-textfield": {
10908
        backgroundColor: "white"
10909
    },
10910
    "&dark .cm-textfield": {
10911
        border: "1px solid #555",
10912
        backgroundColor: "inherit"
10913
    }
10914
}, lightDarkIDs);
10915
 
10916
const observeOptions = {
10917
    childList: true,
10918
    characterData: true,
10919
    subtree: true,
10920
    attributes: true,
10921
    characterDataOldValue: true
10922
};
10923
// IE11 has very broken mutation observers, so we also listen to
10924
// DOMCharacterDataModified there
10925
const useCharData = browser.ie && browser.ie_version <= 11;
10926
class DOMObserver {
10927
    constructor(view) {
10928
        this.view = view;
10929
        this.active = false;
1441 ariadna 10930
        this.editContext = null;
1 efrain 10931
        // The known selection. Kept in our own object, as opposed to just
10932
        // directly accessing the selection because:
10933
        //  - Safari doesn't report the right selection in shadow DOM
10934
        //  - Reading from the selection forces a DOM layout
10935
        //  - This way, we can ignore selectionchange events if we have
10936
        //    already seen the 'new' selection
10937
        this.selectionRange = new DOMSelectionState;
10938
        // Set when a selection change is detected, cleared on flush
10939
        this.selectionChanged = false;
10940
        this.delayedFlush = -1;
10941
        this.resizeTimeout = -1;
10942
        this.queue = [];
10943
        this.delayedAndroidKey = null;
10944
        this.flushingAndroidKey = -1;
10945
        this.lastChange = 0;
10946
        this.scrollTargets = [];
10947
        this.intersection = null;
10948
        this.resizeScroll = null;
10949
        this.intersecting = false;
10950
        this.gapIntersection = null;
10951
        this.gaps = [];
10952
        this.printQuery = null;
10953
        // Timeout for scheduling check of the parents that need scroll handlers
10954
        this.parentCheck = -1;
10955
        this.dom = view.contentDOM;
10956
        this.observer = new MutationObserver(mutations => {
10957
            for (let mut of mutations)
10958
                this.queue.push(mut);
10959
            // IE11 will sometimes (on typing over a selection or
10960
            // backspacing out a single character text node) call the
10961
            // observer callback before actually updating the DOM.
10962
            //
10963
            // Unrelatedly, iOS Safari will, when ending a composition,
10964
            // sometimes first clear it, deliver the mutations, and then
10965
            // reinsert the finished text. CodeMirror's handling of the
10966
            // deletion will prevent the reinsertion from happening,
10967
            // breaking composition.
10968
            if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&
10969
                mutations.some(m => m.type == "childList" && m.removedNodes.length ||
10970
                    m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
10971
                this.flushSoon();
10972
            else
10973
                this.flush();
10974
        });
1441 ariadna 10975
        if (window.EditContext && view.constructor.EDIT_CONTEXT !== false &&
10976
            // Chrome <126 doesn't support inverted selections in edit context (#1392)
10977
            !(browser.chrome && browser.chrome_version < 126)) {
10978
            this.editContext = new EditContextManager(view);
10979
            if (view.state.facet(editable))
10980
                view.contentDOM.editContext = this.editContext.editContext;
10981
        }
1 efrain 10982
        if (useCharData)
10983
            this.onCharData = (event) => {
10984
                this.queue.push({ target: event.target,
10985
                    type: "characterData",
10986
                    oldValue: event.prevValue });
10987
                this.flushSoon();
10988
            };
10989
        this.onSelectionChange = this.onSelectionChange.bind(this);
10990
        this.onResize = this.onResize.bind(this);
10991
        this.onPrint = this.onPrint.bind(this);
10992
        this.onScroll = this.onScroll.bind(this);
10993
        if (window.matchMedia)
10994
            this.printQuery = window.matchMedia("print");
10995
        if (typeof ResizeObserver == "function") {
10996
            this.resizeScroll = new ResizeObserver(() => {
10997
                var _a;
10998
                if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)
10999
                    this.onResize();
11000
            });
11001
            this.resizeScroll.observe(view.scrollDOM);
11002
        }
11003
        this.addWindowListeners(this.win = view.win);
11004
        this.start();
11005
        if (typeof IntersectionObserver == "function") {
11006
            this.intersection = new IntersectionObserver(entries => {
11007
                if (this.parentCheck < 0)
11008
                    this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);
11009
                if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {
11010
                    this.intersecting = !this.intersecting;
11011
                    if (this.intersecting != this.view.inView)
11012
                        this.onScrollChanged(document.createEvent("Event"));
11013
                }
11014
            }, { threshold: [0, .001] });
11015
            this.intersection.observe(this.dom);
11016
            this.gapIntersection = new IntersectionObserver(entries => {
11017
                if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
11018
                    this.onScrollChanged(document.createEvent("Event"));
11019
            }, {});
11020
        }
11021
        this.listenForScroll();
11022
        this.readSelectionRange();
11023
    }
11024
    onScrollChanged(e) {
11025
        this.view.inputState.runHandlers("scroll", e);
11026
        if (this.intersecting)
11027
            this.view.measure();
11028
    }
11029
    onScroll(e) {
11030
        if (this.intersecting)
11031
            this.flush(false);
1441 ariadna 11032
        if (this.editContext)
11033
            this.view.requestMeasure(this.editContext.measureReq);
1 efrain 11034
        this.onScrollChanged(e);
11035
    }
11036
    onResize() {
11037
        if (this.resizeTimeout < 0)
11038
            this.resizeTimeout = setTimeout(() => {
11039
                this.resizeTimeout = -1;
11040
                this.view.requestMeasure();
11041
            }, 50);
11042
    }
11043
    onPrint(event) {
1441 ariadna 11044
        if ((event.type == "change" || !event.type) && !event.matches)
1 efrain 11045
            return;
11046
        this.view.viewState.printing = true;
11047
        this.view.measure();
11048
        setTimeout(() => {
11049
            this.view.viewState.printing = false;
11050
            this.view.requestMeasure();
11051
        }, 500);
11052
    }
11053
    updateGaps(gaps) {
11054
        if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
11055
            this.gapIntersection.disconnect();
11056
            for (let gap of gaps)
11057
                this.gapIntersection.observe(gap);
11058
            this.gaps = gaps;
11059
        }
11060
    }
11061
    onSelectionChange(event) {
11062
        let wasChanged = this.selectionChanged;
11063
        if (!this.readSelectionRange() || this.delayedAndroidKey)
11064
            return;
11065
        let { view } = this, sel = this.selectionRange;
1441 ariadna 11066
        if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel))
1 efrain 11067
            return;
11068
        let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
11069
        if (context && context.ignoreEvent(event)) {
11070
            if (!wasChanged)
11071
                this.selectionChanged = false;
11072
            return;
11073
        }
11074
        // Deletions on IE11 fire their events in the wrong order, giving
11075
        // us a selection change event before the DOM changes are
11076
        // reported.
11077
        // Chrome Android has a similar issue when backspacing out a
11078
        // selection (#645).
11079
        if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&
11080
            // (Selection.isCollapsed isn't reliable on IE)
11081
            sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
11082
            this.flushSoon();
11083
        else
11084
            this.flush(false);
11085
    }
11086
    readSelectionRange() {
11087
        let { view } = this;
11088
        // The Selection object is broken in shadow roots in Safari. See
11089
        // https://github.com/codemirror/dev/issues/414
11090
        let selection = getSelection(view.root);
11091
        if (!selection)
11092
            return false;
11093
        let range = browser.safari && view.root.nodeType == 11 &&
1441 ariadna 11094
            view.root.activeElement == this.dom &&
1 efrain 11095
            safariSelectionRangeHack(this.view, selection) || selection;
11096
        if (!range || this.selectionRange.eq(range))
11097
            return false;
11098
        let local = hasSelection(this.dom, range);
11099
        // Detect the situation where the browser has, on focus, moved the
11100
        // selection to the start of the content element. Reset it to the
11101
        // position from the editor state.
11102
        if (local && !this.selectionChanged &&
11103
            view.inputState.lastFocusTime > Date.now() - 200 &&
11104
            view.inputState.lastTouchTime < Date.now() - 300 &&
11105
            atElementStart(this.dom, range)) {
11106
            this.view.inputState.lastFocusTime = 0;
11107
            view.docView.updateSelection();
11108
            return false;
11109
        }
11110
        this.selectionRange.setRange(range);
11111
        if (local)
11112
            this.selectionChanged = true;
11113
        return true;
11114
    }
11115
    setSelectionRange(anchor, head) {
11116
        this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
11117
        this.selectionChanged = false;
11118
    }
11119
    clearSelectionRange() {
11120
        this.selectionRange.set(null, 0, null, 0);
11121
    }
11122
    listenForScroll() {
11123
        this.parentCheck = -1;
11124
        let i = 0, changed = null;
11125
        for (let dom = this.dom; dom;) {
11126
            if (dom.nodeType == 1) {
11127
                if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
11128
                    i++;
11129
                else if (!changed)
11130
                    changed = this.scrollTargets.slice(0, i);
11131
                if (changed)
11132
                    changed.push(dom);
11133
                dom = dom.assignedSlot || dom.parentNode;
11134
            }
11135
            else if (dom.nodeType == 11) { // Shadow root
11136
                dom = dom.host;
11137
            }
11138
            else {
11139
                break;
11140
            }
11141
        }
11142
        if (i < this.scrollTargets.length && !changed)
11143
            changed = this.scrollTargets.slice(0, i);
11144
        if (changed) {
11145
            for (let dom of this.scrollTargets)
11146
                dom.removeEventListener("scroll", this.onScroll);
11147
            for (let dom of this.scrollTargets = changed)
11148
                dom.addEventListener("scroll", this.onScroll);
11149
        }
11150
    }
11151
    ignore(f) {
11152
        if (!this.active)
11153
            return f();
11154
        try {
11155
            this.stop();
11156
            return f();
11157
        }
11158
        finally {
11159
            this.start();
11160
            this.clear();
11161
        }
11162
    }
11163
    start() {
11164
        if (this.active)
11165
            return;
11166
        this.observer.observe(this.dom, observeOptions);
11167
        if (useCharData)
11168
            this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
11169
        this.active = true;
11170
    }
11171
    stop() {
11172
        if (!this.active)
11173
            return;
11174
        this.active = false;
11175
        this.observer.disconnect();
11176
        if (useCharData)
11177
            this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
11178
    }
11179
    // Throw away any pending changes
11180
    clear() {
11181
        this.processRecords();
11182
        this.queue.length = 0;
11183
        this.selectionChanged = false;
11184
    }
11185
    // Chrome Android, especially in combination with GBoard, not only
11186
    // doesn't reliably fire regular key events, but also often
11187
    // surrounds the effect of enter or backspace with a bunch of
11188
    // composition events that, when interrupted, cause text duplication
11189
    // or other kinds of corruption. This hack makes the editor back off
11190
    // from handling DOM changes for a moment when such a key is
11191
    // detected (via beforeinput or keydown), and then tries to flush
11192
    // them or, if that has no effect, dispatches the given key.
11193
    delayAndroidKey(key, keyCode) {
11194
        var _a;
11195
        if (!this.delayedAndroidKey) {
11196
            let flush = () => {
11197
                let key = this.delayedAndroidKey;
11198
                if (key) {
11199
                    this.clearDelayedAndroidKey();
11200
                    this.view.inputState.lastKeyCode = key.keyCode;
11201
                    this.view.inputState.lastKeyTime = Date.now();
11202
                    let flushed = this.flush();
11203
                    if (!flushed && key.force)
11204
                        dispatchKey(this.dom, key.key, key.keyCode);
11205
                }
11206
            };
11207
            this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
11208
        }
11209
        // Since backspace beforeinput is sometimes signalled spuriously,
11210
        // Enter always takes precedence.
11211
        if (!this.delayedAndroidKey || key == "Enter")
11212
            this.delayedAndroidKey = {
11213
                key, keyCode,
11214
                // Only run the key handler when no changes are detected if
11215
                // this isn't coming right after another change, in which case
11216
                // it is probably part of a weird chain of updates, and should
11217
                // be ignored if it returns the DOM to its previous state.
11218
                force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)
11219
            };
11220
    }
11221
    clearDelayedAndroidKey() {
11222
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
11223
        this.delayedAndroidKey = null;
11224
        this.flushingAndroidKey = -1;
11225
    }
11226
    flushSoon() {
11227
        if (this.delayedFlush < 0)
11228
            this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });
11229
    }
11230
    forceFlush() {
11231
        if (this.delayedFlush >= 0) {
11232
            this.view.win.cancelAnimationFrame(this.delayedFlush);
11233
            this.delayedFlush = -1;
11234
        }
11235
        this.flush();
11236
    }
11237
    pendingRecords() {
11238
        for (let mut of this.observer.takeRecords())
11239
            this.queue.push(mut);
11240
        return this.queue;
11241
    }
11242
    processRecords() {
11243
        let records = this.pendingRecords();
11244
        if (records.length)
11245
            this.queue = [];
11246
        let from = -1, to = -1, typeOver = false;
11247
        for (let record of records) {
11248
            let range = this.readMutation(record);
11249
            if (!range)
11250
                continue;
11251
            if (range.typeOver)
11252
                typeOver = true;
11253
            if (from == -1) {
11254
                ({ from, to } = range);
11255
            }
11256
            else {
11257
                from = Math.min(range.from, from);
11258
                to = Math.max(range.to, to);
11259
            }
11260
        }
11261
        return { from, to, typeOver };
11262
    }
11263
    readChange() {
11264
        let { from, to, typeOver } = this.processRecords();
11265
        let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
11266
        if (from < 0 && !newSel)
11267
            return null;
11268
        if (from > -1)
11269
            this.lastChange = Date.now();
11270
        this.view.inputState.lastFocusTime = 0;
11271
        this.selectionChanged = false;
11272
        let change = new DOMChange(this.view, from, to, typeOver);
11273
        this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
11274
        return change;
11275
    }
11276
    // Apply pending changes, if any
11277
    flush(readSelection = true) {
11278
        // Completely hold off flushing when pending keys are set—the code
11279
        // managing those will make sure processRecords is called and the
11280
        // view is resynchronized after
11281
        if (this.delayedFlush >= 0 || this.delayedAndroidKey)
11282
            return false;
11283
        if (readSelection)
11284
            this.readSelectionRange();
11285
        let domChange = this.readChange();
11286
        if (!domChange) {
11287
            this.view.requestMeasure();
11288
            return false;
11289
        }
11290
        let startState = this.view.state;
11291
        let handled = applyDOMChange(this.view, domChange);
1441 ariadna 11292
        // The view wasn't updated but DOM/selection changes were seen. Reset the view.
11293
        if (this.view.state == startState &&
11294
            (domChange.domChanged || domChange.newSel && !domChange.newSel.main.eq(this.view.state.selection.main)))
1 efrain 11295
            this.view.update([]);
11296
        return handled;
11297
    }
11298
    readMutation(rec) {
11299
        let cView = this.view.docView.nearest(rec.target);
11300
        if (!cView || cView.ignoreMutation(rec))
11301
            return null;
11302
        cView.markDirty(rec.type == "attributes");
11303
        if (rec.type == "attributes")
11304
            cView.flags |= 4 /* ViewFlag.AttrsDirty */;
11305
        if (rec.type == "childList") {
11306
            let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
11307
            let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
11308
            return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
11309
                to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };
11310
        }
11311
        else if (rec.type == "characterData") {
11312
            return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
11313
        }
11314
        else {
11315
            return null;
11316
        }
11317
    }
11318
    setWindow(win) {
11319
        if (win != this.win) {
11320
            this.removeWindowListeners(this.win);
11321
            this.win = win;
11322
            this.addWindowListeners(this.win);
11323
        }
11324
    }
11325
    addWindowListeners(win) {
11326
        win.addEventListener("resize", this.onResize);
1441 ariadna 11327
        if (this.printQuery) {
11328
            if (this.printQuery.addEventListener)
11329
                this.printQuery.addEventListener("change", this.onPrint);
11330
            else
11331
                this.printQuery.addListener(this.onPrint);
11332
        }
1 efrain 11333
        else
11334
            win.addEventListener("beforeprint", this.onPrint);
11335
        win.addEventListener("scroll", this.onScroll);
11336
        win.document.addEventListener("selectionchange", this.onSelectionChange);
11337
    }
11338
    removeWindowListeners(win) {
11339
        win.removeEventListener("scroll", this.onScroll);
11340
        win.removeEventListener("resize", this.onResize);
1441 ariadna 11341
        if (this.printQuery) {
11342
            if (this.printQuery.removeEventListener)
11343
                this.printQuery.removeEventListener("change", this.onPrint);
11344
            else
11345
                this.printQuery.removeListener(this.onPrint);
11346
        }
1 efrain 11347
        else
11348
            win.removeEventListener("beforeprint", this.onPrint);
11349
        win.document.removeEventListener("selectionchange", this.onSelectionChange);
11350
    }
1441 ariadna 11351
    update(update) {
11352
        if (this.editContext) {
11353
            this.editContext.update(update);
11354
            if (update.startState.facet(editable) != update.state.facet(editable))
11355
                update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null;
11356
        }
11357
    }
1 efrain 11358
    destroy() {
11359
        var _a, _b, _c;
11360
        this.stop();
11361
        (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();
11362
        (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();
11363
        (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();
11364
        for (let dom of this.scrollTargets)
11365
            dom.removeEventListener("scroll", this.onScroll);
11366
        this.removeWindowListeners(this.win);
11367
        clearTimeout(this.parentCheck);
11368
        clearTimeout(this.resizeTimeout);
11369
        this.win.cancelAnimationFrame(this.delayedFlush);
11370
        this.win.cancelAnimationFrame(this.flushingAndroidKey);
1441 ariadna 11371
        if (this.editContext) {
11372
            this.view.contentDOM.editContext = null;
11373
            this.editContext.destroy();
11374
        }
1 efrain 11375
    }
11376
}
11377
function findChild(cView, dom, dir) {
11378
    while (dom) {
11379
        let curView = ContentView.get(dom);
11380
        if (curView && curView.parent == cView)
11381
            return curView;
11382
        let parent = dom.parentNode;
11383
        dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
11384
    }
11385
    return null;
11386
}
11387
function buildSelectionRangeFromRange(view, range) {
11388
    let anchorNode = range.startContainer, anchorOffset = range.startOffset;
11389
    let focusNode = range.endContainer, focusOffset = range.endOffset;
11390
    let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
11391
    // Since such a range doesn't distinguish between anchor and head,
11392
    // use a heuristic that flips it around if its end matches the
11393
    // current anchor.
11394
    if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
11395
        [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
11396
    return { anchorNode, anchorOffset, focusNode, focusOffset };
11397
}
11398
// Used to work around a Safari Selection/shadow DOM bug (#414)
11399
function safariSelectionRangeHack(view, selection) {
11400
    if (selection.getComposedRanges) {
11401
        let range = selection.getComposedRanges(view.root)[0];
11402
        if (range)
11403
            return buildSelectionRangeFromRange(view, range);
11404
    }
11405
    let found = null;
11406
    // Because Safari (at least in 2018-2021) doesn't provide regular
11407
    // access to the selection inside a shadowroot, we have to perform a
11408
    // ridiculous hack to get at it—using `execCommand` to trigger a
11409
    // `beforeInput` event so that we can read the target range from the
11410
    // event.
11411
    function read(event) {
11412
        event.preventDefault();
11413
        event.stopImmediatePropagation();
11414
        found = event.getTargetRanges()[0];
11415
    }
11416
    view.contentDOM.addEventListener("beforeinput", read, true);
11417
    view.dom.ownerDocument.execCommand("indent");
11418
    view.contentDOM.removeEventListener("beforeinput", read, true);
11419
    return found ? buildSelectionRangeFromRange(view, found) : null;
11420
}
1441 ariadna 11421
class EditContextManager {
11422
    constructor(view) {
11423
        // The document window for which the text in the context is
11424
        // maintained. For large documents, this may be smaller than the
11425
        // editor document. This window always includes the selection head.
11426
        this.from = 0;
11427
        this.to = 0;
11428
        // When applying a transaction, this is used to compare the change
11429
        // made to the context content to the change in the transaction in
11430
        // order to make the minimal changes to the context (since touching
11431
        // that sometimes breaks series of multiple edits made for a single
11432
        // user action on some Android keyboards)
11433
        this.pendingContextChange = null;
11434
        this.handlers = Object.create(null);
11435
        // Kludge to work around the fact that EditContext does not respond
11436
        // well to having its content updated during a composition (see #1472)
11437
        this.composing = null;
11438
        this.resetRange(view.state);
11439
        let context = this.editContext = new window.EditContext({
11440
            text: view.state.doc.sliceString(this.from, this.to),
11441
            selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))),
11442
            selectionEnd: this.toContextPos(view.state.selection.main.head)
11443
        });
11444
        this.handlers.textupdate = e => {
11445
            let main = view.state.selection.main, { anchor, head } = main;
11446
            let from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd);
11447
            if (view.inputState.composing >= 0 && !this.composing)
11448
                this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: false };
11449
            let change = { from, to, insert: Text.of(e.text.split("\n")) };
11450
            // If the window doesn't include the anchor, assume changes
11451
            // adjacent to a side go up to the anchor.
11452
            if (change.from == this.from && anchor < this.from)
11453
                change.from = anchor;
11454
            else if (change.to == this.to && anchor > this.to)
11455
                change.to = anchor;
11456
            // Edit contexts sometimes fire empty changes
11457
            if (change.from == change.to && !change.insert.length) {
11458
                let newSel = EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd));
11459
                if (!newSel.main.eq(main))
11460
                    view.dispatch({ selection: newSel, userEvent: "select" });
11461
                return;
11462
            }
11463
            if ((browser.mac || browser.android) && change.from == head - 1 &&
11464
                /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off")
11465
                change = { from, to, insert: Text.of([e.text.replace(".", " ")]) };
11466
            this.pendingContextChange = change;
11467
            if (!view.state.readOnly) {
11468
                let newLen = this.to - this.from + (change.to - change.from + change.insert.length);
11469
                applyDOMChangeInner(view, change, EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen)));
11470
            }
11471
            // If the transaction didn't flush our change, revert it so
11472
            // that the context is in sync with the editor state again.
11473
            if (this.pendingContextChange) {
11474
                this.revertPending(view.state);
11475
                this.setSelection(view.state);
11476
            }
11477
        };
11478
        this.handlers.characterboundsupdate = e => {
11479
            let rects = [], prev = null;
11480
            for (let i = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i < end; i++) {
11481
                let rect = view.coordsForChar(i);
11482
                prev = (rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top))
11483
                    || prev || new DOMRect;
11484
                rects.push(prev);
11485
            }
11486
            context.updateCharacterBounds(e.rangeStart, rects);
11487
        };
11488
        this.handlers.textformatupdate = e => {
11489
            let deco = [];
11490
            for (let format of e.getTextFormats()) {
11491
                let lineStyle = format.underlineStyle, thickness = format.underlineThickness;
11492
                if (lineStyle != "None" && thickness != "None") {
11493
                    let from = this.toEditorPos(format.rangeStart), to = this.toEditorPos(format.rangeEnd);
11494
                    if (from < to) {
11495
                        let style = `text-decoration: underline ${lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${thickness == "Thin" ? 1 : 2}px`;
11496
                        deco.push(Decoration.mark({ attributes: { style } }).range(from, to));
11497
                    }
11498
                }
11499
            }
11500
            view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) });
11501
        };
11502
        this.handlers.compositionstart = () => {
11503
            if (view.inputState.composing < 0) {
11504
                view.inputState.composing = 0;
11505
                view.inputState.compositionFirstChange = true;
11506
            }
11507
        };
11508
        this.handlers.compositionend = () => {
11509
            view.inputState.composing = -1;
11510
            view.inputState.compositionFirstChange = null;
11511
            if (this.composing) {
11512
                let { drifted } = this.composing;
11513
                this.composing = null;
11514
                if (drifted)
11515
                    this.reset(view.state);
11516
            }
11517
        };
11518
        for (let event in this.handlers)
11519
            context.addEventListener(event, this.handlers[event]);
11520
        this.measureReq = { read: view => {
11521
                this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());
11522
                let sel = getSelection(view.root);
11523
                if (sel && sel.rangeCount)
11524
                    this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect());
11525
            } };
11526
    }
11527
    applyEdits(update) {
11528
        let off = 0, abort = false, pending = this.pendingContextChange;
11529
        update.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {
11530
            if (abort)
11531
                return;
11532
            let dLen = insert.length - (toA - fromA);
11533
            if (pending && toA >= pending.to) {
11534
                if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert)) {
11535
                    pending = this.pendingContextChange = null; // Match
11536
                    off += dLen;
11537
                    this.to += dLen;
11538
                    return;
11539
                }
11540
                else { // Mismatch, revert
11541
                    pending = null;
11542
                    this.revertPending(update.state);
11543
                }
11544
            }
11545
            fromA += off;
11546
            toA += off;
11547
            if (toA <= this.from) { // Before the window
11548
                this.from += dLen;
11549
                this.to += dLen;
11550
            }
11551
            else if (fromA < this.to) { // Overlaps with window
11552
                if (fromA < this.from || toA > this.to || (this.to - this.from) + insert.length > 30000 /* CxVp.MaxSize */) {
11553
                    abort = true;
11554
                    return;
11555
                }
11556
                this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert.toString());
11557
                this.to += dLen;
11558
            }
11559
            off += dLen;
11560
        });
11561
        if (pending && !abort)
11562
            this.revertPending(update.state);
11563
        return !abort;
11564
    }
11565
    update(update) {
11566
        let reverted = this.pendingContextChange, startSel = update.startState.selection.main;
11567
        if (this.composing &&
11568
            (this.composing.drifted ||
11569
                (!update.changes.touchesRange(startSel.from, startSel.to) &&
11570
                    update.transactions.some(tr => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to))))) {
11571
            this.composing.drifted = true;
11572
            this.composing.editorBase = update.changes.mapPos(this.composing.editorBase);
11573
        }
11574
        else if (!this.applyEdits(update) || !this.rangeIsValid(update.state)) {
11575
            this.pendingContextChange = null;
11576
            this.reset(update.state);
11577
        }
11578
        else if (update.docChanged || update.selectionSet || reverted) {
11579
            this.setSelection(update.state);
11580
        }
11581
        if (update.geometryChanged || update.docChanged || update.selectionSet)
11582
            update.view.requestMeasure(this.measureReq);
11583
    }
11584
    resetRange(state) {
11585
        let { head } = state.selection.main;
11586
        this.from = Math.max(0, head - 10000 /* CxVp.Margin */);
11587
        this.to = Math.min(state.doc.length, head + 10000 /* CxVp.Margin */);
11588
    }
11589
    reset(state) {
11590
        this.resetRange(state);
11591
        this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to));
11592
        this.setSelection(state);
11593
    }
11594
    revertPending(state) {
11595
        let pending = this.pendingContextChange;
11596
        this.pendingContextChange = null;
11597
        this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to));
11598
    }
11599
    setSelection(state) {
11600
        let { main } = state.selection;
11601
        let start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor)));
11602
        let end = this.toContextPos(main.head);
11603
        if (this.editContext.selectionStart != start || this.editContext.selectionEnd != end)
11604
            this.editContext.updateSelection(start, end);
11605
    }
11606
    rangeIsValid(state) {
11607
        let { head } = state.selection.main;
11608
        return !(this.from > 0 && head - this.from < 500 /* CxVp.MinMargin */ ||
11609
            this.to < state.doc.length && this.to - head < 500 /* CxVp.MinMargin */ ||
11610
            this.to - this.from > 10000 /* CxVp.Margin */ * 3);
11611
    }
11612
    toEditorPos(contextPos, clipLen = this.to - this.from) {
11613
        contextPos = Math.min(contextPos, clipLen);
11614
        let c = this.composing;
11615
        return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from;
11616
    }
11617
    toContextPos(editorPos) {
11618
        let c = this.composing;
11619
        return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from;
11620
    }
11621
    destroy() {
11622
        for (let event in this.handlers)
11623
            this.editContext.removeEventListener(event, this.handlers[event]);
11624
    }
11625
}
1 efrain 11626
 
11627
// The editor's update state machine looks something like this:
11628
//
11629
//     Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle
11630
//                                         ↑      ↓
11631
//                                         Updating (measure)
11632
//
11633
// The difference between 'Idle' and 'Idle (unchecked)' lies in
11634
// whether a layout check has been scheduled. A regular update through
11635
// the `update` method updates the DOM in a write-only fashion, and
11636
// relies on a check (scheduled with `requestAnimationFrame`) to make
11637
// sure everything is where it should be and the viewport covers the
11638
// visible code. That check continues to measure and then optionally
11639
// update until it reaches a coherent state.
11640
/**
11641
An editor view represents the editor's user interface. It holds
11642
the editable DOM surface, and possibly other elements such as the
11643
line number gutter. It handles events and dispatches state
11644
transactions for editing actions.
11645
*/
11646
class EditorView {
11647
    /**
11648
    The current editor state.
11649
    */
11650
    get state() { return this.viewState.state; }
11651
    /**
11652
    To be able to display large documents without consuming too much
11653
    memory or overloading the browser, CodeMirror only draws the
11654
    code that is visible (plus a margin around it) to the DOM. This
11655
    property tells you the extent of the current drawn viewport, in
11656
    document positions.
11657
    */
11658
    get viewport() { return this.viewState.viewport; }
11659
    /**
11660
    When there are, for example, large collapsed ranges in the
11661
    viewport, its size can be a lot bigger than the actual visible
11662
    content. Thus, if you are doing something like styling the
11663
    content in the viewport, it is preferable to only do so for
11664
    these ranges, which are the subset of the viewport that is
11665
    actually drawn.
11666
    */
11667
    get visibleRanges() { return this.viewState.visibleRanges; }
11668
    /**
11669
    Returns false when the editor is entirely scrolled out of view
11670
    or otherwise hidden.
11671
    */
11672
    get inView() { return this.viewState.inView; }
11673
    /**
11674
    Indicates whether the user is currently composing text via
11675
    [IME](https://en.wikipedia.org/wiki/Input_method), and at least
11676
    one change has been made in the current composition.
11677
    */
11678
    get composing() { return this.inputState.composing > 0; }
11679
    /**
11680
    Indicates whether the user is currently in composing state. Note
11681
    that on some platforms, like Android, this will be the case a
11682
    lot, since just putting the cursor on a word starts a
11683
    composition there.
11684
    */
11685
    get compositionStarted() { return this.inputState.composing >= 0; }
11686
    /**
11687
    The document or shadow root that the view lives in.
11688
    */
11689
    get root() { return this._root; }
11690
    /**
11691
    @internal
11692
    */
11693
    get win() { return this.dom.ownerDocument.defaultView || window; }
11694
    /**
11695
    Construct a new view. You'll want to either provide a `parent`
11696
    option, or put `view.dom` into your document after creating a
11697
    view, so that the user can see the editor.
11698
    */
11699
    constructor(config = {}) {
1441 ariadna 11700
        var _a;
1 efrain 11701
        this.plugins = [];
11702
        this.pluginMap = new Map;
11703
        this.editorAttrs = {};
11704
        this.contentAttrs = {};
11705
        this.bidiCache = [];
11706
        this.destroyed = false;
11707
        /**
11708
        @internal
11709
        */
11710
        this.updateState = 2 /* UpdateState.Updating */;
11711
        /**
11712
        @internal
11713
        */
11714
        this.measureScheduled = -1;
11715
        /**
11716
        @internal
11717
        */
11718
        this.measureRequests = [];
11719
        this.contentDOM = document.createElement("div");
11720
        this.scrollDOM = document.createElement("div");
11721
        this.scrollDOM.tabIndex = -1;
11722
        this.scrollDOM.className = "cm-scroller";
11723
        this.scrollDOM.appendChild(this.contentDOM);
11724
        this.announceDOM = document.createElement("div");
11725
        this.announceDOM.className = "cm-announced";
11726
        this.announceDOM.setAttribute("aria-live", "polite");
11727
        this.dom = document.createElement("div");
11728
        this.dom.appendChild(this.announceDOM);
11729
        this.dom.appendChild(this.scrollDOM);
11730
        if (config.parent)
11731
            config.parent.appendChild(this.dom);
11732
        let { dispatch } = config;
11733
        this.dispatchTransactions = config.dispatchTransactions ||
11734
            (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||
11735
            ((trs) => this.update(trs));
11736
        this.dispatch = this.dispatch.bind(this);
11737
        this._root = (config.root || getRoot(config.parent) || document);
11738
        this.viewState = new ViewState(config.state || EditorState.create(config));
11739
        if (config.scrollTo && config.scrollTo.is(scrollIntoView$1))
11740
            this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);
11741
        this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));
11742
        for (let plugin of this.plugins)
11743
            plugin.update(this);
11744
        this.observer = new DOMObserver(this);
11745
        this.inputState = new InputState(this);
11746
        this.inputState.ensureHandlers(this.plugins);
11747
        this.docView = new DocView(this);
11748
        this.mountStyles();
11749
        this.updateAttrs();
11750
        this.updateState = 0 /* UpdateState.Idle */;
11751
        this.requestMeasure();
1441 ariadna 11752
        if ((_a = document.fonts) === null || _a === void 0 ? void 0 : _a.ready)
11753
            document.fonts.ready.then(() => this.requestMeasure());
1 efrain 11754
    }
11755
    dispatch(...input) {
11756
        let trs = input.length == 1 && input[0] instanceof Transaction ? input
11757
            : input.length == 1 && Array.isArray(input[0]) ? input[0]
11758
                : [this.state.update(...input)];
11759
        this.dispatchTransactions(trs, this);
11760
    }
11761
    /**
11762
    Update the view for the given array of transactions. This will
11763
    update the visible document and selection to match the state
11764
    produced by the transactions, and notify view plugins of the
11765
    change. You should usually call
11766
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
11767
    as a primitive.
11768
    */
11769
    update(transactions) {
11770
        if (this.updateState != 0 /* UpdateState.Idle */)
11771
            throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
11772
        let redrawn = false, attrsChanged = false, update;
11773
        let state = this.state;
11774
        for (let tr of transactions) {
11775
            if (tr.startState != state)
11776
                throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
11777
            state = tr.state;
11778
        }
11779
        if (this.destroyed) {
11780
            this.viewState.state = state;
11781
            return;
11782
        }
11783
        let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
11784
        if (transactions.some(tr => tr.annotation(isFocusChange))) {
11785
            this.inputState.notifiedFocused = focus;
11786
            // If a focus-change transaction is being dispatched, set this update flag.
11787
            focusFlag = 1 /* UpdateFlag.Focus */;
11788
        }
11789
        else if (focus != this.inputState.notifiedFocused) {
11790
            this.inputState.notifiedFocused = focus;
11791
            // Schedule a separate focus transaction if necessary, otherwise
11792
            // add a flag to this update
11793
            dispatchFocus = focusChangeTransaction(state, focus);
11794
            if (!dispatchFocus)
11795
                focusFlag = 1 /* UpdateFlag.Focus */;
11796
        }
11797
        // If there was a pending DOM change, eagerly read it and try to
11798
        // apply it after the given transactions.
11799
        let pendingKey = this.observer.delayedAndroidKey, domChange = null;
11800
        if (pendingKey) {
11801
            this.observer.clearDelayedAndroidKey();
11802
            domChange = this.observer.readChange();
11803
            // Only try to apply DOM changes if the transactions didn't
11804
            // change the doc or selection.
11805
            if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
11806
                domChange = null;
11807
        }
11808
        else {
11809
            this.observer.clear();
11810
        }
11811
        // When the phrases change, redraw the editor
11812
        if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
11813
            return this.setState(state);
11814
        update = ViewUpdate.create(this, state, transactions);
11815
        update.flags |= focusFlag;
11816
        let scrollTarget = this.viewState.scrollTarget;
11817
        try {
11818
            this.updateState = 2 /* UpdateState.Updating */;
11819
            for (let tr of transactions) {
11820
                if (scrollTarget)
11821
                    scrollTarget = scrollTarget.map(tr.changes);
11822
                if (tr.scrollIntoView) {
11823
                    let { main } = tr.state.selection;
11824
                    scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
11825
                }
11826
                for (let e of tr.effects)
11827
                    if (e.is(scrollIntoView$1))
11828
                        scrollTarget = e.value.clip(this.state);
11829
            }
11830
            this.viewState.update(update, scrollTarget);
11831
            this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
11832
            if (!update.empty) {
11833
                this.updatePlugins(update);
11834
                this.inputState.update(update);
11835
            }
11836
            redrawn = this.docView.update(update);
11837
            if (this.state.facet(styleModule) != this.styleModules)
11838
                this.mountStyles();
11839
            attrsChanged = this.updateAttrs();
11840
            this.showAnnouncements(transactions);
11841
            this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
11842
        }
11843
        finally {
11844
            this.updateState = 0 /* UpdateState.Idle */;
11845
        }
11846
        if (update.startState.facet(theme) != update.state.facet(theme))
11847
            this.viewState.mustMeasureContent = true;
11848
        if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
11849
            this.requestMeasure();
11850
        if (redrawn)
11851
            this.docViewUpdate();
11852
        if (!update.empty)
11853
            for (let listener of this.state.facet(updateListener)) {
11854
                try {
11855
                    listener(update);
11856
                }
11857
                catch (e) {
11858
                    logException(this.state, e, "update listener");
11859
                }
11860
            }
11861
        if (dispatchFocus || domChange)
11862
            Promise.resolve().then(() => {
11863
                if (dispatchFocus && this.state == dispatchFocus.startState)
11864
                    this.dispatch(dispatchFocus);
11865
                if (domChange) {
11866
                    if (!applyDOMChange(this, domChange) && pendingKey.force)
11867
                        dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
11868
                }
11869
            });
11870
    }
11871
    /**
11872
    Reset the view to the given state. (This will cause the entire
11873
    document to be redrawn and all view plugins to be reinitialized,
11874
    so you should probably only use it when the new state isn't
11875
    derived from the old state. Otherwise, use
11876
    [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
11877
    */
11878
    setState(newState) {
11879
        if (this.updateState != 0 /* UpdateState.Idle */)
11880
            throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
11881
        if (this.destroyed) {
11882
            this.viewState.state = newState;
11883
            return;
11884
        }
11885
        this.updateState = 2 /* UpdateState.Updating */;
11886
        let hadFocus = this.hasFocus;
11887
        try {
11888
            for (let plugin of this.plugins)
11889
                plugin.destroy(this);
11890
            this.viewState = new ViewState(newState);
11891
            this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));
11892
            this.pluginMap.clear();
11893
            for (let plugin of this.plugins)
11894
                plugin.update(this);
11895
            this.docView.destroy();
11896
            this.docView = new DocView(this);
11897
            this.inputState.ensureHandlers(this.plugins);
11898
            this.mountStyles();
11899
            this.updateAttrs();
11900
            this.bidiCache = [];
11901
        }
11902
        finally {
11903
            this.updateState = 0 /* UpdateState.Idle */;
11904
        }
11905
        if (hadFocus)
11906
            this.focus();
11907
        this.requestMeasure();
11908
    }
11909
    updatePlugins(update) {
11910
        let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
11911
        if (prevSpecs != specs) {
11912
            let newPlugins = [];
11913
            for (let spec of specs) {
11914
                let found = prevSpecs.indexOf(spec);
11915
                if (found < 0) {
11916
                    newPlugins.push(new PluginInstance(spec));
11917
                }
11918
                else {
11919
                    let plugin = this.plugins[found];
11920
                    plugin.mustUpdate = update;
11921
                    newPlugins.push(plugin);
11922
                }
11923
            }
11924
            for (let plugin of this.plugins)
11925
                if (plugin.mustUpdate != update)
11926
                    plugin.destroy(this);
11927
            this.plugins = newPlugins;
11928
            this.pluginMap.clear();
11929
        }
11930
        else {
11931
            for (let p of this.plugins)
11932
                p.mustUpdate = update;
11933
        }
11934
        for (let i = 0; i < this.plugins.length; i++)
11935
            this.plugins[i].update(this);
11936
        if (prevSpecs != specs)
11937
            this.inputState.ensureHandlers(this.plugins);
11938
    }
11939
    docViewUpdate() {
11940
        for (let plugin of this.plugins) {
11941
            let val = plugin.value;
11942
            if (val && val.docViewUpdate) {
11943
                try {
11944
                    val.docViewUpdate(this);
11945
                }
11946
                catch (e) {
11947
                    logException(this.state, e, "doc view update listener");
11948
                }
11949
            }
11950
        }
11951
    }
11952
    /**
11953
    @internal
11954
    */
11955
    measure(flush = true) {
11956
        if (this.destroyed)
11957
            return;
11958
        if (this.measureScheduled > -1)
11959
            this.win.cancelAnimationFrame(this.measureScheduled);
11960
        if (this.observer.delayedAndroidKey) {
11961
            this.measureScheduled = -1;
11962
            this.requestMeasure();
11963
            return;
11964
        }
11965
        this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame
11966
        if (flush)
11967
            this.observer.forceFlush();
11968
        let updated = null;
11969
        let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
11970
        let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
11971
        if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
11972
            scrollAnchorHeight = -1;
11973
        this.viewState.scrollAnchorHeight = -1;
11974
        try {
11975
            for (let i = 0;; i++) {
11976
                if (scrollAnchorHeight < 0) {
11977
                    if (isScrolledToBottom(sDOM)) {
11978
                        scrollAnchorPos = -1;
11979
                        scrollAnchorHeight = this.viewState.heightMap.height;
11980
                    }
11981
                    else {
11982
                        let block = this.viewState.scrollAnchorAt(scrollTop);
11983
                        scrollAnchorPos = block.from;
11984
                        scrollAnchorHeight = block.top;
11985
                    }
11986
                }
11987
                this.updateState = 1 /* UpdateState.Measuring */;
11988
                let changed = this.viewState.measure(this);
11989
                if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
11990
                    break;
11991
                if (i > 5) {
11992
                    console.warn(this.measureRequests.length
11993
                        ? "Measure loop restarted more than 5 times"
11994
                        : "Viewport failed to stabilize");
11995
                    break;
11996
                }
11997
                let measuring = [];
11998
                // Only run measure requests in this cycle when the viewport didn't change
11999
                if (!(changed & 4 /* UpdateFlag.Viewport */))
12000
                    [this.measureRequests, measuring] = [measuring, this.measureRequests];
12001
                let measured = measuring.map(m => {
12002
                    try {
12003
                        return m.read(this);
12004
                    }
12005
                    catch (e) {
12006
                        logException(this.state, e);
12007
                        return BadMeasure;
12008
                    }
12009
                });
12010
                let update = ViewUpdate.create(this, this.state, []), redrawn = false;
12011
                update.flags |= changed;
12012
                if (!updated)
12013
                    updated = update;
12014
                else
12015
                    updated.flags |= changed;
12016
                this.updateState = 2 /* UpdateState.Updating */;
12017
                if (!update.empty) {
12018
                    this.updatePlugins(update);
12019
                    this.inputState.update(update);
12020
                    this.updateAttrs();
12021
                    redrawn = this.docView.update(update);
12022
                    if (redrawn)
12023
                        this.docViewUpdate();
12024
                }
12025
                for (let i = 0; i < measuring.length; i++)
12026
                    if (measured[i] != BadMeasure) {
12027
                        try {
12028
                            let m = measuring[i];
12029
                            if (m.write)
12030
                                m.write(measured[i], this);
12031
                        }
12032
                        catch (e) {
12033
                            logException(this.state, e);
12034
                        }
12035
                    }
12036
                if (redrawn)
12037
                    this.docView.updateSelection(true);
12038
                if (!update.viewportChanged && this.measureRequests.length == 0) {
12039
                    if (this.viewState.editorHeight) {
12040
                        if (this.viewState.scrollTarget) {
12041
                            this.docView.scrollIntoView(this.viewState.scrollTarget);
12042
                            this.viewState.scrollTarget = null;
12043
                            scrollAnchorHeight = -1;
12044
                            continue;
12045
                        }
12046
                        else {
12047
                            let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :
12048
                                this.viewState.lineBlockAt(scrollAnchorPos).top;
12049
                            let diff = newAnchorHeight - scrollAnchorHeight;
12050
                            if (diff > 1 || diff < -1) {
12051
                                scrollTop = scrollTop + diff;
12052
                                sDOM.scrollTop = scrollTop / this.scaleY;
12053
                                scrollAnchorHeight = -1;
12054
                                continue;
12055
                            }
12056
                        }
12057
                    }
12058
                    break;
12059
                }
12060
            }
12061
        }
12062
        finally {
12063
            this.updateState = 0 /* UpdateState.Idle */;
12064
            this.measureScheduled = -1;
12065
        }
12066
        if (updated && !updated.empty)
12067
            for (let listener of this.state.facet(updateListener))
12068
                listener(updated);
12069
    }
12070
    /**
12071
    Get the CSS classes for the currently active editor themes.
12072
    */
12073
    get themeClasses() {
12074
        return baseThemeID + " " +
12075
            (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " +
12076
            this.state.facet(theme);
12077
    }
12078
    updateAttrs() {
12079
        let editorAttrs = attrsFromFacet(this, editorAttributes, {
12080
            class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
12081
        });
12082
        let contentAttrs = {
12083
            spellcheck: "false",
12084
            autocorrect: "off",
12085
            autocapitalize: "off",
1441 ariadna 12086
            writingsuggestions: "false",
1 efrain 12087
            translate: "no",
12088
            contenteditable: !this.state.facet(editable) ? "false" : "true",
12089
            class: "cm-content",
12090
            style: `${browser.tabSize}: ${this.state.tabSize}`,
12091
            role: "textbox",
12092
            "aria-multiline": "true"
12093
        };
12094
        if (this.state.readOnly)
12095
            contentAttrs["aria-readonly"] = "true";
12096
        attrsFromFacet(this, contentAttributes, contentAttrs);
12097
        let changed = this.observer.ignore(() => {
12098
            let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
12099
            let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
12100
            return changedContent || changedEditor;
12101
        });
12102
        this.editorAttrs = editorAttrs;
12103
        this.contentAttrs = contentAttrs;
12104
        return changed;
12105
    }
12106
    showAnnouncements(trs) {
12107
        let first = true;
12108
        for (let tr of trs)
12109
            for (let effect of tr.effects)
12110
                if (effect.is(EditorView.announce)) {
12111
                    if (first)
12112
                        this.announceDOM.textContent = "";
12113
                    first = false;
12114
                    let div = this.announceDOM.appendChild(document.createElement("div"));
12115
                    div.textContent = effect.value;
12116
                }
12117
    }
12118
    mountStyles() {
12119
        this.styleModules = this.state.facet(styleModule);
12120
        let nonce = this.state.facet(EditorView.cspNonce);
12121
        StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$3).reverse(), nonce ? { nonce } : undefined);
12122
    }
12123
    readMeasured() {
12124
        if (this.updateState == 2 /* UpdateState.Updating */)
12125
            throw new Error("Reading the editor layout isn't allowed during an update");
12126
        if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)
12127
            this.measure(false);
12128
    }
12129
    /**
12130
    Schedule a layout measurement, optionally providing callbacks to
12131
    do custom DOM measuring followed by a DOM write phase. Using
12132
    this is preferable reading DOM layout directly from, for
12133
    example, an event handler, because it'll make sure measuring and
12134
    drawing done by other components is synchronized, avoiding
12135
    unnecessary DOM layout computations.
12136
    */
12137
    requestMeasure(request) {
12138
        if (this.measureScheduled < 0)
12139
            this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
12140
        if (request) {
12141
            if (this.measureRequests.indexOf(request) > -1)
12142
                return;
12143
            if (request.key != null)
12144
                for (let i = 0; i < this.measureRequests.length; i++) {
12145
                    if (this.measureRequests[i].key === request.key) {
12146
                        this.measureRequests[i] = request;
12147
                        return;
12148
                    }
12149
                }
12150
            this.measureRequests.push(request);
12151
        }
12152
    }
12153
    /**
12154
    Get the value of a specific plugin, if present. Note that
12155
    plugins that crash can be dropped from a view, so even when you
12156
    know you registered a given plugin, it is recommended to check
12157
    the return value of this method.
12158
    */
12159
    plugin(plugin) {
12160
        let known = this.pluginMap.get(plugin);
12161
        if (known === undefined || known && known.spec != plugin)
12162
            this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);
12163
        return known && known.update(this).value;
12164
    }
12165
    /**
12166
    The top position of the document, in screen coordinates. This
12167
    may be negative when the editor is scrolled down. Points
12168
    directly to the top of the first line, not above the padding.
12169
    */
12170
    get documentTop() {
12171
        return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
12172
    }
12173
    /**
12174
    Reports the padding above and below the document.
12175
    */
12176
    get documentPadding() {
12177
        return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
12178
    }
12179
    /**
12180
    If the editor is transformed with CSS, this provides the scale
12181
    along the X axis. Otherwise, it will just be 1. Note that
12182
    transforms other than translation and scaling are not supported.
12183
    */
12184
    get scaleX() { return this.viewState.scaleX; }
12185
    /**
12186
    Provide the CSS transformed scale along the Y axis.
12187
    */
12188
    get scaleY() { return this.viewState.scaleY; }
12189
    /**
12190
    Find the text line or block widget at the given vertical
12191
    position (which is interpreted as relative to the [top of the
12192
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
12193
    */
12194
    elementAtHeight(height) {
12195
        this.readMeasured();
12196
        return this.viewState.elementAtHeight(height);
12197
    }
12198
    /**
12199
    Find the line block (see
12200
    [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
12201
    height, again interpreted relative to the [top of the
12202
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
12203
    */
12204
    lineBlockAtHeight(height) {
12205
        this.readMeasured();
12206
        return this.viewState.lineBlockAtHeight(height);
12207
    }
12208
    /**
12209
    Get the extent and vertical position of all [line
12210
    blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
12211
    are relative to the [top of the
12212
    document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
12213
    */
12214
    get viewportLineBlocks() {
12215
        return this.viewState.viewportLines;
12216
    }
12217
    /**
12218
    Find the line block around the given document position. A line
12219
    block is a range delimited on both sides by either a
1441 ariadna 12220
    non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line break, or the
1 efrain 12221
    start/end of the document. It will usually just hold a line of
12222
    text, but may be broken into multiple textblocks by block
12223
    widgets.
12224
    */
12225
    lineBlockAt(pos) {
12226
        return this.viewState.lineBlockAt(pos);
12227
    }
12228
    /**
12229
    The editor's total content height.
12230
    */
12231
    get contentHeight() {
12232
        return this.viewState.contentHeight;
12233
    }
12234
    /**
12235
    Move a cursor position by [grapheme
12236
    cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
12237
    the motion is away from the line start, or towards it. In
12238
    bidirectional text, the line is traversed in visual order, using
12239
    the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
12240
    When the start position was the last one on the line, the
12241
    returned position will be across the line break. If there is no
12242
    further line, the original position is returned.
12243
 
12244
    By default, this method moves over a single cluster. The
12245
    optional `by` argument can be used to move across more. It will
12246
    be called with the first cluster as argument, and should return
12247
    a predicate that determines, for each subsequent cluster,
12248
    whether it should also be moved over.
12249
    */
12250
    moveByChar(start, forward, by) {
12251
        return skipAtoms(this, start, moveByChar(this, start, forward, by));
12252
    }
12253
    /**
12254
    Move a cursor position across the next group of either
12255
    [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
12256
    non-whitespace characters.
12257
    */
12258
    moveByGroup(start, forward) {
12259
        return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));
12260
    }
12261
    /**
12262
    Get the cursor position visually at the start or end of a line.
12263
    Note that this may differ from the _logical_ position at its
12264
    start or end (which is simply at `line.from`/`line.to`) if text
12265
    at the start or end goes against the line's base text direction.
12266
    */
12267
    visualLineSide(line, end) {
12268
        let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from);
12269
        let span = order[end ? order.length - 1 : 0];
12270
        return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
12271
    }
12272
    /**
12273
    Move to the next line boundary in the given direction. If
12274
    `includeWrap` is true, line wrapping is on, and there is a
12275
    further wrap point on the current line, the wrap point will be
12276
    returned. Otherwise this function will return the start or end
12277
    of the line.
12278
    */
12279
    moveToLineBoundary(start, forward, includeWrap = true) {
12280
        return moveToLineBoundary(this, start, forward, includeWrap);
12281
    }
12282
    /**
12283
    Move a cursor position vertically. When `distance` isn't given,
12284
    it defaults to moving to the next line (including wrapped
12285
    lines). Otherwise, `distance` should provide a positive distance
12286
    in pixels.
12287
 
12288
    When `start` has a
12289
    [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
12290
    motion will use that as a target horizontal position. Otherwise,
12291
    the cursor's own horizontal position is used. The returned
12292
    cursor will have its goal column set to whichever column was
12293
    used.
12294
    */
12295
    moveVertically(start, forward, distance) {
12296
        return skipAtoms(this, start, moveVertically(this, start, forward, distance));
12297
    }
12298
    /**
12299
    Find the DOM parent node and offset (child offset if `node` is
12300
    an element, character offset when it is a text node) at the
12301
    given document position.
12302
 
12303
    Note that for positions that aren't currently in
12304
    `visibleRanges`, the resulting DOM position isn't necessarily
12305
    meaningful (it may just point before or after a placeholder
12306
    element).
12307
    */
12308
    domAtPos(pos) {
12309
        return this.docView.domAtPos(pos);
12310
    }
12311
    /**
12312
    Find the document position at the given DOM node. Can be useful
12313
    for associating positions with DOM events. Will raise an error
12314
    when `node` isn't part of the editor content.
12315
    */
12316
    posAtDOM(node, offset = 0) {
12317
        return this.docView.posFromDOM(node, offset);
12318
    }
12319
    posAtCoords(coords, precise = true) {
12320
        this.readMeasured();
12321
        return posAtCoords(this, coords, precise);
12322
    }
12323
    /**
12324
    Get the screen coordinates at the given document position.
12325
    `side` determines whether the coordinates are based on the
12326
    element before (-1) or after (1) the position (if no element is
12327
    available on the given side, the method will transparently use
12328
    another strategy to get reasonable coordinates).
12329
    */
12330
    coordsAtPos(pos, side = 1) {
12331
        this.readMeasured();
12332
        let rect = this.docView.coordsAt(pos, side);
12333
        if (!rect || rect.left == rect.right)
12334
            return rect;
12335
        let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
12336
        let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
12337
        return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));
12338
    }
12339
    /**
12340
    Return the rectangle around a given character. If `pos` does not
12341
    point in front of a character that is in the viewport and
12342
    rendered (i.e. not replaced, not a line break), this will return
12343
    null. For space characters that are a line wrap point, this will
12344
    return the position before the line break.
12345
    */
12346
    coordsForChar(pos) {
12347
        this.readMeasured();
12348
        return this.docView.coordsForChar(pos);
12349
    }
12350
    /**
12351
    The default width of a character in the editor. May not
12352
    accurately reflect the width of all characters (given variable
12353
    width fonts or styling of invididual ranges).
12354
    */
12355
    get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }
12356
    /**
12357
    The default height of a line in the editor. May not be accurate
12358
    for all lines.
12359
    */
12360
    get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }
12361
    /**
12362
    The text direction
12363
    ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
12364
    CSS property) of the editor's content element.
12365
    */
12366
    get textDirection() { return this.viewState.defaultTextDirection; }
12367
    /**
12368
    Find the text direction of the block at the given position, as
12369
    assigned by CSS. If
12370
    [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
12371
    isn't enabled, or the given position is outside of the viewport,
12372
    this will always return the same as
12373
    [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
12374
    this may trigger a DOM layout.
12375
    */
12376
    textDirectionAt(pos) {
12377
        let perLine = this.state.facet(perLineTextDirection);
12378
        if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
12379
            return this.textDirection;
12380
        this.readMeasured();
12381
        return this.docView.textDirectionAt(pos);
12382
    }
12383
    /**
12384
    Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
12385
    (as determined by the
12386
    [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
12387
    CSS property of its content element).
12388
    */
12389
    get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }
12390
    /**
12391
    Returns the bidirectional text structure of the given line
12392
    (which should be in the current document) as an array of span
12393
    objects. The order of these spans matches the [text
12394
    direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
12395
    left-to-right, the leftmost spans come first, otherwise the
12396
    rightmost spans come first.
12397
    */
12398
    bidiSpans(line) {
12399
        if (line.length > MaxBidiLine)
12400
            return trivialOrder(line.length);
12401
        let dir = this.textDirectionAt(line.from), isolates;
12402
        for (let entry of this.bidiCache) {
12403
            if (entry.from == line.from && entry.dir == dir &&
12404
                (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line))))
12405
                return entry.order;
12406
        }
12407
        if (!isolates)
12408
            isolates = getIsolatedRanges(this, line);
12409
        let order = computeOrder(line.text, dir, isolates);
12410
        this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
12411
        return order;
12412
    }
12413
    /**
12414
    Check whether the editor has focus.
12415
    */
12416
    get hasFocus() {
12417
        var _a;
12418
        // Safari return false for hasFocus when the context menu is open
12419
        // or closing, which leads us to ignore selection changes from the
12420
        // context menu because it looks like the editor isn't focused.
12421
        // This kludges around that.
12422
        return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&
12423
            this.root.activeElement == this.contentDOM;
12424
    }
12425
    /**
12426
    Put focus on the editor.
12427
    */
12428
    focus() {
12429
        this.observer.ignore(() => {
12430
            focusPreventScroll(this.contentDOM);
12431
            this.docView.updateSelection();
12432
        });
12433
    }
12434
    /**
12435
    Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
12436
    necessary when moving the editor's existing DOM to a new window or shadow root.
12437
    */
12438
    setRoot(root) {
12439
        if (this._root != root) {
12440
            this._root = root;
12441
            this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
12442
            this.mountStyles();
12443
        }
12444
    }
12445
    /**
12446
    Clean up this editor view, removing its element from the
12447
    document, unregistering event handlers, and notifying
12448
    plugins. The view instance can no longer be used after
12449
    calling this.
12450
    */
12451
    destroy() {
1441 ariadna 12452
        if (this.root.activeElement == this.contentDOM)
12453
            this.contentDOM.blur();
1 efrain 12454
        for (let plugin of this.plugins)
12455
            plugin.destroy(this);
12456
        this.plugins = [];
12457
        this.inputState.destroy();
12458
        this.docView.destroy();
12459
        this.dom.remove();
12460
        this.observer.destroy();
12461
        if (this.measureScheduled > -1)
12462
            this.win.cancelAnimationFrame(this.measureScheduled);
12463
        this.destroyed = true;
12464
    }
12465
    /**
12466
    Returns an effect that can be
12467
    [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
12468
    cause it to scroll the given position or range into view.
12469
    */
12470
    static scrollIntoView(pos, options = {}) {
12471
        return scrollIntoView$1.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
12472
    }
12473
    /**
12474
    Return an effect that resets the editor to its current (at the
12475
    time this method was called) scroll position. Note that this
12476
    only affects the editor's own scrollable element, not parents.
12477
    See also
12478
    [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
12479
 
12480
    The effect should be used with a document identical to the one
12481
    it was created for. Failing to do so is not an error, but may
12482
    not scroll to the expected position. You can
12483
    [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
12484
    */
12485
    scrollSnapshot() {
12486
        let { scrollTop, scrollLeft } = this.scrollDOM;
12487
        let ref = this.viewState.scrollAnchorAt(scrollTop);
12488
        return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
12489
    }
12490
    /**
1441 ariadna 12491
    Enable or disable tab-focus mode, which disables key bindings
12492
    for Tab and Shift-Tab, letting the browser's default
12493
    focus-changing behavior go through instead. This is useful to
12494
    prevent trapping keyboard users in your editor.
12495
 
12496
    Without argument, this toggles the mode. With a boolean, it
12497
    enables (true) or disables it (false). Given a number, it
12498
    temporarily enables the mode until that number of milliseconds
12499
    have passed or another non-Tab key is pressed.
12500
    */
12501
    setTabFocusMode(to) {
12502
        if (to == null)
12503
            this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1;
12504
        else if (typeof to == "boolean")
12505
            this.inputState.tabFocusMode = to ? 0 : -1;
12506
        else if (this.inputState.tabFocusMode != 0)
12507
            this.inputState.tabFocusMode = Date.now() + to;
12508
    }
12509
    /**
1 efrain 12510
    Returns an extension that can be used to add DOM event handlers.
12511
    The value should be an object mapping event names to handler
12512
    functions. For any given event, such functions are ordered by
12513
    extension precedence, and the first handler to return true will
12514
    be assumed to have handled that event, and no other handlers or
12515
    built-in behavior will be activated for it. These are registered
12516
    on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
12517
    for `scroll` handlers, which will be called any time the
12518
    editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
12519
    its parent nodes is scrolled.
12520
    */
12521
    static domEventHandlers(handlers) {
12522
        return ViewPlugin.define(() => ({}), { eventHandlers: handlers });
12523
    }
12524
    /**
12525
    Create an extension that registers DOM event observers. Contrary
12526
    to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
12527
    observers can't be prevented from running by a higher-precedence
12528
    handler returning true. They also don't prevent other handlers
12529
    and observers from running when they return true, and should not
12530
    call `preventDefault`.
12531
    */
12532
    static domEventObservers(observers) {
12533
        return ViewPlugin.define(() => ({}), { eventObservers: observers });
12534
    }
12535
    /**
12536
    Create a theme extension. The first argument can be a
12537
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)
12538
    style spec providing the styles for the theme. These will be
12539
    prefixed with a generated class for the style.
12540
 
12541
    Because the selectors will be prefixed with a scope class, rule
12542
    that directly match the editor's [wrapper
12543
    element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
12544
    added—need to be explicitly differentiated by adding an `&` to
12545
    the selector for that element—for example
12546
    `&.cm-focused`.
12547
 
12548
    When `dark` is set to true, the theme will be marked as dark,
12549
    which will cause the `&dark` rules from [base
12550
    themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
12551
    `&light` when a light theme is active).
12552
    */
12553
    static theme(spec, options) {
12554
        let prefix = StyleModule.newName();
12555
        let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
12556
        if (options && options.dark)
12557
            result.push(darkTheme.of(true));
12558
        return result;
12559
    }
12560
    /**
12561
    Create an extension that adds styles to the base theme. Like
12562
    with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
12563
    place of the editor wrapper element when directly targeting
12564
    that. You can also use `&dark` or `&light` instead to only
12565
    target editors with a dark or light theme.
12566
    */
12567
    static baseTheme(spec) {
12568
        return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
12569
    }
12570
    /**
12571
    Retrieve an editor view instance from the view's DOM
12572
    representation.
12573
    */
12574
    static findFromDOM(dom) {
12575
        var _a;
12576
        let content = dom.querySelector(".cm-content");
12577
        let cView = content && ContentView.get(content) || ContentView.get(dom);
12578
        return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null;
12579
    }
12580
}
12581
/**
12582
Facet to add a [style
12583
module](https://github.com/marijnh/style-mod#documentation) to
12584
an editor view. The view will ensure that the module is
12585
mounted in its [document
12586
root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
12587
*/
12588
EditorView.styleModule = styleModule;
12589
/**
12590
An input handler can override the way changes to the editable
12591
DOM content are handled. Handlers are passed the document
12592
positions between which the change was found, and the new
12593
content. When one returns true, no further input handlers are
12594
called and the default behavior is prevented.
12595
 
12596
The `insert` argument can be used to get the default transaction
12597
that would be applied for this input. This can be useful when
12598
dispatching the custom behavior as a separate transaction.
12599
*/
12600
EditorView.inputHandler = inputHandler$1;
12601
/**
1441 ariadna 12602
Functions provided in this facet will be used to transform text
12603
pasted or dropped into the editor.
12604
*/
12605
EditorView.clipboardInputFilter = clipboardInputFilter;
12606
/**
12607
Transform text copied or dragged from the editor.
12608
*/
12609
EditorView.clipboardOutputFilter = clipboardOutputFilter;
12610
/**
1 efrain 12611
Scroll handlers can override how things are scrolled into view.
12612
If they return `true`, no further handling happens for the
12613
scrolling. If they return false, the default scroll behavior is
12614
applied. Scroll handlers should never initiate editor updates.
12615
*/
12616
EditorView.scrollHandler = scrollHandler;
12617
/**
12618
This facet can be used to provide functions that create effects
12619
to be dispatched when the editor's focus state changes.
12620
*/
12621
EditorView.focusChangeEffect = focusChangeEffect;
12622
/**
12623
By default, the editor assumes all its content has the same
12624
[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
12625
value to make it read the text direction of every (rendered)
12626
line separately.
12627
*/
12628
EditorView.perLineTextDirection = perLineTextDirection;
12629
/**
12630
Allows you to provide a function that should be called when the
12631
library catches an exception from an extension (mostly from view
12632
plugins, but may be used by other extensions to route exceptions
12633
from user-code-provided callbacks). This is mostly useful for
12634
debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
12635
*/
12636
EditorView.exceptionSink = exceptionSink;
12637
/**
12638
A facet that can be used to register a function to be called
12639
every time the view updates.
12640
*/
12641
EditorView.updateListener = updateListener;
12642
/**
12643
Facet that controls whether the editor content DOM is editable.
12644
When its highest-precedence value is `false`, the element will
12645
not have its `contenteditable` attribute set. (Note that this
12646
doesn't affect API calls that change the editor content, even
12647
when those are bound to keys or buttons. See the
12648
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
12649
*/
12650
EditorView.editable = editable;
12651
/**
12652
Allows you to influence the way mouse selection happens. The
12653
functions in this facet will be called for a `mousedown` event
12654
on the editor, and can return an object that overrides the way a
12655
selection is computed from that mouse click or drag.
12656
*/
12657
EditorView.mouseSelectionStyle = mouseSelectionStyle;
12658
/**
12659
Facet used to configure whether a given selection drag event
12660
should move or copy the selection. The given predicate will be
12661
called with the `mousedown` event, and can return `true` when
12662
the drag should move the content.
12663
*/
12664
EditorView.dragMovesSelection = dragMovesSelection$1;
12665
/**
12666
Facet used to configure whether a given selecting click adds a
12667
new range to the existing selection or replaces it entirely. The
12668
default behavior is to check `event.metaKey` on macOS, and
12669
`event.ctrlKey` elsewhere.
12670
*/
12671
EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
12672
/**
12673
A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
12674
are shown in the view. Decorations can be provided in two
12675
ways—directly, or via a function that takes an editor view.
12676
 
12677
Only decoration sets provided directly are allowed to influence
12678
the editor's vertical layout structure. The ones provided as
12679
functions are called _after_ the new viewport has been computed,
12680
and thus **must not** introduce block widgets or replacing
12681
decorations that cover line breaks.
12682
 
12683
If you want decorated ranges to behave like atomic units for
12684
cursor motion and deletion purposes, also provide the range set
12685
containing the decorations to
12686
[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
12687
*/
12688
EditorView.decorations = decorations;
12689
/**
12690
Facet that works much like
12691
[`decorations`](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), but puts its
12692
inputs at the very bottom of the precedence stack, meaning mark
12693
decorations provided here will only be split by other, partially
12694
overlapping \`outerDecorations\` ranges, and wrap around all
12695
regular decorations. Use this for mark elements that should, as
12696
much as possible, remain in one piece.
12697
*/
12698
EditorView.outerDecorations = outerDecorations;
12699
/**
12700
Used to provide ranges that should be treated as atoms as far as
12701
cursor motion is concerned. This causes methods like
12702
[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
12703
[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
12704
commands built on top of them) to skip across such regions when
12705
a selection endpoint would enter them. This does _not_ prevent
12706
direct programmatic [selection
12707
updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
12708
regions.
12709
*/
12710
EditorView.atomicRanges = atomicRanges;
12711
/**
12712
When range decorations add a `unicode-bidi: isolate` style, they
12713
should also include a
12714
[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
12715
in their decoration spec, and be exposed through this facet, so
12716
that the editor can compute the proper text order. (Other values
12717
for `unicode-bidi`, except of course `normal`, are not
12718
supported.)
12719
*/
12720
EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
12721
/**
12722
Facet that allows extensions to provide additional scroll
12723
margins (space around the sides of the scrolling element that
12724
should be considered invisible). This can be useful when the
12725
plugin introduces elements that cover part of that element (for
12726
example a horizontally fixed gutter).
12727
*/
12728
EditorView.scrollMargins = scrollMargins;
12729
/**
12730
This facet records whether a dark theme is active. The extension
12731
returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
12732
includes an instance of this when the `dark` option is set to
12733
true.
12734
*/
12735
EditorView.darkTheme = darkTheme;
12736
/**
12737
Provides a Content Security Policy nonce to use when creating
12738
the style sheets for the editor. Holds the empty string when no
12739
nonce has been provided.
12740
*/
12741
EditorView.cspNonce = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : "" });
12742
/**
12743
Facet that provides additional DOM attributes for the editor's
12744
editable DOM element.
12745
*/
12746
EditorView.contentAttributes = contentAttributes;
12747
/**
12748
Facet that provides DOM attributes for the editor's outer
12749
element.
12750
*/
12751
EditorView.editorAttributes = editorAttributes;
12752
/**
12753
An extension that enables line wrapping in the editor (by
12754
setting CSS `white-space` to `pre-wrap` in the content).
12755
*/
12756
EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
12757
/**
12758
State effect used to include screen reader announcements in a
12759
transaction. These will be added to the DOM in a visually hidden
12760
element with `aria-live="polite"` set, and should be used to
12761
describe effects that are visually obvious but may not be
12762
noticed by screen reader users (such as moving to the next
12763
search match).
12764
*/
12765
EditorView.announce = /*@__PURE__*/StateEffect.define();
12766
// Maximum line length for which we compute accurate bidi info
12767
const MaxBidiLine = 4096;
12768
const BadMeasure = {};
12769
class CachedOrder {
12770
    constructor(from, to, dir, isolates, fresh, order) {
12771
        this.from = from;
12772
        this.to = to;
12773
        this.dir = dir;
12774
        this.isolates = isolates;
12775
        this.fresh = fresh;
12776
        this.order = order;
12777
    }
12778
    static update(cache, changes) {
12779
        if (changes.empty && !cache.some(c => c.fresh))
12780
            return cache;
12781
        let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
12782
        for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
12783
            let entry = cache[i];
12784
            if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
12785
                result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
12786
        }
12787
        return result;
12788
    }
12789
}
12790
function attrsFromFacet(view, facet, base) {
12791
    for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
12792
        let source = sources[i], value = typeof source == "function" ? source(view) : source;
12793
        if (value)
12794
            combineAttrs(value, base);
12795
    }
12796
    return base;
12797
}
12798
 
12799
const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
12800
function normalizeKeyName(name, platform) {
12801
    const parts = name.split(/-(?!$)/);
12802
    let result = parts[parts.length - 1];
12803
    if (result == "Space")
12804
        result = " ";
12805
    let alt, ctrl, shift, meta;
12806
    for (let i = 0; i < parts.length - 1; ++i) {
12807
        const mod = parts[i];
12808
        if (/^(cmd|meta|m)$/i.test(mod))
12809
            meta = true;
12810
        else if (/^a(lt)?$/i.test(mod))
12811
            alt = true;
12812
        else if (/^(c|ctrl|control)$/i.test(mod))
12813
            ctrl = true;
12814
        else if (/^s(hift)?$/i.test(mod))
12815
            shift = true;
12816
        else if (/^mod$/i.test(mod)) {
12817
            if (platform == "mac")
12818
                meta = true;
12819
            else
12820
                ctrl = true;
12821
        }
12822
        else
12823
            throw new Error("Unrecognized modifier name: " + mod);
12824
    }
12825
    if (alt)
12826
        result = "Alt-" + result;
12827
    if (ctrl)
12828
        result = "Ctrl-" + result;
12829
    if (meta)
12830
        result = "Meta-" + result;
12831
    if (shift)
12832
        result = "Shift-" + result;
12833
    return result;
12834
}
12835
function modifiers(name, event, shift) {
12836
    if (event.altKey)
12837
        name = "Alt-" + name;
12838
    if (event.ctrlKey)
12839
        name = "Ctrl-" + name;
12840
    if (event.metaKey)
12841
        name = "Meta-" + name;
12842
    if (shift !== false && event.shiftKey)
12843
        name = "Shift-" + name;
12844
    return name;
12845
}
12846
const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({
12847
    keydown(event, view) {
12848
        return runHandlers(getKeymap(view.state), event, view, "editor");
12849
    }
12850
}));
12851
/**
12852
Facet used for registering keymaps.
12853
 
12854
You can add multiple keymaps to an editor. Their priorities
12855
determine their precedence (the ones specified early or with high
12856
priority get checked first). When a handler has returned `true`
12857
for a given key, no further handlers are called.
12858
*/
12859
const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents });
12860
const Keymaps = /*@__PURE__*/new WeakMap();
12861
// This is hidden behind an indirection, rather than directly computed
12862
// by the facet, to keep internal types out of the facet's type.
12863
function getKeymap(state) {
12864
    let bindings = state.facet(keymap);
12865
    let map = Keymaps.get(bindings);
12866
    if (!map)
12867
        Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
12868
    return map;
12869
}
12870
/**
12871
Run the key handlers registered for a given scope. The event
12872
object should be a `"keydown"` event. Returns true if any of the
12873
handlers handled it.
12874
*/
12875
function runScopeHandlers(view, event, scope) {
12876
    return runHandlers(getKeymap(view.state), event, view, scope);
12877
}
12878
let storedPrefix = null;
12879
const PrefixTimeout = 4000;
12880
function buildKeymap(bindings, platform = currentPlatform) {
12881
    let bound = Object.create(null);
12882
    let isPrefix = Object.create(null);
12883
    let checkPrefix = (name, is) => {
12884
        let current = isPrefix[name];
12885
        if (current == null)
12886
            isPrefix[name] = is;
12887
        else if (current != is)
12888
            throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix");
12889
    };
12890
    let add = (scope, key, command, preventDefault, stopPropagation) => {
12891
        var _a, _b;
12892
        let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12893
        let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
12894
        for (let i = 1; i < parts.length; i++) {
12895
            let prefix = parts.slice(0, i).join(" ");
12896
            checkPrefix(prefix, true);
12897
            if (!scopeObj[prefix])
12898
                scopeObj[prefix] = {
12899
                    preventDefault: true,
12900
                    stopPropagation: false,
12901
                    run: [(view) => {
12902
                            let ourObj = storedPrefix = { view, prefix, scope };
12903
                            setTimeout(() => { if (storedPrefix == ourObj)
12904
                                storedPrefix = null; }, PrefixTimeout);
12905
                            return true;
12906
                        }]
12907
                };
12908
        }
12909
        let full = parts.join(" ");
12910
        checkPrefix(full, false);
12911
        let binding = scopeObj[full] || (scopeObj[full] = {
12912
            preventDefault: false,
12913
            stopPropagation: false,
12914
            run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
12915
        });
12916
        if (command)
12917
            binding.run.push(command);
12918
        if (preventDefault)
12919
            binding.preventDefault = true;
12920
        if (stopPropagation)
12921
            binding.stopPropagation = true;
12922
    };
12923
    for (let b of bindings) {
12924
        let scopes = b.scope ? b.scope.split(" ") : ["editor"];
12925
        if (b.any)
12926
            for (let scope of scopes) {
12927
                let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12928
                if (!scopeObj._any)
12929
                    scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
1441 ariadna 12930
                let { any } = b;
1 efrain 12931
                for (let key in scopeObj)
1441 ariadna 12932
                    scopeObj[key].run.push(view => any(view, currentKeyEvent));
1 efrain 12933
            }
12934
        let name = b[platform] || b.key;
12935
        if (!name)
12936
            continue;
12937
        for (let scope of scopes) {
12938
            add(scope, name, b.run, b.preventDefault, b.stopPropagation);
12939
            if (b.shift)
12940
                add(scope, "Shift-" + name, b.shift, b.preventDefault, b.stopPropagation);
12941
        }
12942
    }
12943
    return bound;
12944
}
1441 ariadna 12945
let currentKeyEvent = null;
1 efrain 12946
function runHandlers(map, event, view, scope) {
1441 ariadna 12947
    currentKeyEvent = event;
1 efrain 12948
    let name = keyName(event);
12949
    let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " ";
12950
    let prefix = "", handled = false, prevented = false, stopPropagation = false;
12951
    if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
12952
        prefix = storedPrefix.prefix + " ";
12953
        if (modifierCodes.indexOf(event.keyCode) < 0) {
12954
            prevented = true;
12955
            storedPrefix = null;
12956
        }
12957
    }
12958
    let ran = new Set;
12959
    let runFor = (binding) => {
12960
        if (binding) {
12961
            for (let cmd of binding.run)
12962
                if (!ran.has(cmd)) {
12963
                    ran.add(cmd);
1441 ariadna 12964
                    if (cmd(view)) {
1 efrain 12965
                        if (binding.stopPropagation)
12966
                            stopPropagation = true;
12967
                        return true;
12968
                    }
12969
                }
12970
            if (binding.preventDefault) {
12971
                if (binding.stopPropagation)
12972
                    stopPropagation = true;
12973
                prevented = true;
12974
            }
12975
        }
12976
        return false;
12977
    };
12978
    let scopeObj = map[scope], baseName, shiftName;
12979
    if (scopeObj) {
12980
        if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {
12981
            handled = true;
12982
        }
12983
        else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&
12984
            // Ctrl-Alt may be used for AltGr on Windows
12985
            !(browser.windows && event.ctrlKey && event.altKey) &&
12986
            (baseName = base[event.keyCode]) && baseName != name) {
12987
            if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {
12988
                handled = true;
12989
            }
12990
            else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName &&
12991
                runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {
12992
                handled = true;
12993
            }
12994
        }
12995
        else if (isChar && event.shiftKey &&
12996
            runFor(scopeObj[prefix + modifiers(name, event, true)])) {
12997
            handled = true;
12998
        }
12999
        if (!handled && runFor(scopeObj._any))
13000
            handled = true;
13001
    }
13002
    if (prevented)
13003
        handled = true;
13004
    if (handled && stopPropagation)
13005
        event.stopPropagation();
1441 ariadna 13006
    currentKeyEvent = null;
1 efrain 13007
    return handled;
13008
}
13009
 
13010
/**
13011
Implementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates
13012
a rectangle at a given set of coordinates.
13013
*/
13014
class RectangleMarker {
13015
    /**
13016
    Create a marker with the given class and dimensions. If `width`
13017
    is null, the DOM element will get no width style.
13018
    */
13019
    constructor(className,
13020
    /**
13021
    The left position of the marker (in pixels, document-relative).
13022
    */
13023
    left,
13024
    /**
13025
    The top position of the marker.
13026
    */
13027
    top,
13028
    /**
13029
    The width of the marker, or null if it shouldn't get a width assigned.
13030
    */
13031
    width,
13032
    /**
13033
    The height of the marker.
13034
    */
13035
    height) {
13036
        this.className = className;
13037
        this.left = left;
13038
        this.top = top;
13039
        this.width = width;
13040
        this.height = height;
13041
    }
13042
    draw() {
13043
        let elt = document.createElement("div");
13044
        elt.className = this.className;
13045
        this.adjust(elt);
13046
        return elt;
13047
    }
13048
    update(elt, prev) {
13049
        if (prev.className != this.className)
13050
            return false;
13051
        this.adjust(elt);
13052
        return true;
13053
    }
13054
    adjust(elt) {
13055
        elt.style.left = this.left + "px";
13056
        elt.style.top = this.top + "px";
13057
        if (this.width != null)
13058
            elt.style.width = this.width + "px";
13059
        elt.style.height = this.height + "px";
13060
    }
13061
    eq(p) {
13062
        return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&
13063
            this.className == p.className;
13064
    }
13065
    /**
13066
    Create a set of rectangles for the given selection range,
13067
    assigning them theclass`className`. Will create a single
13068
    rectangle for empty ranges, and a set of selection-style
13069
    rectangles covering the range's content (in a bidi-aware
13070
    way) for non-empty ones.
13071
    */
13072
    static forRange(view, className, range) {
13073
        if (range.empty) {
13074
            let pos = view.coordsAtPos(range.head, range.assoc || 1);
13075
            if (!pos)
13076
                return [];
13077
            let base = getBase(view);
13078
            return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];
13079
        }
13080
        else {
13081
            return rectanglesForRange(view, className, range);
13082
        }
13083
    }
13084
}
13085
function getBase(view) {
13086
    let rect = view.scrollDOM.getBoundingClientRect();
13087
    let left = view.textDirection == Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
13088
    return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
13089
}
1441 ariadna 13090
function wrappedLine(view, pos, side, inside) {
13091
    let coords = view.coordsAtPos(pos, side * 2);
13092
    if (!coords)
13093
        return inside;
13094
    let editorRect = view.dom.getBoundingClientRect();
13095
    let y = (coords.top + coords.bottom) / 2;
13096
    let left = view.posAtCoords({ x: editorRect.left + 1, y });
13097
    let right = view.posAtCoords({ x: editorRect.right - 1, y });
13098
    if (left == null || right == null)
13099
        return inside;
13100
    return { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) };
1 efrain 13101
}
13102
function rectanglesForRange(view, className, range) {
13103
    if (range.to <= view.viewport.from || range.from >= view.viewport.to)
13104
        return [];
13105
    let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
13106
    let ltr = view.textDirection == Direction.LTR;
13107
    let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);
13108
    let lineElt = content.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
13109
    let leftSide = contentRect.left +
13110
        (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
13111
    let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
13112
    let startBlock = blockAt(view, from), endBlock = blockAt(view, to);
13113
    let visualStart = startBlock.type == BlockType.Text ? startBlock : null;
13114
    let visualEnd = endBlock.type == BlockType.Text ? endBlock : null;
13115
    if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
1441 ariadna 13116
        visualStart = wrappedLine(view, from, 1, visualStart);
1 efrain 13117
    if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
1441 ariadna 13118
        visualEnd = wrappedLine(view, to, -1, visualEnd);
13119
    if (visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) {
1 efrain 13120
        return pieces(drawForLine(range.from, range.to, visualStart));
13121
    }
13122
    else {
13123
        let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
13124
        let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
13125
        let between = [];
13126
        if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||
13127
            startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)
13128
            between.push(piece(leftSide, top.bottom, rightSide, bottom.top));
13129
        else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == BlockType.Text)
13130
            top.bottom = bottom.top = (top.bottom + bottom.top) / 2;
13131
        return pieces(top).concat(between).concat(pieces(bottom));
13132
    }
13133
    function piece(left, top, right, bottom) {
1441 ariadna 13134
        return new RectangleMarker(className, left - base.left, top - base.top, right - left, bottom - top);
1 efrain 13135
    }
13136
    function pieces({ top, bottom, horizontal }) {
13137
        let pieces = [];
13138
        for (let i = 0; i < horizontal.length; i += 2)
13139
            pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));
13140
        return pieces;
13141
    }
13142
    // Gets passed from/to in line-local positions
13143
    function drawForLine(from, to, line) {
13144
        let top = 1e9, bottom = -1e9, horizontal = [];
13145
        function addSpan(from, fromOpen, to, toOpen, dir) {
13146
            // Passing 2/-2 is a kludge to force the view to return
13147
            // coordinates on the proper side of block widgets, since
13148
            // normalizing the side there, though appropriate for most
13149
            // coordsAtPos queries, would break selection drawing.
13150
            let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));
13151
            let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));
13152
            if (!fromCoords || !toCoords)
13153
                return;
13154
            top = Math.min(fromCoords.top, toCoords.top, top);
13155
            bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
13156
            if (dir == Direction.LTR)
13157
                horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
13158
            else
13159
                horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
13160
        }
13161
        let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;
13162
        // Split the range by visible range and document line
13163
        for (let r of view.visibleRanges)
13164
            if (r.to > start && r.from < end) {
13165
                for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
13166
                    let docLine = view.state.doc.lineAt(pos);
13167
                    for (let span of view.bidiSpans(docLine)) {
13168
                        let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
13169
                        if (spanFrom >= endPos)
13170
                            break;
13171
                        if (spanTo > pos)
13172
                            addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);
13173
                    }
13174
                    pos = docLine.to + 1;
13175
                    if (pos >= endPos)
13176
                        break;
13177
                }
13178
            }
13179
        if (horizontal.length == 0)
13180
            addSpan(start, from == null, end, to == null, view.textDirection);
13181
        return { top, bottom, horizontal };
13182
    }
13183
    function drawForWidget(block, top) {
13184
        let y = contentRect.top + (top ? block.top : block.bottom);
13185
        return { top: y, bottom: y, horizontal: [] };
13186
    }
13187
}
13188
function sameMarker(a, b) {
13189
    return a.constructor == b.constructor && a.eq(b);
13190
}
13191
class LayerView {
13192
    constructor(view, layer) {
13193
        this.view = view;
13194
        this.layer = layer;
13195
        this.drawn = [];
13196
        this.scaleX = 1;
13197
        this.scaleY = 1;
13198
        this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
13199
        this.dom = view.scrollDOM.appendChild(document.createElement("div"));
13200
        this.dom.classList.add("cm-layer");
13201
        if (layer.above)
13202
            this.dom.classList.add("cm-layer-above");
13203
        if (layer.class)
13204
            this.dom.classList.add(layer.class);
13205
        this.scale();
13206
        this.dom.setAttribute("aria-hidden", "true");
13207
        this.setOrder(view.state);
13208
        view.requestMeasure(this.measureReq);
13209
        if (layer.mount)
13210
            layer.mount(this.dom, view);
13211
    }
13212
    update(update) {
13213
        if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))
13214
            this.setOrder(update.state);
13215
        if (this.layer.update(update, this.dom) || update.geometryChanged) {
13216
            this.scale();
13217
            update.view.requestMeasure(this.measureReq);
13218
        }
13219
    }
13220
    docViewUpdate(view) {
13221
        if (this.layer.updateOnDocViewUpdate !== false)
13222
            view.requestMeasure(this.measureReq);
13223
    }
13224
    setOrder(state) {
13225
        let pos = 0, order = state.facet(layerOrder);
13226
        while (pos < order.length && order[pos] != this.layer)
13227
            pos++;
13228
        this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
13229
    }
13230
    measure() {
13231
        return this.layer.markers(this.view);
13232
    }
13233
    scale() {
13234
        let { scaleX, scaleY } = this.view;
13235
        if (scaleX != this.scaleX || scaleY != this.scaleY) {
13236
            this.scaleX = scaleX;
13237
            this.scaleY = scaleY;
13238
            this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
13239
        }
13240
    }
13241
    draw(markers) {
13242
        if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
13243
            let old = this.dom.firstChild, oldI = 0;
13244
            for (let marker of markers) {
13245
                if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&
13246
                    marker.update(old, this.drawn[oldI])) {
13247
                    old = old.nextSibling;
13248
                    oldI++;
13249
                }
13250
                else {
13251
                    this.dom.insertBefore(marker.draw(), old);
13252
                }
13253
            }
13254
            while (old) {
13255
                let next = old.nextSibling;
13256
                old.remove();
13257
                old = next;
13258
            }
13259
            this.drawn = markers;
13260
        }
13261
    }
13262
    destroy() {
13263
        if (this.layer.destroy)
13264
            this.layer.destroy(this.dom, this.view);
13265
        this.dom.remove();
13266
    }
13267
}
13268
const layerOrder = /*@__PURE__*/Facet.define();
13269
/**
13270
Define a layer.
13271
*/
13272
function layer(config) {
13273
    return [
13274
        ViewPlugin.define(v => new LayerView(v, config)),
13275
        layerOrder.of(config)
13276
    ];
13277
}
13278
 
1441 ariadna 13279
const CanHidePrimary = !(browser.ios && browser.webkit && browser.webkit_version < 534);
1 efrain 13280
const selectionConfig = /*@__PURE__*/Facet.define({
13281
    combine(configs) {
13282
        return combineConfig(configs, {
13283
            cursorBlinkRate: 1200,
13284
            drawRangeCursor: true
13285
        }, {
13286
            cursorBlinkRate: (a, b) => Math.min(a, b),
13287
            drawRangeCursor: (a, b) => a || b
13288
        });
13289
    }
13290
});
13291
/**
13292
Returns an extension that hides the browser's native selection and
13293
cursor, replacing the selection with a background behind the text
13294
(with the `cm-selectionBackground` class), and the
13295
cursors with elements overlaid over the code (using
13296
`cm-cursor-primary` and `cm-cursor-secondary`).
13297
 
13298
This allows the editor to display secondary selection ranges, and
13299
tends to produce a type of selection more in line with that users
13300
expect in a text editor (the native selection styling will often
13301
leave gaps between lines and won't fill the horizontal space after
13302
a line when the selection continues past it).
13303
 
13304
It does have a performance cost, in that it requires an extra DOM
13305
layout cycle for many updates (the selection is drawn based on DOM
13306
layout information that's only available after laying out the
13307
content).
13308
*/
13309
function drawSelection(config = {}) {
13310
    return [
13311
        selectionConfig.of(config),
13312
        cursorLayer,
13313
        selectionLayer,
13314
        hideNativeSelection,
13315
        nativeSelectionHidden.of(true)
13316
    ];
13317
}
13318
function configChanged(update) {
13319
    return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
13320
}
13321
const cursorLayer = /*@__PURE__*/layer({
13322
    above: true,
13323
    markers(view) {
13324
        let { state } = view, conf = state.facet(selectionConfig);
13325
        let cursors = [];
13326
        for (let r of state.selection.ranges) {
13327
            let prim = r == state.selection.main;
13328
            if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
13329
                let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
13330
                let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
13331
                for (let piece of RectangleMarker.forRange(view, className, cursor))
13332
                    cursors.push(piece);
13333
            }
13334
        }
13335
        return cursors;
13336
    },
13337
    update(update, dom) {
13338
        if (update.transactions.some(tr => tr.selection))
13339
            dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
13340
        let confChange = configChanged(update);
13341
        if (confChange)
13342
            setBlinkRate(update.state, dom);
13343
        return update.docChanged || update.selectionSet || confChange;
13344
    },
13345
    mount(dom, view) {
13346
        setBlinkRate(view.state, dom);
13347
    },
13348
    class: "cm-cursorLayer"
13349
});
13350
function setBlinkRate(state, dom) {
13351
    dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
13352
}
13353
const selectionLayer = /*@__PURE__*/layer({
13354
    above: false,
13355
    markers(view) {
13356
        return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r))
13357
            .reduce((a, b) => a.concat(b));
13358
    },
13359
    update(update, dom) {
13360
        return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
13361
    },
13362
    class: "cm-selectionLayer"
13363
});
13364
const themeSpec = {
13365
    ".cm-line": {
1441 ariadna 13366
        "& ::selection, &::selection": { backgroundColor: "transparent !important" },
13367
    },
13368
    ".cm-content": {
13369
        "& :focus": {
13370
            caretColor: "initial !important",
13371
            "&::selection, & ::selection": {
13372
                backgroundColor: "Highlight !important"
13373
            }
13374
        }
1 efrain 13375
    }
13376
};
1441 ariadna 13377
if (CanHidePrimary)
13378
    themeSpec[".cm-line"].caretColor = themeSpec[".cm-content"].caretColor = "transparent !important";
1 efrain 13379
const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec));
13380
 
13381
const setDropCursorPos = /*@__PURE__*/StateEffect.define({
13382
    map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }
13383
});
13384
const dropCursorPos = /*@__PURE__*/StateField.define({
13385
    create() { return null; },
13386
    update(pos, tr) {
13387
        if (pos != null)
13388
            pos = tr.changes.mapPos(pos);
13389
        return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);
13390
    }
13391
});
13392
const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class {
13393
    constructor(view) {
13394
        this.view = view;
13395
        this.cursor = null;
13396
        this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
13397
    }
13398
    update(update) {
13399
        var _a;
13400
        let cursorPos = update.state.field(dropCursorPos);
13401
        if (cursorPos == null) {
13402
            if (this.cursor != null) {
13403
                (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();
13404
                this.cursor = null;
13405
            }
13406
        }
13407
        else {
13408
            if (!this.cursor) {
13409
                this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
13410
                this.cursor.className = "cm-dropCursor";
13411
            }
13412
            if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)
13413
                this.view.requestMeasure(this.measureReq);
13414
        }
13415
    }
13416
    readPos() {
13417
        let { view } = this;
13418
        let pos = view.state.field(dropCursorPos);
13419
        let rect = pos != null && view.coordsAtPos(pos);
13420
        if (!rect)
13421
            return null;
13422
        let outer = view.scrollDOM.getBoundingClientRect();
13423
        return {
13424
            left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
13425
            top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
13426
            height: rect.bottom - rect.top
13427
        };
13428
    }
13429
    drawCursor(pos) {
13430
        if (this.cursor) {
13431
            let { scaleX, scaleY } = this.view;
13432
            if (pos) {
13433
                this.cursor.style.left = pos.left / scaleX + "px";
13434
                this.cursor.style.top = pos.top / scaleY + "px";
13435
                this.cursor.style.height = pos.height / scaleY + "px";
13436
            }
13437
            else {
13438
                this.cursor.style.left = "-100000px";
13439
            }
13440
        }
13441
    }
13442
    destroy() {
13443
        if (this.cursor)
13444
            this.cursor.remove();
13445
    }
13446
    setDropPos(pos) {
13447
        if (this.view.state.field(dropCursorPos) != pos)
13448
            this.view.dispatch({ effects: setDropCursorPos.of(pos) });
13449
    }
13450
}, {
13451
    eventObservers: {
13452
        dragover(event) {
13453
            this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));
13454
        },
13455
        dragleave(event) {
13456
            if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))
13457
                this.setDropPos(null);
13458
        },
13459
        dragend() {
13460
            this.setDropPos(null);
13461
        },
13462
        drop() {
13463
            this.setDropPos(null);
13464
        }
13465
    }
13466
});
13467
/**
13468
Draws a cursor at the current drop position when something is
13469
dragged over the editor.
13470
*/
13471
function dropCursor() {
13472
    return [dropCursorPos, drawDropCursor];
13473
}
13474
 
13475
function iterMatches(doc, re, from, to, f) {
13476
    re.lastIndex = 0;
13477
    for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
13478
        if (!cursor.lineBreak)
13479
            while (m = re.exec(cursor.value))
13480
                f(pos + m.index, m);
13481
    }
13482
}
13483
function matchRanges(view, maxLength) {
13484
    let visible = view.visibleRanges;
13485
    if (visible.length == 1 && visible[0].from == view.viewport.from &&
13486
        visible[0].to == view.viewport.to)
13487
        return visible;
13488
    let result = [];
13489
    for (let { from, to } of visible) {
13490
        from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
13491
        to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
13492
        if (result.length && result[result.length - 1].to >= from)
13493
            result[result.length - 1].to = to;
13494
        else
13495
            result.push({ from, to });
13496
    }
13497
    return result;
13498
}
13499
/**
13500
Helper class used to make it easier to maintain decorations on
13501
visible code that matches a given regular expression. To be used
13502
in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object
13503
represent a matching configuration.
13504
*/
13505
class MatchDecorator {
13506
    /**
13507
    Create a decorator.
13508
    */
13509
    constructor(config) {
13510
        const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;
13511
        if (!regexp.global)
13512
            throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
13513
        this.regexp = regexp;
13514
        if (decorate) {
13515
            this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);
13516
        }
13517
        else if (typeof decoration == "function") {
13518
            this.addMatch = (match, view, from, add) => {
13519
                let deco = decoration(match, view, from);
13520
                if (deco)
13521
                    add(from, from + match[0].length, deco);
13522
            };
13523
        }
13524
        else if (decoration) {
13525
            this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);
13526
        }
13527
        else {
13528
            throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
13529
        }
13530
        this.boundary = boundary;
13531
        this.maxLength = maxLength;
13532
    }
13533
    /**
13534
    Compute the full set of decorations for matches in the given
13535
    view's viewport. You'll want to call this when initializing your
13536
    plugin.
13537
    */
13538
    createDeco(view) {
13539
        let build = new RangeSetBuilder(), add = build.add.bind(build);
13540
        for (let { from, to } of matchRanges(view, this.maxLength))
13541
            iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));
13542
        return build.finish();
13543
    }
13544
    /**
13545
    Update a set of decorations for a view update. `deco` _must_ be
13546
    the set of decorations produced by _this_ `MatchDecorator` for
13547
    the view state before the update.
13548
    */
13549
    updateDeco(update, deco) {
13550
        let changeFrom = 1e9, changeTo = -1;
13551
        if (update.docChanged)
13552
            update.changes.iterChanges((_f, _t, from, to) => {
1441 ariadna 13553
                if (to >= update.view.viewport.from && from <= update.view.viewport.to) {
1 efrain 13554
                    changeFrom = Math.min(from, changeFrom);
13555
                    changeTo = Math.max(to, changeTo);
13556
                }
13557
            });
1441 ariadna 13558
        if (update.viewportMoved || changeTo - changeFrom > 1000)
1 efrain 13559
            return this.createDeco(update.view);
13560
        if (changeTo > -1)
13561
            return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
13562
        return deco;
13563
    }
13564
    updateRange(view, deco, updateFrom, updateTo) {
13565
        for (let r of view.visibleRanges) {
13566
            let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
13567
            if (to > from) {
13568
                let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
13569
                let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
13570
                if (this.boundary) {
13571
                    for (; from > fromLine.from; from--)
13572
                        if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
13573
                            start = from;
13574
                            break;
13575
                        }
13576
                    for (; to < toLine.to; to++)
13577
                        if (this.boundary.test(toLine.text[to - toLine.from])) {
13578
                            end = to;
13579
                            break;
13580
                        }
13581
                }
13582
                let ranges = [], m;
13583
                let add = (from, to, deco) => ranges.push(deco.range(from, to));
13584
                if (fromLine == toLine) {
13585
                    this.regexp.lastIndex = start - fromLine.from;
13586
                    while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
13587
                        this.addMatch(m, view, m.index + fromLine.from, add);
13588
                }
13589
                else {
13590
                    iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));
13591
                }
13592
                deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });
13593
            }
13594
        }
13595
        return deco;
13596
    }
13597
}
13598
 
13599
const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
13600
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);
13601
const Names = {
13602
    0: "null",
13603
    7: "bell",
13604
    8: "backspace",
13605
    10: "newline",
13606
    11: "vertical tab",
13607
    13: "carriage return",
13608
    27: "escape",
13609
    8203: "zero width space",
13610
    8204: "zero width non-joiner",
13611
    8205: "zero width joiner",
13612
    8206: "left-to-right mark",
13613
    8207: "right-to-left mark",
13614
    8232: "line separator",
13615
    8237: "left-to-right override",
13616
    8238: "right-to-left override",
13617
    8294: "left-to-right isolate",
13618
    8295: "right-to-left isolate",
13619
    8297: "pop directional isolate",
13620
    8233: "paragraph separator",
13621
    65279: "zero width no-break space",
13622
    65532: "object replacement"
13623
};
13624
let _supportsTabSize = null;
13625
function supportsTabSize() {
13626
    var _a;
13627
    if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
13628
        let styles = document.body.style;
13629
        _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;
13630
    }
13631
    return _supportsTabSize || false;
13632
}
13633
const specialCharConfig = /*@__PURE__*/Facet.define({
13634
    combine(configs) {
13635
        let config = combineConfig(configs, {
13636
            render: null,
13637
            specialChars: Specials,
13638
            addSpecialChars: null
13639
        });
13640
        if (config.replaceTabs = !supportsTabSize())
13641
            config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport);
13642
        if (config.addSpecialChars)
13643
            config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport);
13644
        return config;
13645
    }
13646
});
13647
/**
13648
Returns an extension that installs highlighting of special
13649
characters.
13650
*/
13651
function highlightSpecialChars(
13652
/**
13653
Configuration options.
13654
*/
13655
config = {}) {
13656
    return [specialCharConfig.of(config), specialCharPlugin()];
13657
}
13658
let _plugin = null;
13659
function specialCharPlugin() {
13660
    return _plugin || (_plugin = ViewPlugin.fromClass(class {
13661
        constructor(view) {
13662
            this.view = view;
13663
            this.decorations = Decoration.none;
13664
            this.decorationCache = Object.create(null);
13665
            this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
13666
            this.decorations = this.decorator.createDeco(view);
13667
        }
13668
        makeDecorator(conf) {
13669
            return new MatchDecorator({
13670
                regexp: conf.specialChars,
13671
                decoration: (m, view, pos) => {
13672
                    let { doc } = view.state;
13673
                    let code = codePointAt(m[0], 0);
13674
                    if (code == 9) {
13675
                        let line = doc.lineAt(pos);
13676
                        let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
13677
                        return Decoration.replace({
13678
                            widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)
13679
                        });
13680
                    }
13681
                    return this.decorationCache[code] ||
13682
                        (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
13683
                },
13684
                boundary: conf.replaceTabs ? undefined : /[^]/
13685
            });
13686
        }
13687
        update(update) {
13688
            let conf = update.state.facet(specialCharConfig);
13689
            if (update.startState.facet(specialCharConfig) != conf) {
13690
                this.decorator = this.makeDecorator(conf);
13691
                this.decorations = this.decorator.createDeco(update.view);
13692
            }
13693
            else {
13694
                this.decorations = this.decorator.updateDeco(update, this.decorations);
13695
            }
13696
        }
13697
    }, {
13698
        decorations: v => v.decorations
13699
    }));
13700
}
13701
const DefaultPlaceholder = "\u2022";
13702
// Assigns placeholder characters from the Control Pictures block to
13703
// ASCII control characters
13704
function placeholder$1(code) {
13705
    if (code >= 32)
13706
        return DefaultPlaceholder;
13707
    if (code == 10)
13708
        return "\u2424";
13709
    return String.fromCharCode(9216 + code);
13710
}
13711
class SpecialCharWidget extends WidgetType {
13712
    constructor(options, code) {
13713
        super();
13714
        this.options = options;
13715
        this.code = code;
13716
    }
13717
    eq(other) { return other.code == this.code; }
13718
    toDOM(view) {
13719
        let ph = placeholder$1(this.code);
13720
        let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
13721
        let custom = this.options.render && this.options.render(this.code, desc, ph);
13722
        if (custom)
13723
            return custom;
13724
        let span = document.createElement("span");
13725
        span.textContent = ph;
13726
        span.title = desc;
13727
        span.setAttribute("aria-label", desc);
13728
        span.className = "cm-specialChar";
13729
        return span;
13730
    }
13731
    ignoreEvent() { return false; }
13732
}
13733
class TabWidget extends WidgetType {
13734
    constructor(width) {
13735
        super();
13736
        this.width = width;
13737
    }
13738
    eq(other) { return other.width == this.width; }
13739
    toDOM() {
13740
        let span = document.createElement("span");
13741
        span.textContent = "\t";
13742
        span.className = "cm-tab";
13743
        span.style.width = this.width + "px";
13744
        return span;
13745
    }
13746
    ignoreEvent() { return false; }
13747
}
13748
 
13749
/**
13750
Mark lines that have a cursor on them with the `"cm-activeLine"`
13751
DOM class.
13752
*/
13753
function highlightActiveLine() {
13754
    return activeLineHighlighter;
13755
}
13756
const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" });
13757
const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
13758
    constructor(view) {
13759
        this.decorations = this.getDeco(view);
13760
    }
13761
    update(update) {
13762
        if (update.docChanged || update.selectionSet)
13763
            this.decorations = this.getDeco(update.view);
13764
    }
13765
    getDeco(view) {
13766
        let lastLineStart = -1, deco = [];
13767
        for (let r of view.state.selection.ranges) {
13768
            let line = view.lineBlockAt(r.head);
13769
            if (line.from > lastLineStart) {
13770
                deco.push(lineDeco.range(line.from));
13771
                lastLineStart = line.from;
13772
            }
13773
        }
13774
        return Decoration.set(deco);
13775
    }
13776
}, {
13777
    decorations: v => v.decorations
13778
});
13779
 
13780
// Don't compute precise column positions for line offsets above this
13781
// (since it could get expensive). Assume offset==column for them.
13782
const MaxOff = 2000;
13783
function rectangleFor(state, a, b) {
13784
    let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
13785
    let ranges = [];
13786
    if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
13787
        let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
13788
        for (let i = startLine; i <= endLine; i++) {
13789
            let line = state.doc.line(i);
13790
            if (line.length <= endOff)
13791
                ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
13792
        }
13793
    }
13794
    else {
13795
        let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
13796
        for (let i = startLine; i <= endLine; i++) {
13797
            let line = state.doc.line(i);
13798
            let start = findColumn(line.text, startCol, state.tabSize, true);
13799
            if (start < 0) {
13800
                ranges.push(EditorSelection.cursor(line.to));
13801
            }
13802
            else {
13803
                let end = findColumn(line.text, endCol, state.tabSize);
13804
                ranges.push(EditorSelection.range(line.from + start, line.from + end));
13805
            }
13806
        }
13807
    }
13808
    return ranges;
13809
}
13810
function absoluteColumn(view, x) {
13811
    let ref = view.coordsAtPos(view.viewport.from);
13812
    return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;
13813
}
13814
function getPos(view, event) {
13815
    let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
13816
    let line = view.state.doc.lineAt(offset), off = offset - line.from;
13817
    let col = off > MaxOff ? -1
13818
        : off == line.length ? absoluteColumn(view, event.clientX)
13819
            : countColumn(line.text, view.state.tabSize, offset - line.from);
13820
    return { line: line.number, col, off };
13821
}
13822
function rectangleSelectionStyle(view, event) {
13823
    let start = getPos(view, event), startSel = view.state.selection;
13824
    if (!start)
13825
        return null;
13826
    return {
13827
        update(update) {
13828
            if (update.docChanged) {
13829
                let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);
13830
                let newLine = update.state.doc.lineAt(newStart);
13831
                start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
13832
                startSel = startSel.map(update.changes);
13833
            }
13834
        },
13835
        get(event, _extend, multiple) {
13836
            let cur = getPos(view, event);
13837
            if (!cur)
13838
                return startSel;
13839
            let ranges = rectangleFor(view.state, start, cur);
13840
            if (!ranges.length)
13841
                return startSel;
13842
            if (multiple)
13843
                return EditorSelection.create(ranges.concat(startSel.ranges));
13844
            else
13845
                return EditorSelection.create(ranges);
13846
        }
13847
    };
13848
}
13849
/**
13850
Create an extension that enables rectangular selections. By
13851
default, it will react to left mouse drag with the Alt key held
13852
down. When such a selection occurs, the text within the rectangle
13853
that was dragged over will be selected, as one selection
13854
[range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.
13855
*/
13856
function rectangularSelection(options) {
1441 ariadna 13857
    let filter = (e => e.altKey && e.button == 0);
1 efrain 13858
    return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);
13859
}
13860
const keys = {
13861
    Alt: [18, e => !!e.altKey],
13862
    Control: [17, e => !!e.ctrlKey],
13863
    Shift: [16, e => !!e.shiftKey],
13864
    Meta: [91, e => !!e.metaKey]
13865
};
13866
const showCrosshair = { style: "cursor: crosshair" };
13867
/**
13868
Returns an extension that turns the pointer cursor into a
13869
crosshair when a given modifier key, defaulting to Alt, is held
13870
down. Can serve as a visual hint that rectangular selection is
13871
going to happen when paired with
13872
[`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).
13873
*/
13874
function crosshairCursor(options = {}) {
13875
    let [code, getter] = keys[options.key || "Alt"];
13876
    let plugin = ViewPlugin.fromClass(class {
13877
        constructor(view) {
13878
            this.view = view;
13879
            this.isDown = false;
13880
        }
13881
        set(isDown) {
13882
            if (this.isDown != isDown) {
13883
                this.isDown = isDown;
13884
                this.view.update([]);
13885
            }
13886
        }
13887
    }, {
13888
        eventObservers: {
13889
            keydown(e) {
13890
                this.set(e.keyCode == code || getter(e));
13891
            },
13892
            keyup(e) {
13893
                if (e.keyCode == code || !getter(e))
13894
                    this.set(false);
13895
            },
13896
            mousemove(e) {
13897
                this.set(getter(e));
13898
            }
13899
        }
13900
    });
13901
    return [
13902
        plugin,
13903
        EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })
13904
    ];
13905
}
13906
 
13907
const Outside = "-10000px";
13908
class TooltipViewManager {
13909
    constructor(view, facet, createTooltipView, removeTooltipView) {
13910
        this.facet = facet;
13911
        this.createTooltipView = createTooltipView;
13912
        this.removeTooltipView = removeTooltipView;
13913
        this.input = view.state.facet(facet);
13914
        this.tooltips = this.input.filter(t => t);
13915
        let prev = null;
13916
        this.tooltipViews = this.tooltips.map(t => prev = createTooltipView(t, prev));
13917
    }
13918
    update(update, above) {
13919
        var _a;
13920
        let input = update.state.facet(this.facet);
13921
        let tooltips = input.filter(x => x);
13922
        if (input === this.input) {
13923
            for (let t of this.tooltipViews)
13924
                if (t.update)
13925
                    t.update(update);
13926
            return false;
13927
        }
13928
        let tooltipViews = [], newAbove = above ? [] : null;
13929
        for (let i = 0; i < tooltips.length; i++) {
13930
            let tip = tooltips[i], known = -1;
13931
            if (!tip)
13932
                continue;
13933
            for (let i = 0; i < this.tooltips.length; i++) {
13934
                let other = this.tooltips[i];
13935
                if (other && other.create == tip.create)
13936
                    known = i;
13937
            }
13938
            if (known < 0) {
13939
                tooltipViews[i] = this.createTooltipView(tip, i ? tooltipViews[i - 1] : null);
13940
                if (newAbove)
13941
                    newAbove[i] = !!tip.above;
13942
            }
13943
            else {
13944
                let tooltipView = tooltipViews[i] = this.tooltipViews[known];
13945
                if (newAbove)
13946
                    newAbove[i] = above[known];
13947
                if (tooltipView.update)
13948
                    tooltipView.update(update);
13949
            }
13950
        }
13951
        for (let t of this.tooltipViews)
13952
            if (tooltipViews.indexOf(t) < 0) {
13953
                this.removeTooltipView(t);
13954
                (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
13955
            }
13956
        if (above) {
13957
            newAbove.forEach((val, i) => above[i] = val);
13958
            above.length = newAbove.length;
13959
        }
13960
        this.input = input;
13961
        this.tooltips = tooltips;
13962
        this.tooltipViews = tooltipViews;
13963
        return true;
13964
    }
13965
}
13966
function windowSpace(view) {
1441 ariadna 13967
    let docElt = view.dom.ownerDocument.documentElement;
13968
    return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth };
1 efrain 13969
}
13970
const tooltipConfig = /*@__PURE__*/Facet.define({
13971
    combine: values => {
13972
        var _a, _b, _c;
13973
        return ({
13974
            position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed",
13975
            parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
13976
            tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,
13977
        });
13978
    }
13979
});
13980
const knownHeight = /*@__PURE__*/new WeakMap();
13981
const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
13982
    constructor(view) {
13983
        this.view = view;
13984
        this.above = [];
13985
        this.inView = true;
13986
        this.madeAbsolute = false;
13987
        this.lastTransaction = 0;
13988
        this.measureTimeout = -1;
13989
        let config = view.state.facet(tooltipConfig);
13990
        this.position = config.position;
13991
        this.parent = config.parent;
13992
        this.classes = view.themeClasses;
13993
        this.createContainer();
13994
        this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
13995
        this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
13996
        this.manager = new TooltipViewManager(view, showTooltip, (t, p) => this.createTooltip(t, p), t => {
13997
            if (this.resizeObserver)
13998
                this.resizeObserver.unobserve(t.dom);
13999
            t.dom.remove();
14000
        });
14001
        this.above = this.manager.tooltips.map(t => !!t.above);
14002
        this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => {
14003
            if (Date.now() > this.lastTransaction - 50 &&
14004
                entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
14005
                this.measureSoon();
14006
        }, { threshold: [1] }) : null;
14007
        this.observeIntersection();
14008
        view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
14009
        this.maybeMeasure();
14010
    }
14011
    createContainer() {
14012
        if (this.parent) {
14013
            this.container = document.createElement("div");
14014
            this.container.style.position = "relative";
14015
            this.container.className = this.view.themeClasses;
14016
            this.parent.appendChild(this.container);
14017
        }
14018
        else {
14019
            this.container = this.view.dom;
14020
        }
14021
    }
14022
    observeIntersection() {
14023
        if (this.intersectionObserver) {
14024
            this.intersectionObserver.disconnect();
14025
            for (let tooltip of this.manager.tooltipViews)
14026
                this.intersectionObserver.observe(tooltip.dom);
14027
        }
14028
    }
14029
    measureSoon() {
14030
        if (this.measureTimeout < 0)
14031
            this.measureTimeout = setTimeout(() => {
14032
                this.measureTimeout = -1;
14033
                this.maybeMeasure();
14034
            }, 50);
14035
    }
14036
    update(update) {
14037
        if (update.transactions.length)
14038
            this.lastTransaction = Date.now();
14039
        let updated = this.manager.update(update, this.above);
14040
        if (updated)
14041
            this.observeIntersection();
14042
        let shouldMeasure = updated || update.geometryChanged;
14043
        let newConfig = update.state.facet(tooltipConfig);
14044
        if (newConfig.position != this.position && !this.madeAbsolute) {
14045
            this.position = newConfig.position;
14046
            for (let t of this.manager.tooltipViews)
14047
                t.dom.style.position = this.position;
14048
            shouldMeasure = true;
14049
        }
14050
        if (newConfig.parent != this.parent) {
14051
            if (this.parent)
14052
                this.container.remove();
14053
            this.parent = newConfig.parent;
14054
            this.createContainer();
14055
            for (let t of this.manager.tooltipViews)
14056
                this.container.appendChild(t.dom);
14057
            shouldMeasure = true;
14058
        }
14059
        else if (this.parent && this.view.themeClasses != this.classes) {
14060
            this.classes = this.container.className = this.view.themeClasses;
14061
        }
14062
        if (shouldMeasure)
14063
            this.maybeMeasure();
14064
    }
14065
    createTooltip(tooltip, prev) {
14066
        let tooltipView = tooltip.create(this.view);
14067
        let before = prev ? prev.dom : null;
14068
        tooltipView.dom.classList.add("cm-tooltip");
14069
        if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
14070
            let arrow = document.createElement("div");
14071
            arrow.className = "cm-tooltip-arrow";
1441 ariadna 14072
            tooltipView.dom.appendChild(arrow);
1 efrain 14073
        }
14074
        tooltipView.dom.style.position = this.position;
14075
        tooltipView.dom.style.top = Outside;
14076
        tooltipView.dom.style.left = "0px";
14077
        this.container.insertBefore(tooltipView.dom, before);
14078
        if (tooltipView.mount)
14079
            tooltipView.mount(this.view);
14080
        if (this.resizeObserver)
14081
            this.resizeObserver.observe(tooltipView.dom);
14082
        return tooltipView;
14083
    }
14084
    destroy() {
14085
        var _a, _b, _c;
14086
        this.view.win.removeEventListener("resize", this.measureSoon);
14087
        for (let tooltipView of this.manager.tooltipViews) {
14088
            tooltipView.dom.remove();
14089
            (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);
14090
        }
14091
        if (this.parent)
14092
            this.container.remove();
14093
        (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
14094
        (_c = this.intersectionObserver) === null || _c === void 0 ? void 0 : _c.disconnect();
14095
        clearTimeout(this.measureTimeout);
14096
    }
14097
    readMeasure() {
14098
        let scaleX = 1, scaleY = 1, makeAbsolute = false;
14099
        if (this.position == "fixed" && this.manager.tooltipViews.length) {
14100
            let { dom } = this.manager.tooltipViews[0];
14101
            if (browser.gecko) {
14102
                // Firefox sets the element's `offsetParent` to the
14103
                // transformed element when a transform interferes with fixed
14104
                // positioning.
14105
                makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;
14106
            }
14107
            else if (dom.style.top == Outside && dom.style.left == "0px") {
14108
                // On other browsers, we have to awkwardly try and use other
14109
                // information to detect a transform.
14110
                let rect = dom.getBoundingClientRect();
14111
                makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;
14112
            }
14113
        }
14114
        if (makeAbsolute || this.position == "absolute") {
14115
            if (this.parent) {
14116
                let rect = this.parent.getBoundingClientRect();
14117
                if (rect.width && rect.height) {
14118
                    scaleX = rect.width / this.parent.offsetWidth;
14119
                    scaleY = rect.height / this.parent.offsetHeight;
14120
                }
14121
            }
14122
            else {
14123
                ({ scaleX, scaleY } = this.view.viewState);
14124
            }
14125
        }
1441 ariadna 14126
        let visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view);
1 efrain 14127
        return {
1441 ariadna 14128
            visible: {
14129
                left: visible.left + margins.left, top: visible.top + margins.top,
14130
                right: visible.right - margins.right, bottom: visible.bottom - margins.bottom
14131
            },
14132
            parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(),
1 efrain 14133
            pos: this.manager.tooltips.map((t, i) => {
14134
                let tv = this.manager.tooltipViews[i];
14135
                return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);
14136
            }),
14137
            size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
14138
            space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
14139
            scaleX, scaleY, makeAbsolute
14140
        };
14141
    }
14142
    writeMeasure(measured) {
14143
        var _a;
14144
        if (measured.makeAbsolute) {
14145
            this.madeAbsolute = true;
14146
            this.position = "absolute";
14147
            for (let t of this.manager.tooltipViews)
14148
                t.dom.style.position = "absolute";
14149
        }
1441 ariadna 14150
        let { visible, space, scaleX, scaleY } = measured;
1 efrain 14151
        let others = [];
14152
        for (let i = 0; i < this.manager.tooltips.length; i++) {
14153
            let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
14154
            let pos = measured.pos[i], size = measured.size[i];
14155
            // Hide tooltips that are outside of the editor.
1441 ariadna 14156
            if (!pos || tooltip.clip !== false && (pos.bottom <= Math.max(visible.top, space.top) ||
14157
                pos.top >= Math.min(visible.bottom, space.bottom) ||
14158
                pos.right < Math.max(visible.left, space.left) - .1 ||
14159
                pos.left > Math.min(visible.right, space.right) + .1)) {
1 efrain 14160
                dom.style.top = Outside;
14161
                continue;
14162
            }
14163
            let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
14164
            let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;
14165
            let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;
14166
            let offset = tView.offset || noOffset, ltr = this.view.textDirection == Direction.LTR;
1441 ariadna 14167
            let left = size.width > space.right - space.left
14168
                ? (ltr ? space.left : space.right - size.width)
14169
                : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width))
14170
                    : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x), space.right - width);
1 efrain 14171
            let above = this.above[i];
14172
            if (!tooltip.strictSide && (above
1441 ariadna 14173
                ? pos.top - height - arrowHeight - offset.y < space.top
14174
                : pos.bottom + height + arrowHeight + offset.y > space.bottom) &&
1 efrain 14175
                above == (space.bottom - pos.bottom > pos.top - space.top))
14176
                above = this.above[i] = !above;
14177
            let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;
14178
            if (spaceVert < height && tView.resize !== false) {
14179
                if (spaceVert < this.view.defaultLineHeight) {
14180
                    dom.style.top = Outside;
14181
                    continue;
14182
                }
14183
                knownHeight.set(tView, height);
14184
                dom.style.height = (height = spaceVert) / scaleY + "px";
14185
            }
14186
            else if (dom.style.height) {
14187
                dom.style.height = "";
14188
            }
14189
            let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
14190
            let right = left + width;
14191
            if (tView.overlap !== true)
14192
                for (let r of others)
14193
                    if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)
14194
                        top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;
14195
            if (this.position == "absolute") {
14196
                dom.style.top = (top - measured.parent.top) / scaleY + "px";
1441 ariadna 14197
                setLeftStyle(dom, (left - measured.parent.left) / scaleX);
1 efrain 14198
            }
14199
            else {
14200
                dom.style.top = top / scaleY + "px";
1441 ariadna 14201
                setLeftStyle(dom, left / scaleX);
1 efrain 14202
            }
14203
            if (arrow) {
14204
                let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);
14205
                arrow.style.left = arrowLeft / scaleX + "px";
14206
            }
14207
            if (tView.overlap !== true)
14208
                others.push({ left, top, right, bottom: top + height });
14209
            dom.classList.toggle("cm-tooltip-above", above);
14210
            dom.classList.toggle("cm-tooltip-below", !above);
14211
            if (tView.positioned)
14212
                tView.positioned(measured.space);
14213
        }
14214
    }
14215
    maybeMeasure() {
14216
        if (this.manager.tooltips.length) {
14217
            if (this.view.inView)
14218
                this.view.requestMeasure(this.measureReq);
14219
            if (this.inView != this.view.inView) {
14220
                this.inView = this.view.inView;
14221
                if (!this.inView)
14222
                    for (let tv of this.manager.tooltipViews)
14223
                        tv.dom.style.top = Outside;
14224
            }
14225
        }
14226
    }
14227
}, {
14228
    eventObservers: {
14229
        scroll() { this.maybeMeasure(); }
14230
    }
14231
});
1441 ariadna 14232
function setLeftStyle(elt, value) {
14233
    let current = parseInt(elt.style.left, 10);
14234
    if (isNaN(current) || Math.abs(value - current) > 1)
14235
        elt.style.left = value + "px";
14236
}
1 efrain 14237
const baseTheme$4 = /*@__PURE__*/EditorView.baseTheme({
14238
    ".cm-tooltip": {
1441 ariadna 14239
        zIndex: 500,
1 efrain 14240
        boxSizing: "border-box"
14241
    },
14242
    "&light .cm-tooltip": {
14243
        border: "1px solid #bbb",
14244
        backgroundColor: "#f5f5f5"
14245
    },
14246
    "&light .cm-tooltip-section:not(:first-child)": {
14247
        borderTop: "1px solid #bbb",
14248
    },
14249
    "&dark .cm-tooltip": {
14250
        backgroundColor: "#333338",
14251
        color: "white"
14252
    },
14253
    ".cm-tooltip-arrow": {
14254
        height: `${7 /* Arrow.Size */}px`,
14255
        width: `${7 /* Arrow.Size */ * 2}px`,
14256
        position: "absolute",
14257
        zIndex: -1,
14258
        overflow: "hidden",
14259
        "&:before, &:after": {
14260
            content: "''",
14261
            position: "absolute",
14262
            width: 0,
14263
            height: 0,
14264
            borderLeft: `${7 /* Arrow.Size */}px solid transparent`,
14265
            borderRight: `${7 /* Arrow.Size */}px solid transparent`,
14266
        },
14267
        ".cm-tooltip-above &": {
14268
            bottom: `-${7 /* Arrow.Size */}px`,
14269
            "&:before": {
14270
                borderTop: `${7 /* Arrow.Size */}px solid #bbb`,
14271
            },
14272
            "&:after": {
14273
                borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,
14274
                bottom: "1px"
14275
            }
14276
        },
14277
        ".cm-tooltip-below &": {
14278
            top: `-${7 /* Arrow.Size */}px`,
14279
            "&:before": {
14280
                borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,
14281
            },
14282
            "&:after": {
14283
                borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,
14284
                top: "1px"
14285
            }
14286
        },
14287
    },
14288
    "&dark .cm-tooltip .cm-tooltip-arrow": {
14289
        "&:before": {
14290
            borderTopColor: "#333338",
14291
            borderBottomColor: "#333338"
14292
        },
14293
        "&:after": {
14294
            borderTopColor: "transparent",
14295
            borderBottomColor: "transparent"
14296
        }
14297
    }
14298
});
14299
const noOffset = { x: 0, y: 0 };
14300
/**
14301
Facet to which an extension can add a value to show a tooltip.
14302
*/
14303
const showTooltip = /*@__PURE__*/Facet.define({
14304
    enables: [tooltipPlugin, baseTheme$4]
14305
});
14306
const showHoverTooltip = /*@__PURE__*/Facet.define({
14307
    combine: inputs => inputs.reduce((a, i) => a.concat(i), [])
14308
});
14309
class HoverTooltipHost {
14310
    // Needs to be static so that host tooltip instances always match
14311
    static create(view) {
14312
        return new HoverTooltipHost(view);
14313
    }
14314
    constructor(view) {
14315
        this.view = view;
14316
        this.mounted = false;
14317
        this.dom = document.createElement("div");
14318
        this.dom.classList.add("cm-tooltip-hover");
14319
        this.manager = new TooltipViewManager(view, showHoverTooltip, (t, p) => this.createHostedView(t, p), t => t.dom.remove());
14320
    }
14321
    createHostedView(tooltip, prev) {
14322
        let hostedView = tooltip.create(this.view);
14323
        hostedView.dom.classList.add("cm-tooltip-section");
14324
        this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
14325
        if (this.mounted && hostedView.mount)
14326
            hostedView.mount(this.view);
14327
        return hostedView;
14328
    }
14329
    mount(view) {
14330
        for (let hostedView of this.manager.tooltipViews) {
14331
            if (hostedView.mount)
14332
                hostedView.mount(view);
14333
        }
14334
        this.mounted = true;
14335
    }
14336
    positioned(space) {
14337
        for (let hostedView of this.manager.tooltipViews) {
14338
            if (hostedView.positioned)
14339
                hostedView.positioned(space);
14340
        }
14341
    }
14342
    update(update) {
14343
        this.manager.update(update);
14344
    }
14345
    destroy() {
14346
        var _a;
14347
        for (let t of this.manager.tooltipViews)
14348
            (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
14349
    }
14350
    passProp(name) {
14351
        let value = undefined;
14352
        for (let view of this.manager.tooltipViews) {
14353
            let given = view[name];
14354
            if (given !== undefined) {
14355
                if (value === undefined)
14356
                    value = given;
14357
                else if (value !== given)
14358
                    return undefined;
14359
            }
14360
        }
14361
        return value;
14362
    }
14363
    get offset() { return this.passProp("offset"); }
14364
    get getCoords() { return this.passProp("getCoords"); }
14365
    get overlap() { return this.passProp("overlap"); }
14366
    get resize() { return this.passProp("resize"); }
14367
}
14368
const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {
14369
    let tooltips = state.facet(showHoverTooltip);
14370
    if (tooltips.length === 0)
14371
        return null;
14372
    return {
14373
        pos: Math.min(...tooltips.map(t => t.pos)),
14374
        end: Math.max(...tooltips.map(t => { var _a; return (_a = t.end) !== null && _a !== void 0 ? _a : t.pos; })),
14375
        create: HoverTooltipHost.create,
14376
        above: tooltips[0].above,
14377
        arrow: tooltips.some(t => t.arrow),
14378
    };
14379
});
14380
class HoverPlugin {
14381
    constructor(view, source, field, setHover, hoverTime) {
14382
        this.view = view;
14383
        this.source = source;
14384
        this.field = field;
14385
        this.setHover = setHover;
14386
        this.hoverTime = hoverTime;
14387
        this.hoverTimeout = -1;
14388
        this.restartTimeout = -1;
14389
        this.pending = null;
14390
        this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
14391
        this.checkHover = this.checkHover.bind(this);
14392
        view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
14393
        view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
14394
    }
14395
    update() {
14396
        if (this.pending) {
14397
            this.pending = null;
14398
            clearTimeout(this.restartTimeout);
14399
            this.restartTimeout = setTimeout(() => this.startHover(), 20);
14400
        }
14401
    }
14402
    get active() {
14403
        return this.view.state.field(this.field);
14404
    }
14405
    checkHover() {
14406
        this.hoverTimeout = -1;
14407
        if (this.active.length)
14408
            return;
14409
        let hovered = Date.now() - this.lastMove.time;
14410
        if (hovered < this.hoverTime)
14411
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
14412
        else
14413
            this.startHover();
14414
    }
14415
    startHover() {
14416
        clearTimeout(this.restartTimeout);
14417
        let { view, lastMove } = this;
14418
        let desc = view.docView.nearest(lastMove.target);
14419
        if (!desc)
14420
            return;
14421
        let pos, side = 1;
14422
        if (desc instanceof WidgetView) {
14423
            pos = desc.posAtStart;
14424
        }
14425
        else {
14426
            pos = view.posAtCoords(lastMove);
14427
            if (pos == null)
14428
                return;
14429
            let posCoords = view.coordsAtPos(pos);
14430
            if (!posCoords ||
14431
                lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||
14432
                lastMove.x < posCoords.left - view.defaultCharacterWidth ||
14433
                lastMove.x > posCoords.right + view.defaultCharacterWidth)
14434
                return;
14435
            let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
14436
            let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
14437
            side = (lastMove.x < posCoords.left ? -rtl : rtl);
14438
        }
14439
        let open = this.source(view, pos, side);
14440
        if (open === null || open === void 0 ? void 0 : open.then) {
14441
            let pending = this.pending = { pos };
14442
            open.then(result => {
14443
                if (this.pending == pending) {
14444
                    this.pending = null;
14445
                    if (result && !(Array.isArray(result) && !result.length))
14446
                        view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) });
14447
                }
14448
            }, e => logException(view.state, e, "hover tooltip"));
14449
        }
14450
        else if (open && !(Array.isArray(open) && !open.length)) {
14451
            view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) });
14452
        }
14453
    }
14454
    get tooltip() {
14455
        let plugin = this.view.plugin(tooltipPlugin);
14456
        let index = plugin ? plugin.manager.tooltips.findIndex(t => t.create == HoverTooltipHost.create) : -1;
14457
        return index > -1 ? plugin.manager.tooltipViews[index] : null;
14458
    }
14459
    mousemove(event) {
14460
        var _a, _b;
14461
        this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
14462
        if (this.hoverTimeout < 0)
14463
            this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
14464
        let { active, tooltip } = this;
14465
        if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
14466
            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;
14467
            if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos
14468
                : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {
14469
                this.view.dispatch({ effects: this.setHover.of([]) });
14470
                this.pending = null;
14471
            }
14472
        }
14473
    }
14474
    mouseleave(event) {
14475
        clearTimeout(this.hoverTimeout);
14476
        this.hoverTimeout = -1;
14477
        let { active } = this;
14478
        if (active.length) {
14479
            let { tooltip } = this;
14480
            let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);
14481
            if (!inTooltip)
14482
                this.view.dispatch({ effects: this.setHover.of([]) });
14483
            else
14484
                this.watchTooltipLeave(tooltip.dom);
14485
        }
14486
    }
14487
    watchTooltipLeave(tooltip) {
14488
        let watch = (event) => {
14489
            tooltip.removeEventListener("mouseleave", watch);
14490
            if (this.active.length && !this.view.dom.contains(event.relatedTarget))
14491
                this.view.dispatch({ effects: this.setHover.of([]) });
14492
        };
14493
        tooltip.addEventListener("mouseleave", watch);
14494
    }
14495
    destroy() {
14496
        clearTimeout(this.hoverTimeout);
14497
        this.view.dom.removeEventListener("mouseleave", this.mouseleave);
14498
        this.view.dom.removeEventListener("mousemove", this.mousemove);
14499
    }
14500
}
14501
const tooltipMargin = 4;
14502
function isInTooltip(tooltip, event) {
1441 ariadna 14503
    let { left, right, top, bottom } = tooltip.getBoundingClientRect(), arrow;
14504
    if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) {
14505
        let arrowRect = arrow.getBoundingClientRect();
14506
        top = Math.min(arrowRect.top, top);
14507
        bottom = Math.max(arrowRect.bottom, bottom);
14508
    }
14509
    return event.clientX >= left - tooltipMargin && event.clientX <= right + tooltipMargin &&
14510
        event.clientY >= top - tooltipMargin && event.clientY <= bottom + tooltipMargin;
1 efrain 14511
}
14512
function isOverRange(view, from, to, x, y, margin) {
14513
    let rect = view.scrollDOM.getBoundingClientRect();
14514
    let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
14515
    if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)
14516
        return false;
14517
    let pos = view.posAtCoords({ x, y }, false);
14518
    return pos >= from && pos <= to;
14519
}
14520
/**
14521
Set up a hover tooltip, which shows up when the pointer hovers
14522
over ranges of text. The callback is called when the mouse hovers
14523
over the document text. It should, if there is a tooltip
14524
associated with position `pos`, return the tooltip description
14525
(either directly or in a promise). The `side` argument indicates
14526
on which side of the position the pointer is—it will be -1 if the
14527
pointer is before the position, 1 if after the position.
14528
 
14529
Note that all hover tooltips are hosted within a single tooltip
14530
container element. This allows multiple tooltips over the same
14531
range to be "merged" together without overlapping.
1441 ariadna 14532
 
14533
The return value is a valid [editor extension](https://codemirror.net/6/docs/ref/#state.Extension)
14534
but also provides an `active` property holding a state field that
14535
can be used to read the currently active tooltips produced by this
14536
extension.
1 efrain 14537
*/
14538
function hoverTooltip(source, options = {}) {
14539
    let setHover = StateEffect.define();
14540
    let hoverState = StateField.define({
14541
        create() { return []; },
14542
        update(value, tr) {
14543
            if (value.length) {
14544
                if (options.hideOnChange && (tr.docChanged || tr.selection))
14545
                    value = [];
14546
                else if (options.hideOn)
14547
                    value = value.filter(v => !options.hideOn(tr, v));
14548
                if (tr.docChanged) {
14549
                    let mapped = [];
14550
                    for (let tooltip of value) {
14551
                        let newPos = tr.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
14552
                        if (newPos != null) {
14553
                            let copy = Object.assign(Object.create(null), tooltip);
14554
                            copy.pos = newPos;
14555
                            if (copy.end != null)
14556
                                copy.end = tr.changes.mapPos(copy.end);
14557
                            mapped.push(copy);
14558
                        }
14559
                    }
14560
                    value = mapped;
14561
                }
14562
            }
14563
            for (let effect of tr.effects) {
14564
                if (effect.is(setHover))
14565
                    value = effect.value;
14566
                if (effect.is(closeHoverTooltipEffect))
14567
                    value = [];
14568
            }
14569
            return value;
14570
        },
14571
        provide: f => showHoverTooltip.from(f)
14572
    });
1441 ariadna 14573
    return {
14574
        active: hoverState,
14575
        extension: [
14576
            hoverState,
14577
            ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),
14578
            showHoverTooltipHost
14579
        ]
14580
    };
1 efrain 14581
}
14582
/**
14583
Get the active tooltip view for a given tooltip, if available.
14584
*/
14585
function getTooltip(view, tooltip) {
14586
    let plugin = view.plugin(tooltipPlugin);
14587
    if (!plugin)
14588
        return null;
14589
    let found = plugin.manager.tooltips.indexOf(tooltip);
14590
    return found < 0 ? null : plugin.manager.tooltipViews[found];
14591
}
14592
const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define();
14593
 
14594
const panelConfig = /*@__PURE__*/Facet.define({
14595
    combine(configs) {
14596
        let topContainer, bottomContainer;
14597
        for (let c of configs) {
14598
            topContainer = topContainer || c.topContainer;
14599
            bottomContainer = bottomContainer || c.bottomContainer;
14600
        }
14601
        return { topContainer, bottomContainer };
14602
    }
14603
});
14604
/**
14605
Get the active panel created by the given constructor, if any.
14606
This can be useful when you need access to your panels' DOM
14607
structure.
14608
*/
14609
function getPanel(view, panel) {
14610
    let plugin = view.plugin(panelPlugin);
14611
    let index = plugin ? plugin.specs.indexOf(panel) : -1;
14612
    return index > -1 ? plugin.panels[index] : null;
14613
}
14614
const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
14615
    constructor(view) {
14616
        this.input = view.state.facet(showPanel);
14617
        this.specs = this.input.filter(s => s);
14618
        this.panels = this.specs.map(spec => spec(view));
14619
        let conf = view.state.facet(panelConfig);
14620
        this.top = new PanelGroup(view, true, conf.topContainer);
14621
        this.bottom = new PanelGroup(view, false, conf.bottomContainer);
14622
        this.top.sync(this.panels.filter(p => p.top));
14623
        this.bottom.sync(this.panels.filter(p => !p.top));
14624
        for (let p of this.panels) {
14625
            p.dom.classList.add("cm-panel");
14626
            if (p.mount)
14627
                p.mount();
14628
        }
14629
    }
14630
    update(update) {
14631
        let conf = update.state.facet(panelConfig);
14632
        if (this.top.container != conf.topContainer) {
14633
            this.top.sync([]);
14634
            this.top = new PanelGroup(update.view, true, conf.topContainer);
14635
        }
14636
        if (this.bottom.container != conf.bottomContainer) {
14637
            this.bottom.sync([]);
14638
            this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
14639
        }
14640
        this.top.syncClasses();
14641
        this.bottom.syncClasses();
14642
        let input = update.state.facet(showPanel);
14643
        if (input != this.input) {
14644
            let specs = input.filter(x => x);
14645
            let panels = [], top = [], bottom = [], mount = [];
14646
            for (let spec of specs) {
14647
                let known = this.specs.indexOf(spec), panel;
14648
                if (known < 0) {
14649
                    panel = spec(update.view);
14650
                    mount.push(panel);
14651
                }
14652
                else {
14653
                    panel = this.panels[known];
14654
                    if (panel.update)
14655
                        panel.update(update);
14656
                }
14657
                panels.push(panel);
14658
                (panel.top ? top : bottom).push(panel);
14659
            }
14660
            this.specs = specs;
14661
            this.panels = panels;
14662
            this.top.sync(top);
14663
            this.bottom.sync(bottom);
14664
            for (let p of mount) {
14665
                p.dom.classList.add("cm-panel");
14666
                if (p.mount)
14667
                    p.mount();
14668
            }
14669
        }
14670
        else {
14671
            for (let p of this.panels)
14672
                if (p.update)
14673
                    p.update(update);
14674
        }
14675
    }
14676
    destroy() {
14677
        this.top.sync([]);
14678
        this.bottom.sync([]);
14679
    }
14680
}, {
14681
    provide: plugin => EditorView.scrollMargins.of(view => {
14682
        let value = view.plugin(plugin);
14683
        return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
14684
    })
14685
});
14686
class PanelGroup {
14687
    constructor(view, top, container) {
14688
        this.view = view;
14689
        this.top = top;
14690
        this.container = container;
14691
        this.dom = undefined;
14692
        this.classes = "";
14693
        this.panels = [];
14694
        this.syncClasses();
14695
    }
14696
    sync(panels) {
14697
        for (let p of this.panels)
14698
            if (p.destroy && panels.indexOf(p) < 0)
14699
                p.destroy();
14700
        this.panels = panels;
14701
        this.syncDOM();
14702
    }
14703
    syncDOM() {
14704
        if (this.panels.length == 0) {
14705
            if (this.dom) {
14706
                this.dom.remove();
14707
                this.dom = undefined;
14708
            }
14709
            return;
14710
        }
14711
        if (!this.dom) {
14712
            this.dom = document.createElement("div");
14713
            this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
14714
            this.dom.style[this.top ? "top" : "bottom"] = "0";
14715
            let parent = this.container || this.view.dom;
14716
            parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
14717
        }
14718
        let curDOM = this.dom.firstChild;
14719
        for (let panel of this.panels) {
14720
            if (panel.dom.parentNode == this.dom) {
14721
                while (curDOM != panel.dom)
14722
                    curDOM = rm(curDOM);
14723
                curDOM = curDOM.nextSibling;
14724
            }
14725
            else {
14726
                this.dom.insertBefore(panel.dom, curDOM);
14727
            }
14728
        }
14729
        while (curDOM)
14730
            curDOM = rm(curDOM);
14731
    }
14732
    scrollMargin() {
14733
        return !this.dom || this.container ? 0
14734
            : Math.max(0, this.top ?
14735
                this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :
14736
                Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
14737
    }
14738
    syncClasses() {
14739
        if (!this.container || this.classes == this.view.themeClasses)
14740
            return;
14741
        for (let cls of this.classes.split(" "))
14742
            if (cls)
14743
                this.container.classList.remove(cls);
14744
        for (let cls of (this.classes = this.view.themeClasses).split(" "))
14745
            if (cls)
14746
                this.container.classList.add(cls);
14747
    }
14748
}
14749
function rm(node) {
14750
    let next = node.nextSibling;
14751
    node.remove();
14752
    return next;
14753
}
14754
/**
14755
Opening a panel is done by providing a constructor function for
14756
the panel through this facet. (The panel is closed again when its
14757
constructor is no longer provided.) Values of `null` are ignored.
14758
*/
14759
const showPanel = /*@__PURE__*/Facet.define({
14760
    enables: panelPlugin
14761
});
14762
 
14763
/**
14764
A gutter marker represents a bit of information attached to a line
14765
in a specific gutter. Your own custom markers have to extend this
14766
class.
14767
*/
14768
class GutterMarker extends RangeValue {
14769
    /**
14770
    @internal
14771
    */
14772
    compare(other) {
14773
        return this == other || this.constructor == other.constructor && this.eq(other);
14774
    }
14775
    /**
14776
    Compare this marker to another marker of the same type.
14777
    */
14778
    eq(other) { return false; }
14779
    /**
14780
    Called if the marker has a `toDOM` method and its representation
14781
    was removed from a gutter.
14782
    */
14783
    destroy(dom) { }
14784
}
14785
GutterMarker.prototype.elementClass = "";
14786
GutterMarker.prototype.toDOM = undefined;
14787
GutterMarker.prototype.mapMode = MapMode.TrackBefore;
14788
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
14789
GutterMarker.prototype.point = true;
14790
/**
14791
Facet used to add a class to all gutter elements for a given line.
14792
Markers given to this facet should _only_ define an
14793
[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a
14794
[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear
14795
in all gutters for the line).
14796
*/
14797
const gutterLineClass = /*@__PURE__*/Facet.define();
1441 ariadna 14798
/**
14799
Facet used to add a class to all gutter elements next to a widget.
14800
Should not provide widgets with a `toDOM` method.
14801
*/
14802
const gutterWidgetClass = /*@__PURE__*/Facet.define();
1 efrain 14803
const defaults$1 = {
14804
    class: "",
14805
    renderEmptyElements: false,
14806
    elementStyle: "",
14807
    markers: () => RangeSet.empty,
14808
    lineMarker: () => null,
14809
    widgetMarker: () => null,
14810
    lineMarkerChange: null,
14811
    initialSpacer: null,
14812
    updateSpacer: null,
14813
    domEventHandlers: {}
14814
};
14815
const activeGutters = /*@__PURE__*/Facet.define();
14816
/**
14817
Define an editor gutter. The order in which the gutters appear is
14818
determined by their extension priority.
14819
*/
14820
function gutter(config) {
14821
    return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config))];
14822
}
14823
const unfixGutters = /*@__PURE__*/Facet.define({
14824
    combine: values => values.some(x => x)
14825
});
14826
/**
14827
The gutter-drawing plugin is automatically enabled when you add a
14828
gutter, but you can use this function to explicitly configure it.
14829
 
14830
Unless `fixed` is explicitly set to `false`, the gutters are
14831
fixed, meaning they don't scroll along with the content
14832
horizontally (except on Internet Explorer, which doesn't support
14833
CSS [`position:
14834
sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
14835
*/
14836
function gutters(config) {
14837
    let result = [
14838
        gutterView,
14839
    ];
14840
    return result;
14841
}
14842
const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class {
14843
    constructor(view) {
14844
        this.view = view;
14845
        this.prevViewport = view.viewport;
14846
        this.dom = document.createElement("div");
14847
        this.dom.className = "cm-gutters";
14848
        this.dom.setAttribute("aria-hidden", "true");
14849
        this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
14850
        this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
14851
        for (let gutter of this.gutters)
14852
            this.dom.appendChild(gutter.dom);
14853
        this.fixed = !view.state.facet(unfixGutters);
14854
        if (this.fixed) {
14855
            // FIXME IE11 fallback, which doesn't support position: sticky,
14856
            // by using position: relative + event handlers that realign the
14857
            // gutter (or just force fixed=false on IE11?)
14858
            this.dom.style.position = "sticky";
14859
        }
14860
        this.syncGutters(false);
14861
        view.scrollDOM.insertBefore(this.dom, view.contentDOM);
14862
    }
14863
    update(update) {
14864
        if (this.updateGutters(update)) {
14865
            // Detach during sync when the viewport changed significantly
14866
            // (such as during scrolling), since for large updates that is
14867
            // faster.
14868
            let vpA = this.prevViewport, vpB = update.view.viewport;
14869
            let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
14870
            this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
14871
        }
14872
        if (update.geometryChanged) {
14873
            this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
14874
        }
14875
        if (this.view.state.facet(unfixGutters) != !this.fixed) {
14876
            this.fixed = !this.fixed;
14877
            this.dom.style.position = this.fixed ? "sticky" : "";
14878
        }
14879
        this.prevViewport = update.view.viewport;
14880
    }
14881
    syncGutters(detach) {
14882
        let after = this.dom.nextSibling;
14883
        if (detach)
14884
            this.dom.remove();
14885
        let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
14886
        let classSet = [];
14887
        let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));
14888
        for (let line of this.view.viewportLineBlocks) {
14889
            if (classSet.length)
14890
                classSet = [];
14891
            if (Array.isArray(line.type)) {
14892
                let first = true;
14893
                for (let b of line.type) {
14894
                    if (b.type == BlockType.Text && first) {
14895
                        advanceCursor(lineClasses, classSet, b.from);
14896
                        for (let cx of contexts)
14897
                            cx.line(this.view, b, classSet);
14898
                        first = false;
14899
                    }
14900
                    else if (b.widget) {
14901
                        for (let cx of contexts)
14902
                            cx.widget(this.view, b);
14903
                    }
14904
                }
14905
            }
14906
            else if (line.type == BlockType.Text) {
14907
                advanceCursor(lineClasses, classSet, line.from);
14908
                for (let cx of contexts)
14909
                    cx.line(this.view, line, classSet);
14910
            }
14911
            else if (line.widget) {
14912
                for (let cx of contexts)
14913
                    cx.widget(this.view, line);
14914
            }
14915
        }
14916
        for (let cx of contexts)
14917
            cx.finish();
14918
        if (detach)
14919
            this.view.scrollDOM.insertBefore(this.dom, after);
14920
    }
14921
    updateGutters(update) {
14922
        let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);
14923
        let change = update.docChanged || update.heightChanged || update.viewportChanged ||
14924
            !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);
14925
        if (prev == cur) {
14926
            for (let gutter of this.gutters)
14927
                if (gutter.update(update))
14928
                    change = true;
14929
        }
14930
        else {
14931
            change = true;
14932
            let gutters = [];
14933
            for (let conf of cur) {
14934
                let known = prev.indexOf(conf);
14935
                if (known < 0) {
14936
                    gutters.push(new SingleGutterView(this.view, conf));
14937
                }
14938
                else {
14939
                    this.gutters[known].update(update);
14940
                    gutters.push(this.gutters[known]);
14941
                }
14942
            }
14943
            for (let g of this.gutters) {
14944
                g.dom.remove();
14945
                if (gutters.indexOf(g) < 0)
14946
                    g.destroy();
14947
            }
14948
            for (let g of gutters)
14949
                this.dom.appendChild(g.dom);
14950
            this.gutters = gutters;
14951
        }
14952
        return change;
14953
    }
14954
    destroy() {
14955
        for (let view of this.gutters)
14956
            view.destroy();
14957
        this.dom.remove();
14958
    }
14959
}, {
14960
    provide: plugin => EditorView.scrollMargins.of(view => {
14961
        let value = view.plugin(plugin);
14962
        if (!value || value.gutters.length == 0 || !value.fixed)
14963
            return null;
14964
        return view.textDirection == Direction.LTR
14965
            ? { left: value.dom.offsetWidth * view.scaleX }
14966
            : { right: value.dom.offsetWidth * view.scaleX };
14967
    })
14968
});
14969
function asArray(val) { return (Array.isArray(val) ? val : [val]); }
14970
function advanceCursor(cursor, collect, pos) {
14971
    while (cursor.value && cursor.from <= pos) {
14972
        if (cursor.from == pos)
14973
            collect.push(cursor.value);
14974
        cursor.next();
14975
    }
14976
}
14977
class UpdateContext {
14978
    constructor(gutter, viewport, height) {
14979
        this.gutter = gutter;
14980
        this.height = height;
14981
        this.i = 0;
14982
        this.cursor = RangeSet.iter(gutter.markers, viewport.from);
14983
    }
14984
    addElement(view, block, markers) {
14985
        let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;
14986
        if (this.i == gutter.elements.length) {
14987
            let newElt = new GutterElement(view, height, above, markers);
14988
            gutter.elements.push(newElt);
14989
            gutter.dom.appendChild(newElt.dom);
14990
        }
14991
        else {
14992
            gutter.elements[this.i].update(view, height, above, markers);
14993
        }
14994
        this.height = block.bottom;
14995
        this.i++;
14996
    }
14997
    line(view, line, extraMarkers) {
14998
        let localMarkers = [];
14999
        advanceCursor(this.cursor, localMarkers, line.from);
15000
        if (extraMarkers.length)
15001
            localMarkers = localMarkers.concat(extraMarkers);
15002
        let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
15003
        if (forLine)
15004
            localMarkers.unshift(forLine);
15005
        let gutter = this.gutter;
15006
        if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)
15007
            return;
15008
        this.addElement(view, line, localMarkers);
15009
    }
15010
    widget(view, block) {
1441 ariadna 15011
        let marker = this.gutter.config.widgetMarker(view, block.widget, block), markers = marker ? [marker] : null;
15012
        for (let cls of view.state.facet(gutterWidgetClass)) {
15013
            let marker = cls(view, block.widget, block);
15014
            if (marker)
15015
                (markers || (markers = [])).push(marker);
15016
        }
15017
        if (markers)
15018
            this.addElement(view, block, markers);
1 efrain 15019
    }
15020
    finish() {
15021
        let gutter = this.gutter;
15022
        while (gutter.elements.length > this.i) {
15023
            let last = gutter.elements.pop();
15024
            gutter.dom.removeChild(last.dom);
15025
            last.destroy();
15026
        }
15027
    }
15028
}
15029
class SingleGutterView {
15030
    constructor(view, config) {
15031
        this.view = view;
15032
        this.config = config;
15033
        this.elements = [];
15034
        this.spacer = null;
15035
        this.dom = document.createElement("div");
15036
        this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
15037
        for (let prop in config.domEventHandlers) {
15038
            this.dom.addEventListener(prop, (event) => {
15039
                let target = event.target, y;
15040
                if (target != this.dom && this.dom.contains(target)) {
15041
                    while (target.parentNode != this.dom)
15042
                        target = target.parentNode;
15043
                    let rect = target.getBoundingClientRect();
15044
                    y = (rect.top + rect.bottom) / 2;
15045
                }
15046
                else {
15047
                    y = event.clientY;
15048
                }
15049
                let line = view.lineBlockAtHeight(y - view.documentTop);
15050
                if (config.domEventHandlers[prop](view, line, event))
15051
                    event.preventDefault();
15052
            });
15053
        }
15054
        this.markers = asArray(config.markers(view));
15055
        if (config.initialSpacer) {
15056
            this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);
15057
            this.dom.appendChild(this.spacer.dom);
15058
            this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
15059
        }
15060
    }
15061
    update(update) {
15062
        let prevMarkers = this.markers;
15063
        this.markers = asArray(this.config.markers(update.view));
15064
        if (this.spacer && this.config.updateSpacer) {
15065
            let updated = this.config.updateSpacer(this.spacer.markers[0], update);
15066
            if (updated != this.spacer.markers[0])
15067
                this.spacer.update(update.view, 0, 0, [updated]);
15068
        }
15069
        let vp = update.view.viewport;
15070
        return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||
15071
            (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);
15072
    }
15073
    destroy() {
15074
        for (let elt of this.elements)
15075
            elt.destroy();
15076
    }
15077
}
15078
class GutterElement {
15079
    constructor(view, height, above, markers) {
15080
        this.height = -1;
15081
        this.above = 0;
15082
        this.markers = [];
15083
        this.dom = document.createElement("div");
15084
        this.dom.className = "cm-gutterElement";
15085
        this.update(view, height, above, markers);
15086
    }
15087
    update(view, height, above, markers) {
15088
        if (this.height != height) {
15089
            this.height = height;
15090
            this.dom.style.height = height + "px";
15091
        }
15092
        if (this.above != above)
15093
            this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
15094
        if (!sameMarkers(this.markers, markers))
15095
            this.setMarkers(view, markers);
15096
    }
15097
    setMarkers(view, markers) {
15098
        let cls = "cm-gutterElement", domPos = this.dom.firstChild;
15099
        for (let iNew = 0, iOld = 0;;) {
15100
            let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
15101
            if (marker) {
15102
                let c = marker.elementClass;
15103
                if (c)
15104
                    cls += " " + c;
15105
                for (let i = iOld; i < this.markers.length; i++)
15106
                    if (this.markers[i].compare(marker)) {
15107
                        skipTo = i;
15108
                        matched = true;
15109
                        break;
15110
                    }
15111
            }
15112
            else {
15113
                skipTo = this.markers.length;
15114
            }
15115
            while (iOld < skipTo) {
15116
                let next = this.markers[iOld++];
15117
                if (next.toDOM) {
15118
                    next.destroy(domPos);
15119
                    let after = domPos.nextSibling;
15120
                    domPos.remove();
15121
                    domPos = after;
15122
                }
15123
            }
15124
            if (!marker)
15125
                break;
15126
            if (marker.toDOM) {
15127
                if (matched)
15128
                    domPos = domPos.nextSibling;
15129
                else
15130
                    this.dom.insertBefore(marker.toDOM(view), domPos);
15131
            }
15132
            if (matched)
15133
                iOld++;
15134
        }
15135
        this.dom.className = cls;
15136
        this.markers = markers;
15137
    }
15138
    destroy() {
15139
        this.setMarkers(null, []); // First argument not used unless creating markers
15140
    }
15141
}
15142
function sameMarkers(a, b) {
15143
    if (a.length != b.length)
15144
        return false;
15145
    for (let i = 0; i < a.length; i++)
15146
        if (!a[i].compare(b[i]))
15147
            return false;
15148
    return true;
15149
}
15150
/**
15151
Facet used to provide markers to the line number gutter.
15152
*/
15153
const lineNumberMarkers = /*@__PURE__*/Facet.define();
1441 ariadna 15154
/**
15155
Facet used to create markers in the line number gutter next to widgets.
15156
*/
15157
const lineNumberWidgetMarker = /*@__PURE__*/Facet.define();
1 efrain 15158
const lineNumberConfig = /*@__PURE__*/Facet.define({
15159
    combine(values) {
15160
        return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
15161
            domEventHandlers(a, b) {
15162
                let result = Object.assign({}, a);
15163
                for (let event in b) {
15164
                    let exists = result[event], add = b[event];
15165
                    result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;
15166
                }
15167
                return result;
15168
            }
15169
        });
15170
    }
15171
});
15172
class NumberMarker extends GutterMarker {
15173
    constructor(number) {
15174
        super();
15175
        this.number = number;
15176
    }
15177
    eq(other) { return this.number == other.number; }
15178
    toDOM() { return document.createTextNode(this.number); }
15179
}
15180
function formatNumber(view, number) {
15181
    return view.state.facet(lineNumberConfig).formatNumber(number, view.state);
15182
}
15183
const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({
15184
    class: "cm-lineNumbers",
15185
    renderEmptyElements: false,
15186
    markers(view) { return view.state.facet(lineNumberMarkers); },
15187
    lineMarker(view, line, others) {
15188
        if (others.some(m => m.toDOM))
15189
            return null;
15190
        return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
15191
    },
1441 ariadna 15192
    widgetMarker: (view, widget, block) => {
15193
        for (let m of view.state.facet(lineNumberWidgetMarker)) {
15194
            let result = m(view, widget, block);
15195
            if (result)
15196
                return result;
15197
        }
15198
        return null;
15199
    },
1 efrain 15200
    lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),
15201
    initialSpacer(view) {
15202
        return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
15203
    },
15204
    updateSpacer(spacer, update) {
15205
        let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));
15206
        return max == spacer.number ? spacer : new NumberMarker(max);
15207
    },
15208
    domEventHandlers: state.facet(lineNumberConfig).domEventHandlers
15209
}));
15210
/**
15211
Create a line number gutter extension.
15212
*/
15213
function lineNumbers(config = {}) {
15214
    return [
15215
        lineNumberConfig.of(config),
15216
        gutters(),
15217
        lineNumberGutter
15218
    ];
15219
}
15220
function maxLineNumber(lines) {
15221
    let last = 9;
15222
    while (last < lines)
15223
        last = last * 10 + 9;
15224
    return last;
15225
}
15226
const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {
15227
    constructor() {
15228
        super(...arguments);
15229
        this.elementClass = "cm-activeLineGutter";
15230
    }
15231
};
15232
const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => {
15233
    let marks = [], last = -1;
15234
    for (let range of state.selection.ranges) {
15235
        let linePos = state.doc.lineAt(range.head).from;
15236
        if (linePos > last) {
15237
            last = linePos;
15238
            marks.push(activeLineGutterMarker.range(linePos));
15239
        }
15240
    }
15241
    return RangeSet.of(marks);
15242
});
15243
/**
15244
Returns an extension that adds a `cm-activeLineGutter` class to
15245
all gutter elements on the [active
15246
line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
15247
*/
15248
function highlightActiveLineGutter() {
15249
    return activeLineGutterHighlighter;
15250
}
15251
 
15252
/**
15253
The default maximum length of a `TreeBuffer` node.
15254
*/
15255
const DefaultBufferLength = 1024;
15256
let nextPropID = 0;
15257
class Range {
15258
    constructor(from, to) {
15259
        this.from = from;
15260
        this.to = to;
15261
    }
15262
}
15263
/**
15264
Each [node type](#common.NodeType) or [individual tree](#common.Tree)
15265
can have metadata associated with it in props. Instances of this
15266
class represent prop names.
15267
*/
15268
class NodeProp {
15269
    /**
15270
    Create a new node prop type.
15271
    */
15272
    constructor(config = {}) {
15273
        this.id = nextPropID++;
15274
        this.perNode = !!config.perNode;
15275
        this.deserialize = config.deserialize || (() => {
15276
            throw new Error("This node type doesn't define a deserialize function");
15277
        });
15278
    }
15279
    /**
15280
    This is meant to be used with
15281
    [`NodeSet.extend`](#common.NodeSet.extend) or
15282
    [`LRParser.configure`](#lr.ParserConfig.props) to compute
15283
    prop values for each node type in the set. Takes a [match
15284
    object](#common.NodeType^match) or function that returns undefined
15285
    if the node type doesn't get this prop, and the prop's value if
15286
    it does.
15287
    */
15288
    add(match) {
15289
        if (this.perNode)
15290
            throw new RangeError("Can't add per-node props to node types");
15291
        if (typeof match != "function")
15292
            match = NodeType.match(match);
15293
        return (type) => {
15294
            let result = match(type);
15295
            return result === undefined ? null : [this, result];
15296
        };
15297
    }
15298
}
15299
/**
15300
Prop that is used to describe matching delimiters. For opening
15301
delimiters, this holds an array of node names (written as a
15302
space-separated string when declaring this prop in a grammar)
15303
for the node types of closing delimiters that match it.
15304
*/
15305
NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
15306
/**
15307
The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
15308
attached to closing delimiters, holding an array of node names
15309
of types of matching opening delimiters.
15310
*/
15311
NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
15312
/**
15313
Used to assign node types to groups (for example, all node
15314
types that represent an expression could be tagged with an
15315
`"Expression"` group).
15316
*/
15317
NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
15318
/**
15319
Attached to nodes to indicate these should be
15320
[displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
15321
in a bidirectional text isolate, so that direction-neutral
15322
characters on their sides don't incorrectly get associated with
15323
surrounding text. You'll generally want to set this for nodes
15324
that contain arbitrary text, like strings and comments, and for
15325
nodes that appear _inside_ arbitrary text, like HTML tags. When
15326
not given a value, in a grammar declaration, defaults to
15327
`"auto"`.
15328
*/
15329
NodeProp.isolate = new NodeProp({ deserialize: value => {
15330
        if (value && value != "rtl" && value != "ltr" && value != "auto")
15331
            throw new RangeError("Invalid value for isolate: " + value);
15332
        return value || "auto";
15333
    } });
15334
/**
15335
The hash of the [context](#lr.ContextTracker.constructor)
15336
that the node was parsed in, if any. Used to limit reuse of
15337
contextual nodes.
15338
*/
15339
NodeProp.contextHash = new NodeProp({ perNode: true });
15340
/**
15341
The distance beyond the end of the node that the tokenizer
15342
looked ahead for any of the tokens inside the node. (The LR
15343
parser only stores this when it is larger than 25, for
15344
efficiency reasons.)
15345
*/
15346
NodeProp.lookAhead = new NodeProp({ perNode: true });
15347
/**
15348
This per-node prop is used to replace a given node, or part of a
15349
node, with another tree. This is useful to include trees from
15350
different languages in mixed-language parsers.
15351
*/
15352
NodeProp.mounted = new NodeProp({ perNode: true });
15353
/**
15354
A mounted tree, which can be [stored](#common.NodeProp^mounted) on
15355
a tree node to indicate that parts of its content are
15356
represented by another tree.
15357
*/
15358
class MountedTree {
15359
    constructor(
15360
    /**
15361
    The inner tree.
15362
    */
15363
    tree,
15364
    /**
15365
    If this is null, this tree replaces the entire node (it will
15366
    be included in the regular iteration instead of its host
15367
    node). If not, only the given ranges are considered to be
15368
    covered by this tree. This is used for trees that are mixed in
15369
    a way that isn't strictly hierarchical. Such mounted trees are
15370
    only entered by [`resolveInner`](#common.Tree.resolveInner)
15371
    and [`enter`](#common.SyntaxNode.enter).
15372
    */
15373
    overlay,
15374
    /**
15375
    The parser used to create this subtree.
15376
    */
15377
    parser) {
15378
        this.tree = tree;
15379
        this.overlay = overlay;
15380
        this.parser = parser;
15381
    }
15382
    /**
15383
    @internal
15384
    */
15385
    static get(tree) {
15386
        return tree && tree.props && tree.props[NodeProp.mounted.id];
15387
    }
15388
}
15389
const noProps = Object.create(null);
15390
/**
15391
Each node in a syntax tree has a node type associated with it.
15392
*/
15393
class NodeType {
15394
    /**
15395
    @internal
15396
    */
15397
    constructor(
15398
    /**
15399
    The name of the node type. Not necessarily unique, but if the
15400
    grammar was written properly, different node types with the
15401
    same name within a node set should play the same semantic
15402
    role.
15403
    */
15404
    name,
15405
    /**
15406
    @internal
15407
    */
15408
    props,
15409
    /**
15410
    The id of this node in its set. Corresponds to the term ids
15411
    used in the parser.
15412
    */
15413
    id,
15414
    /**
15415
    @internal
15416
    */
15417
    flags = 0) {
15418
        this.name = name;
15419
        this.props = props;
15420
        this.id = id;
15421
        this.flags = flags;
15422
    }
15423
    /**
15424
    Define a node type.
15425
    */
15426
    static define(spec) {
15427
        let props = spec.props && spec.props.length ? Object.create(null) : noProps;
15428
        let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |
15429
            (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);
15430
        let type = new NodeType(spec.name || "", props, spec.id, flags);
15431
        if (spec.props)
15432
            for (let src of spec.props) {
15433
                if (!Array.isArray(src))
15434
                    src = src(type);
15435
                if (src) {
15436
                    if (src[0].perNode)
15437
                        throw new RangeError("Can't store a per-node prop on a node type");
15438
                    props[src[0].id] = src[1];
15439
                }
15440
            }
15441
        return type;
15442
    }
15443
    /**
15444
    Retrieves a node prop for this type. Will return `undefined` if
15445
    the prop isn't present on this node.
15446
    */
15447
    prop(prop) { return this.props[prop.id]; }
15448
    /**
15449
    True when this is the top node of a grammar.
15450
    */
15451
    get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }
15452
    /**
15453
    True when this node is produced by a skip rule.
15454
    */
15455
    get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }
15456
    /**
15457
    Indicates whether this is an error node.
15458
    */
15459
    get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }
15460
    /**
15461
    When true, this node type doesn't correspond to a user-declared
15462
    named node, for example because it is used to cache repetition.
15463
    */
15464
    get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }
15465
    /**
15466
    Returns true when this node's name or one of its
15467
    [groups](#common.NodeProp^group) matches the given string.
15468
    */
15469
    is(name) {
15470
        if (typeof name == 'string') {
15471
            if (this.name == name)
15472
                return true;
15473
            let group = this.prop(NodeProp.group);
15474
            return group ? group.indexOf(name) > -1 : false;
15475
        }
15476
        return this.id == name;
15477
    }
15478
    /**
15479
    Create a function from node types to arbitrary values by
15480
    specifying an object whose property names are node or
15481
    [group](#common.NodeProp^group) names. Often useful with
15482
    [`NodeProp.add`](#common.NodeProp.add). You can put multiple
15483
    names, separated by spaces, in a single property name to map
15484
    multiple node names to a single value.
15485
    */
15486
    static match(map) {
15487
        let direct = Object.create(null);
15488
        for (let prop in map)
15489
            for (let name of prop.split(" "))
15490
                direct[name] = map[prop];
15491
        return (node) => {
15492
            for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
15493
                let found = direct[i < 0 ? node.name : groups[i]];
15494
                if (found)
15495
                    return found;
15496
            }
15497
        };
15498
    }
15499
}
15500
/**
15501
An empty dummy node type to use when no actual type is available.
15502
*/
15503
NodeType.none = new NodeType("", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);
15504
/**
15505
A node set holds a collection of node types. It is used to
15506
compactly represent trees by storing their type ids, rather than a
15507
full pointer to the type object, in a numeric array. Each parser
15508
[has](#lr.LRParser.nodeSet) a node set, and [tree
15509
buffers](#common.TreeBuffer) can only store collections of nodes
15510
from the same set. A set can have a maximum of 2**16 (65536) node
15511
types in it, so that the ids fit into 16-bit typed array slots.
15512
*/
15513
class NodeSet {
15514
    /**
15515
    Create a set with the given types. The `id` property of each
15516
    type should correspond to its position within the array.
15517
    */
15518
    constructor(
15519
    /**
15520
    The node types in this set, by id.
15521
    */
15522
    types) {
15523
        this.types = types;
15524
        for (let i = 0; i < types.length; i++)
15525
            if (types[i].id != i)
15526
                throw new RangeError("Node type ids should correspond to array positions when creating a node set");
15527
    }
15528
    /**
15529
    Create a copy of this set with some node properties added. The
15530
    arguments to this method can be created with
15531
    [`NodeProp.add`](#common.NodeProp.add).
15532
    */
15533
    extend(...props) {
15534
        let newTypes = [];
15535
        for (let type of this.types) {
15536
            let newProps = null;
15537
            for (let source of props) {
15538
                let add = source(type);
15539
                if (add) {
15540
                    if (!newProps)
15541
                        newProps = Object.assign({}, type.props);
15542
                    newProps[add[0].id] = add[1];
15543
                }
15544
            }
15545
            newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
15546
        }
15547
        return new NodeSet(newTypes);
15548
    }
15549
}
15550
const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
15551
/**
15552
Options that control iteration. Can be combined with the `|`
15553
operator to enable multiple ones.
15554
*/
15555
var IterMode;
15556
(function (IterMode) {
15557
    /**
15558
    When enabled, iteration will only visit [`Tree`](#common.Tree)
15559
    objects, not nodes packed into
15560
    [`TreeBuffer`](#common.TreeBuffer)s.
15561
    */
15562
    IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
15563
    /**
15564
    Enable this to make iteration include anonymous nodes (such as
15565
    the nodes that wrap repeated grammar constructs into a balanced
15566
    tree).
15567
    */
15568
    IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
15569
    /**
15570
    By default, regular [mounted](#common.NodeProp^mounted) nodes
15571
    replace their base node in iteration. Enable this to ignore them
15572
    instead.
15573
    */
15574
    IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
15575
    /**
15576
    This option only applies in
15577
    [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
15578
    library to not enter mounted overlays if one covers the given
15579
    position.
15580
    */
15581
    IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
15582
})(IterMode || (IterMode = {}));
15583
/**
15584
A piece of syntax tree. There are two ways to approach these
15585
trees: the way they are actually stored in memory, and the
15586
convenient way.
15587
 
15588
Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
15589
objects. By packing detail information into `TreeBuffer` leaf
15590
nodes, the representation is made a lot more memory-efficient.
15591
 
15592
However, when you want to actually work with tree nodes, this
15593
representation is very awkward, so most client code will want to
15594
use the [`TreeCursor`](#common.TreeCursor) or
15595
[`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
15596
a view on some part of this data structure, and can be used to
15597
move around to adjacent nodes.
15598
*/
15599
class Tree {
15600
    /**
15601
    Construct a new tree. See also [`Tree.build`](#common.Tree^build).
15602
    */
15603
    constructor(
15604
    /**
15605
    The type of the top node.
15606
    */
15607
    type,
15608
    /**
15609
    This node's child nodes.
15610
    */
15611
    children,
15612
    /**
15613
    The positions (offsets relative to the start of this tree) of
15614
    the children.
15615
    */
15616
    positions,
15617
    /**
15618
    The total length of this tree
15619
    */
15620
    length,
15621
    /**
15622
    Per-node [node props](#common.NodeProp) to associate with this node.
15623
    */
15624
    props) {
15625
        this.type = type;
15626
        this.children = children;
15627
        this.positions = positions;
15628
        this.length = length;
15629
        /**
15630
        @internal
15631
        */
15632
        this.props = null;
15633
        if (props && props.length) {
15634
            this.props = Object.create(null);
15635
            for (let [prop, value] of props)
15636
                this.props[typeof prop == "number" ? prop : prop.id] = value;
15637
        }
15638
    }
15639
    /**
15640
    @internal
15641
    */
15642
    toString() {
15643
        let mounted = MountedTree.get(this);
15644
        if (mounted && !mounted.overlay)
15645
            return mounted.tree.toString();
15646
        let children = "";
15647
        for (let ch of this.children) {
15648
            let str = ch.toString();
15649
            if (str) {
15650
                if (children)
15651
                    children += ",";
15652
                children += str;
15653
            }
15654
        }
15655
        return !this.type.name ? children :
15656
            (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
15657
                (children.length ? "(" + children + ")" : "");
15658
    }
15659
    /**
15660
    Get a [tree cursor](#common.TreeCursor) positioned at the top of
15661
    the tree. Mode can be used to [control](#common.IterMode) which
15662
    nodes the cursor visits.
15663
    */
15664
    cursor(mode = 0) {
15665
        return new TreeCursor(this.topNode, mode);
15666
    }
15667
    /**
15668
    Get a [tree cursor](#common.TreeCursor) pointing into this tree
15669
    at the given position and side (see
15670
    [`moveTo`](#common.TreeCursor.moveTo).
15671
    */
15672
    cursorAt(pos, side = 0, mode = 0) {
15673
        let scope = CachedNode.get(this) || this.topNode;
15674
        let cursor = new TreeCursor(scope);
15675
        cursor.moveTo(pos, side);
15676
        CachedNode.set(this, cursor._tree);
15677
        return cursor;
15678
    }
15679
    /**
15680
    Get a [syntax node](#common.SyntaxNode) object for the top of the
15681
    tree.
15682
    */
15683
    get topNode() {
15684
        return new TreeNode(this, 0, 0, null);
15685
    }
15686
    /**
15687
    Get the [syntax node](#common.SyntaxNode) at the given position.
15688
    If `side` is -1, this will move into nodes that end at the
15689
    position. If 1, it'll move into nodes that start at the
15690
    position. With 0, it'll only enter nodes that cover the position
15691
    from both sides.
15692
 
15693
    Note that this will not enter
15694
    [overlays](#common.MountedTree.overlay), and you often want
15695
    [`resolveInner`](#common.Tree.resolveInner) instead.
15696
    */
15697
    resolve(pos, side = 0) {
15698
        let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
15699
        CachedNode.set(this, node);
15700
        return node;
15701
    }
15702
    /**
15703
    Like [`resolve`](#common.Tree.resolve), but will enter
15704
    [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
15705
    pointing into the innermost overlaid tree at the given position
15706
    (with parent links going through all parent structure, including
15707
    the host trees).
15708
    */
15709
    resolveInner(pos, side = 0) {
15710
        let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
15711
        CachedInnerNode.set(this, node);
15712
        return node;
15713
    }
15714
    /**
15715
    In some situations, it can be useful to iterate through all
15716
    nodes around a position, including those in overlays that don't
15717
    directly cover the position. This method gives you an iterator
15718
    that will produce all nodes, from small to big, around the given
15719
    position.
15720
    */
15721
    resolveStack(pos, side = 0) {
15722
        return stackIterator(this, pos, side);
15723
    }
15724
    /**
15725
    Iterate over the tree and its children, calling `enter` for any
15726
    node that touches the `from`/`to` region (if given) before
15727
    running over such a node's children, and `leave` (if given) when
15728
    leaving the node. When `enter` returns `false`, that node will
15729
    not have its children iterated over (or `leave` called).
15730
    */
15731
    iterate(spec) {
15732
        let { enter, leave, from = 0, to = this.length } = spec;
15733
        let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
15734
        for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
15735
            let entered = false;
15736
            if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
15737
                if (c.firstChild())
15738
                    continue;
15739
                entered = true;
15740
            }
15741
            for (;;) {
15742
                if (entered && leave && (anon || !c.type.isAnonymous))
15743
                    leave(c);
15744
                if (c.nextSibling())
15745
                    break;
15746
                if (!c.parent())
15747
                    return;
15748
                entered = true;
15749
            }
15750
        }
15751
    }
15752
    /**
15753
    Get the value of the given [node prop](#common.NodeProp) for this
15754
    node. Works with both per-node and per-type props.
15755
    */
15756
    prop(prop) {
15757
        return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
15758
    }
15759
    /**
15760
    Returns the node's [per-node props](#common.NodeProp.perNode) in a
15761
    format that can be passed to the [`Tree`](#common.Tree)
15762
    constructor.
15763
    */
15764
    get propValues() {
15765
        let result = [];
15766
        if (this.props)
15767
            for (let id in this.props)
15768
                result.push([+id, this.props[id]]);
15769
        return result;
15770
    }
15771
    /**
15772
    Balance the direct children of this tree, producing a copy of
15773
    which may have children grouped into subtrees with type
15774
    [`NodeType.none`](#common.NodeType^none).
15775
    */
15776
    balance(config = {}) {
15777
        return this.children.length <= 8 /* Balance.BranchFactor */ ? this :
15778
            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)));
15779
    }
15780
    /**
15781
    Build a tree from a postfix-ordered buffer of node information,
15782
    or a cursor over such a buffer.
15783
    */
15784
    static build(data) { return buildTree(data); }
15785
}
15786
/**
15787
The empty tree
15788
*/
15789
Tree.empty = new Tree(NodeType.none, [], [], 0);
15790
class FlatBufferCursor {
15791
    constructor(buffer, index) {
15792
        this.buffer = buffer;
15793
        this.index = index;
15794
    }
15795
    get id() { return this.buffer[this.index - 4]; }
15796
    get start() { return this.buffer[this.index - 3]; }
15797
    get end() { return this.buffer[this.index - 2]; }
15798
    get size() { return this.buffer[this.index - 1]; }
15799
    get pos() { return this.index; }
15800
    next() { this.index -= 4; }
15801
    fork() { return new FlatBufferCursor(this.buffer, this.index); }
15802
}
15803
/**
15804
Tree buffers contain (type, start, end, endIndex) quads for each
15805
node. In such a buffer, nodes are stored in prefix order (parents
15806
before children, with the endIndex of the parent indicating which
15807
children belong to it).
15808
*/
15809
class TreeBuffer {
15810
    /**
15811
    Create a tree buffer.
15812
    */
15813
    constructor(
15814
    /**
15815
    The buffer's content.
15816
    */
15817
    buffer,
15818
    /**
15819
    The total length of the group of nodes in the buffer.
15820
    */
15821
    length,
15822
    /**
15823
    The node set used in this buffer.
15824
    */
15825
    set) {
15826
        this.buffer = buffer;
15827
        this.length = length;
15828
        this.set = set;
15829
    }
15830
    /**
15831
    @internal
15832
    */
15833
    get type() { return NodeType.none; }
15834
    /**
15835
    @internal
15836
    */
15837
    toString() {
15838
        let result = [];
15839
        for (let index = 0; index < this.buffer.length;) {
15840
            result.push(this.childString(index));
15841
            index = this.buffer[index + 3];
15842
        }
15843
        return result.join(",");
15844
    }
15845
    /**
15846
    @internal
15847
    */
15848
    childString(index) {
15849
        let id = this.buffer[index], endIndex = this.buffer[index + 3];
15850
        let type = this.set.types[id], result = type.name;
15851
        if (/\W/.test(result) && !type.isError)
15852
            result = JSON.stringify(result);
15853
        index += 4;
15854
        if (endIndex == index)
15855
            return result;
15856
        let children = [];
15857
        while (index < endIndex) {
15858
            children.push(this.childString(index));
15859
            index = this.buffer[index + 3];
15860
        }
15861
        return result + "(" + children.join(",") + ")";
15862
    }
15863
    /**
15864
    @internal
15865
    */
15866
    findChild(startIndex, endIndex, dir, pos, side) {
15867
        let { buffer } = this, pick = -1;
15868
        for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
15869
            if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
15870
                pick = i;
15871
                if (dir > 0)
15872
                    break;
15873
            }
15874
        }
15875
        return pick;
15876
    }
15877
    /**
15878
    @internal
15879
    */
15880
    slice(startI, endI, from) {
15881
        let b = this.buffer;
15882
        let copy = new Uint16Array(endI - startI), len = 0;
15883
        for (let i = startI, j = 0; i < endI;) {
15884
            copy[j++] = b[i++];
15885
            copy[j++] = b[i++] - from;
15886
            let to = copy[j++] = b[i++] - from;
15887
            copy[j++] = b[i++] - startI;
15888
            len = Math.max(len, to);
15889
        }
15890
        return new TreeBuffer(copy, len, this.set);
15891
    }
15892
}
15893
function checkSide(side, pos, from, to) {
15894
    switch (side) {
15895
        case -2 /* Side.Before */: return from < pos;
15896
        case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;
15897
        case 0 /* Side.Around */: return from < pos && to > pos;
15898
        case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;
15899
        case 2 /* Side.After */: return to > pos;
15900
        case 4 /* Side.DontCare */: return true;
15901
    }
15902
}
15903
function resolveNode(node, pos, side, overlays) {
15904
    var _a;
15905
    // Move up to a node that actually holds the position, if possible
15906
    while (node.from == node.to ||
15907
        (side < 1 ? node.from >= pos : node.from > pos) ||
15908
        (side > -1 ? node.to <= pos : node.to < pos)) {
15909
        let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
15910
        if (!parent)
15911
            return node;
15912
        node = parent;
15913
    }
15914
    let mode = overlays ? 0 : IterMode.IgnoreOverlays;
15915
    // Must go up out of overlays when those do not overlap with pos
15916
    if (overlays)
15917
        for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
15918
            if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
15919
                node = parent;
15920
        }
15921
    for (;;) {
15922
        let inner = node.enter(pos, side, mode);
15923
        if (!inner)
15924
            return node;
15925
        node = inner;
15926
    }
15927
}
15928
class BaseNode {
15929
    cursor(mode = 0) { return new TreeCursor(this, mode); }
15930
    getChild(type, before = null, after = null) {
15931
        let r = getChildren(this, type, before, after);
15932
        return r.length ? r[0] : null;
15933
    }
15934
    getChildren(type, before = null, after = null) {
15935
        return getChildren(this, type, before, after);
15936
    }
15937
    resolve(pos, side = 0) {
15938
        return resolveNode(this, pos, side, false);
15939
    }
15940
    resolveInner(pos, side = 0) {
15941
        return resolveNode(this, pos, side, true);
15942
    }
15943
    matchContext(context) {
1441 ariadna 15944
        return matchNodeContext(this.parent, context);
1 efrain 15945
    }
15946
    enterUnfinishedNodesBefore(pos) {
15947
        let scan = this.childBefore(pos), node = this;
15948
        while (scan) {
15949
            let last = scan.lastChild;
15950
            if (!last || last.to != scan.to)
15951
                break;
15952
            if (last.type.isError && last.from == last.to) {
15953
                node = scan;
15954
                scan = last.prevSibling;
15955
            }
15956
            else {
15957
                scan = last;
15958
            }
15959
        }
15960
        return node;
15961
    }
15962
    get node() { return this; }
15963
    get next() { return this.parent; }
15964
}
15965
class TreeNode extends BaseNode {
15966
    constructor(_tree, from,
15967
    // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
15968
    index, _parent) {
15969
        super();
15970
        this._tree = _tree;
15971
        this.from = from;
15972
        this.index = index;
15973
        this._parent = _parent;
15974
    }
15975
    get type() { return this._tree.type; }
15976
    get name() { return this._tree.type.name; }
15977
    get to() { return this.from + this._tree.length; }
15978
    nextChild(i, dir, pos, side, mode = 0) {
15979
        for (let parent = this;;) {
15980
            for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
15981
                let next = children[i], start = positions[i] + parent.from;
15982
                if (!checkSide(side, pos, start, start + next.length))
15983
                    continue;
15984
                if (next instanceof TreeBuffer) {
15985
                    if (mode & IterMode.ExcludeBuffers)
15986
                        continue;
15987
                    let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
15988
                    if (index > -1)
15989
                        return new BufferNode(new BufferContext(parent, next, i, start), null, index);
15990
                }
15991
                else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
15992
                    let mounted;
15993
                    if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
15994
                        return new TreeNode(mounted.tree, start, i, parent);
15995
                    let inner = new TreeNode(next, start, i, parent);
15996
                    return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
15997
                        : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
15998
                }
15999
            }
16000
            if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
16001
                return null;
16002
            if (parent.index >= 0)
16003
                i = parent.index + dir;
16004
            else
16005
                i = dir < 0 ? -1 : parent._parent._tree.children.length;
16006
            parent = parent._parent;
16007
            if (!parent)
16008
                return null;
16009
        }
16010
    }
16011
    get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }
16012
    get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }
16013
    childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }
16014
    childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }
16015
    enter(pos, side, mode = 0) {
16016
        let mounted;
16017
        if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
16018
            let rPos = pos - this.from;
16019
            for (let { from, to } of mounted.overlay) {
16020
                if ((side > 0 ? from <= rPos : from < rPos) &&
16021
                    (side < 0 ? to >= rPos : to > rPos))
16022
                    return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
16023
            }
16024
        }
16025
        return this.nextChild(0, 1, pos, side, mode);
16026
    }
16027
    nextSignificantParent() {
16028
        let val = this;
16029
        while (val.type.isAnonymous && val._parent)
16030
            val = val._parent;
16031
        return val;
16032
    }
16033
    get parent() {
16034
        return this._parent ? this._parent.nextSignificantParent() : null;
16035
    }
16036
    get nextSibling() {
16037
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;
16038
    }
16039
    get prevSibling() {
16040
        return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;
16041
    }
16042
    get tree() { return this._tree; }
16043
    toTree() { return this._tree; }
16044
    /**
16045
    @internal
16046
    */
16047
    toString() { return this._tree.toString(); }
16048
}
16049
function getChildren(node, type, before, after) {
16050
    let cur = node.cursor(), result = [];
16051
    if (!cur.firstChild())
16052
        return result;
16053
    if (before != null)
16054
        for (let found = false; !found;) {
16055
            found = cur.type.is(before);
16056
            if (!cur.nextSibling())
16057
                return result;
16058
        }
16059
    for (;;) {
16060
        if (after != null && cur.type.is(after))
16061
            return result;
16062
        if (cur.type.is(type))
16063
            result.push(cur.node);
16064
        if (!cur.nextSibling())
16065
            return after == null ? result : [];
16066
    }
16067
}
16068
function matchNodeContext(node, context, i = context.length - 1) {
1441 ariadna 16069
    for (let p = node; i >= 0; p = p.parent) {
1 efrain 16070
        if (!p)
16071
            return false;
16072
        if (!p.type.isAnonymous) {
16073
            if (context[i] && context[i] != p.name)
16074
                return false;
16075
            i--;
16076
        }
16077
    }
16078
    return true;
16079
}
16080
class BufferContext {
16081
    constructor(parent, buffer, index, start) {
16082
        this.parent = parent;
16083
        this.buffer = buffer;
16084
        this.index = index;
16085
        this.start = start;
16086
    }
16087
}
16088
class BufferNode extends BaseNode {
16089
    get name() { return this.type.name; }
16090
    get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
16091
    get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
16092
    constructor(context, _parent, index) {
16093
        super();
16094
        this.context = context;
16095
        this._parent = _parent;
16096
        this.index = index;
16097
        this.type = context.buffer.set.types[context.buffer.buffer[index]];
16098
    }
16099
    child(dir, pos, side) {
16100
        let { buffer } = this.context;
16101
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
16102
        return index < 0 ? null : new BufferNode(this.context, this, index);
16103
    }
16104
    get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }
16105
    get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }
16106
    childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }
16107
    childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }
16108
    enter(pos, side, mode = 0) {
16109
        if (mode & IterMode.ExcludeBuffers)
16110
            return null;
16111
        let { buffer } = this.context;
16112
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
16113
        return index < 0 ? null : new BufferNode(this.context, this, index);
16114
    }
16115
    get parent() {
16116
        return this._parent || this.context.parent.nextSignificantParent();
16117
    }
16118
    externalSibling(dir) {
16119
        return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);
16120
    }
16121
    get nextSibling() {
16122
        let { buffer } = this.context;
16123
        let after = buffer.buffer[this.index + 3];
16124
        if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
16125
            return new BufferNode(this.context, this._parent, after);
16126
        return this.externalSibling(1);
16127
    }
16128
    get prevSibling() {
16129
        let { buffer } = this.context;
16130
        let parentStart = this._parent ? this._parent.index + 4 : 0;
16131
        if (this.index == parentStart)
16132
            return this.externalSibling(-1);
16133
        return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
16134
    }
16135
    get tree() { return null; }
16136
    toTree() {
16137
        let children = [], positions = [];
16138
        let { buffer } = this.context;
16139
        let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
16140
        if (endI > startI) {
16141
            let from = buffer.buffer[this.index + 1];
16142
            children.push(buffer.slice(startI, endI, from));
16143
            positions.push(0);
16144
        }
16145
        return new Tree(this.type, children, positions, this.to - this.from);
16146
    }
16147
    /**
16148
    @internal
16149
    */
16150
    toString() { return this.context.buffer.childString(this.index); }
16151
}
16152
function iterStack(heads) {
16153
    if (!heads.length)
16154
        return null;
16155
    let pick = 0, picked = heads[0];
16156
    for (let i = 1; i < heads.length; i++) {
16157
        let node = heads[i];
16158
        if (node.from > picked.from || node.to < picked.to) {
16159
            picked = node;
16160
            pick = i;
16161
        }
16162
    }
16163
    let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
16164
    let newHeads = heads.slice();
16165
    if (next)
16166
        newHeads[pick] = next;
16167
    else
16168
        newHeads.splice(pick, 1);
16169
    return new StackIterator(newHeads, picked);
16170
}
16171
class StackIterator {
16172
    constructor(heads, node) {
16173
        this.heads = heads;
16174
        this.node = node;
16175
    }
16176
    get next() { return iterStack(this.heads); }
16177
}
16178
function stackIterator(tree, pos, side) {
16179
    let inner = tree.resolveInner(pos, side), layers = null;
16180
    for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
16181
        if (scan.index < 0) { // This is an overlay root
16182
            let parent = scan.parent;
16183
            (layers || (layers = [inner])).push(parent.resolve(pos, side));
16184
            scan = parent;
16185
        }
16186
        else {
16187
            let mount = MountedTree.get(scan.tree);
16188
            // Relevant overlay branching off
16189
            if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
16190
                let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
16191
                (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
16192
            }
16193
        }
16194
    }
16195
    return layers ? iterStack(layers) : inner;
16196
}
16197
/**
16198
A tree cursor object focuses on a given node in a syntax tree, and
16199
allows you to move to adjacent nodes.
16200
*/
16201
class TreeCursor {
16202
    /**
16203
    Shorthand for `.type.name`.
16204
    */
16205
    get name() { return this.type.name; }
16206
    /**
16207
    @internal
16208
    */
16209
    constructor(node,
16210
    /**
16211
    @internal
16212
    */
16213
    mode = 0) {
16214
        this.mode = mode;
16215
        /**
16216
        @internal
16217
        */
16218
        this.buffer = null;
16219
        this.stack = [];
16220
        /**
16221
        @internal
16222
        */
16223
        this.index = 0;
16224
        this.bufferNode = null;
16225
        if (node instanceof TreeNode) {
16226
            this.yieldNode(node);
16227
        }
16228
        else {
16229
            this._tree = node.context.parent;
16230
            this.buffer = node.context;
16231
            for (let n = node._parent; n; n = n._parent)
16232
                this.stack.unshift(n.index);
16233
            this.bufferNode = node;
16234
            this.yieldBuf(node.index);
16235
        }
16236
    }
16237
    yieldNode(node) {
16238
        if (!node)
16239
            return false;
16240
        this._tree = node;
16241
        this.type = node.type;
16242
        this.from = node.from;
16243
        this.to = node.to;
16244
        return true;
16245
    }
16246
    yieldBuf(index, type) {
16247
        this.index = index;
16248
        let { start, buffer } = this.buffer;
16249
        this.type = type || buffer.set.types[buffer.buffer[index]];
16250
        this.from = start + buffer.buffer[index + 1];
16251
        this.to = start + buffer.buffer[index + 2];
16252
        return true;
16253
    }
16254
    /**
16255
    @internal
16256
    */
16257
    yield(node) {
16258
        if (!node)
16259
            return false;
16260
        if (node instanceof TreeNode) {
16261
            this.buffer = null;
16262
            return this.yieldNode(node);
16263
        }
16264
        this.buffer = node.context;
16265
        return this.yieldBuf(node.index, node.type);
16266
    }
16267
    /**
16268
    @internal
16269
    */
16270
    toString() {
16271
        return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
16272
    }
16273
    /**
16274
    @internal
16275
    */
16276
    enterChild(dir, pos, side) {
16277
        if (!this.buffer)
16278
            return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
16279
        let { buffer } = this.buffer;
16280
        let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
16281
        if (index < 0)
16282
            return false;
16283
        this.stack.push(this.index);
16284
        return this.yieldBuf(index);
16285
    }
16286
    /**
16287
    Move the cursor to this node's first child. When this returns
16288
    false, the node has no child, and the cursor has not been moved.
16289
    */
16290
    firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }
16291
    /**
16292
    Move the cursor to this node's last child.
16293
    */
16294
    lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }
16295
    /**
16296
    Move the cursor to the first child that ends after `pos`.
16297
    */
16298
    childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }
16299
    /**
16300
    Move to the last child that starts before `pos`.
16301
    */
16302
    childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }
16303
    /**
16304
    Move the cursor to the child around `pos`. If side is -1 the
16305
    child may end at that position, when 1 it may start there. This
16306
    will also enter [overlaid](#common.MountedTree.overlay)
16307
    [mounted](#common.NodeProp^mounted) trees unless `overlays` is
16308
    set to false.
16309
    */
16310
    enter(pos, side, mode = this.mode) {
16311
        if (!this.buffer)
16312
            return this.yield(this._tree.enter(pos, side, mode));
16313
        return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
16314
    }
16315
    /**
16316
    Move to the node's parent node, if this isn't the top node.
16317
    */
16318
    parent() {
16319
        if (!this.buffer)
16320
            return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
16321
        if (this.stack.length)
16322
            return this.yieldBuf(this.stack.pop());
16323
        let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
16324
        this.buffer = null;
16325
        return this.yieldNode(parent);
16326
    }
16327
    /**
16328
    @internal
16329
    */
16330
    sibling(dir) {
16331
        if (!this.buffer)
16332
            return !this._tree._parent ? false
16333
                : this.yield(this._tree.index < 0 ? null
16334
                    : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));
16335
        let { buffer } = this.buffer, d = this.stack.length - 1;
16336
        if (dir < 0) {
16337
            let parentStart = d < 0 ? 0 : this.stack[d] + 4;
16338
            if (this.index != parentStart)
16339
                return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
16340
        }
16341
        else {
16342
            let after = buffer.buffer[this.index + 3];
16343
            if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
16344
                return this.yieldBuf(after);
16345
        }
16346
        return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;
16347
    }
16348
    /**
16349
    Move to this node's next sibling, if any.
16350
    */
16351
    nextSibling() { return this.sibling(1); }
16352
    /**
16353
    Move to this node's previous sibling, if any.
16354
    */
16355
    prevSibling() { return this.sibling(-1); }
16356
    atLastNode(dir) {
16357
        let index, parent, { buffer } = this;
16358
        if (buffer) {
16359
            if (dir > 0) {
16360
                if (this.index < buffer.buffer.buffer.length)
16361
                    return false;
16362
            }
16363
            else {
16364
                for (let i = 0; i < this.index; i++)
16365
                    if (buffer.buffer.buffer[i + 3] < this.index)
16366
                        return false;
16367
            }
16368
            ({ index, parent } = buffer);
16369
        }
16370
        else {
16371
            ({ index, _parent: parent } = this._tree);
16372
        }
16373
        for (; parent; { index, _parent: parent } = parent) {
16374
            if (index > -1)
16375
                for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
16376
                    let child = parent._tree.children[i];
16377
                    if ((this.mode & IterMode.IncludeAnonymous) ||
16378
                        child instanceof TreeBuffer ||
16379
                        !child.type.isAnonymous ||
16380
                        hasChild(child))
16381
                        return false;
16382
                }
16383
        }
16384
        return true;
16385
    }
16386
    move(dir, enter) {
16387
        if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))
16388
            return true;
16389
        for (;;) {
16390
            if (this.sibling(dir))
16391
                return true;
16392
            if (this.atLastNode(dir) || !this.parent())
16393
                return false;
16394
        }
16395
    }
16396
    /**
16397
    Move to the next node in a
16398
    [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
16399
    traversal, going from a node to its first child or, if the
16400
    current node is empty or `enter` is false, its next sibling or
16401
    the next sibling of the first parent node that has one.
16402
    */
16403
    next(enter = true) { return this.move(1, enter); }
16404
    /**
1441 ariadna 16405
    Move to the next node in a last-to-first pre-order traversal. A
1 efrain 16406
    node is followed by its last child or, if it has none, its
16407
    previous sibling or the previous sibling of the first parent
16408
    node that has one.
16409
    */
16410
    prev(enter = true) { return this.move(-1, enter); }
16411
    /**
16412
    Move the cursor to the innermost node that covers `pos`. If
16413
    `side` is -1, it will enter nodes that end at `pos`. If it is 1,
16414
    it will enter nodes that start at `pos`.
16415
    */
16416
    moveTo(pos, side = 0) {
16417
        // Move up to a node that actually holds the position, if possible
16418
        while (this.from == this.to ||
16419
            (side < 1 ? this.from >= pos : this.from > pos) ||
16420
            (side > -1 ? this.to <= pos : this.to < pos))
16421
            if (!this.parent())
16422
                break;
16423
        // Then scan down into child nodes as far as possible
16424
        while (this.enterChild(1, pos, side)) { }
16425
        return this;
16426
    }
16427
    /**
16428
    Get a [syntax node](#common.SyntaxNode) at the cursor's current
16429
    position.
16430
    */
16431
    get node() {
16432
        if (!this.buffer)
16433
            return this._tree;
16434
        let cache = this.bufferNode, result = null, depth = 0;
16435
        if (cache && cache.context == this.buffer) {
16436
            scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
16437
                for (let c = cache; c; c = c._parent)
16438
                    if (c.index == index) {
16439
                        if (index == this.index)
16440
                            return c;
16441
                        result = c;
16442
                        depth = d + 1;
16443
                        break scan;
16444
                    }
16445
                index = this.stack[--d];
16446
            }
16447
        }
16448
        for (let i = depth; i < this.stack.length; i++)
16449
            result = new BufferNode(this.buffer, result, this.stack[i]);
16450
        return this.bufferNode = new BufferNode(this.buffer, result, this.index);
16451
    }
16452
    /**
16453
    Get the [tree](#common.Tree) that represents the current node, if
16454
    any. Will return null when the node is in a [tree
16455
    buffer](#common.TreeBuffer).
16456
    */
16457
    get tree() {
16458
        return this.buffer ? null : this._tree._tree;
16459
    }
16460
    /**
16461
    Iterate over the current node and all its descendants, calling
16462
    `enter` when entering a node and `leave`, if given, when leaving
16463
    one. When `enter` returns `false`, any children of that node are
16464
    skipped, and `leave` isn't called for it.
16465
    */
16466
    iterate(enter, leave) {
16467
        for (let depth = 0;;) {
16468
            let mustLeave = false;
16469
            if (this.type.isAnonymous || enter(this) !== false) {
16470
                if (this.firstChild()) {
16471
                    depth++;
16472
                    continue;
16473
                }
16474
                if (!this.type.isAnonymous)
16475
                    mustLeave = true;
16476
            }
16477
            for (;;) {
16478
                if (mustLeave && leave)
16479
                    leave(this);
16480
                mustLeave = this.type.isAnonymous;
1441 ariadna 16481
                if (!depth)
16482
                    return;
1 efrain 16483
                if (this.nextSibling())
16484
                    break;
16485
                this.parent();
16486
                depth--;
16487
                mustLeave = true;
16488
            }
16489
        }
16490
    }
16491
    /**
16492
    Test whether the current node matches a given context—a sequence
16493
    of direct parent node names. Empty strings in the context array
16494
    are treated as wildcards.
16495
    */
16496
    matchContext(context) {
16497
        if (!this.buffer)
1441 ariadna 16498
            return matchNodeContext(this.node.parent, context);
1 efrain 16499
        let { buffer } = this.buffer, { types } = buffer.set;
16500
        for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
16501
            if (d < 0)
1441 ariadna 16502
                return matchNodeContext(this._tree, context, i);
1 efrain 16503
            let type = types[buffer.buffer[this.stack[d]]];
16504
            if (!type.isAnonymous) {
16505
                if (context[i] && context[i] != type.name)
16506
                    return false;
16507
                i--;
16508
            }
16509
        }
16510
        return true;
16511
    }
16512
}
16513
function hasChild(tree) {
16514
    return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
16515
}
16516
function buildTree(data) {
16517
    var _a;
16518
    let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
16519
    let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
16520
    let types = nodeSet.types;
16521
    let contextHash = 0, lookAhead = 0;
16522
    function takeNode(parentStart, minPos, children, positions, inRepeat, depth) {
16523
        let { id, start, end, size } = cursor;
1441 ariadna 16524
        let lookAheadAtStart = lookAhead, contextAtStart = contextHash;
1 efrain 16525
        while (size < 0) {
16526
            cursor.next();
16527
            if (size == -1 /* SpecialRecord.Reuse */) {
16528
                let node = reused[id];
16529
                children.push(node);
16530
                positions.push(start - parentStart);
16531
                return;
16532
            }
16533
            else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change
16534
                contextHash = id;
16535
                return;
16536
            }
16537
            else if (size == -4 /* SpecialRecord.LookAhead */) {
16538
                lookAhead = id;
16539
                return;
16540
            }
16541
            else {
16542
                throw new RangeError(`Unrecognized record size: ${size}`);
16543
            }
16544
        }
16545
        let type = types[id], node, buffer;
16546
        let startPos = start - parentStart;
16547
        if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
16548
            // Small enough for a buffer, and no reused nodes inside
16549
            let data = new Uint16Array(buffer.size - buffer.skip);
16550
            let endPos = cursor.pos - buffer.size, index = data.length;
16551
            while (cursor.pos > endPos)
16552
                index = copyToBuffer(buffer.start, data, index);
16553
            node = new TreeBuffer(data, end - buffer.start, nodeSet);
16554
            startPos = buffer.start - parentStart;
16555
        }
16556
        else { // Make it a node
16557
            let endPos = cursor.pos - size;
16558
            cursor.next();
16559
            let localChildren = [], localPositions = [];
16560
            let localInRepeat = id >= minRepeatType ? id : -1;
16561
            let lastGroup = 0, lastEnd = end;
16562
            while (cursor.pos > endPos) {
16563
                if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
16564
                    if (cursor.end <= lastEnd - maxBufferLength) {
1441 ariadna 16565
                        makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
1 efrain 16566
                        lastGroup = localChildren.length;
16567
                        lastEnd = cursor.end;
16568
                    }
16569
                    cursor.next();
16570
                }
16571
                else if (depth > 2500 /* CutOff.Depth */) {
16572
                    takeFlatNode(start, endPos, localChildren, localPositions);
16573
                }
16574
                else {
16575
                    takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
16576
                }
16577
            }
16578
            if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
1441 ariadna 16579
                makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart);
1 efrain 16580
            localChildren.reverse();
16581
            localPositions.reverse();
16582
            if (localInRepeat > -1 && lastGroup > 0) {
1441 ariadna 16583
                let make = makeBalanced(type, contextAtStart);
1 efrain 16584
                node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
16585
            }
16586
            else {
1441 ariadna 16587
                node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart);
1 efrain 16588
            }
16589
        }
16590
        children.push(node);
16591
        positions.push(startPos);
16592
    }
16593
    function takeFlatNode(parentStart, minPos, children, positions) {
16594
        let nodes = []; // Temporary, inverted array of leaf nodes found, with absolute positions
16595
        let nodeCount = 0, stopAt = -1;
16596
        while (cursor.pos > minPos) {
16597
            let { id, start, end, size } = cursor;
16598
            if (size > 4) { // Not a leaf
16599
                cursor.next();
16600
            }
16601
            else if (stopAt > -1 && start < stopAt) {
16602
                break;
16603
            }
16604
            else {
16605
                if (stopAt < 0)
16606
                    stopAt = end - maxBufferLength;
16607
                nodes.push(id, start, end);
16608
                nodeCount++;
16609
                cursor.next();
16610
            }
16611
        }
16612
        if (nodeCount) {
16613
            let buffer = new Uint16Array(nodeCount * 4);
16614
            let start = nodes[nodes.length - 2];
16615
            for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
16616
                buffer[j++] = nodes[i];
16617
                buffer[j++] = nodes[i + 1] - start;
16618
                buffer[j++] = nodes[i + 2] - start;
16619
                buffer[j++] = j;
16620
            }
16621
            children.push(new TreeBuffer(buffer, nodes[2] - start, nodeSet));
16622
            positions.push(start - parentStart);
16623
        }
16624
    }
1441 ariadna 16625
    function makeBalanced(type, contextHash) {
1 efrain 16626
        return (children, positions, length) => {
16627
            let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
16628
            if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
16629
                if (!lastI && last.type == type && last.length == length)
16630
                    return last;
16631
                if (lookAheadProp = last.prop(NodeProp.lookAhead))
16632
                    lookAhead = positions[lastI] + last.length + lookAheadProp;
16633
            }
1441 ariadna 16634
            return makeTree(type, children, positions, length, lookAhead, contextHash);
1 efrain 16635
        };
16636
    }
1441 ariadna 16637
    function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead, contextHash) {
1 efrain 16638
        let localChildren = [], localPositions = [];
16639
        while (children.length > i) {
16640
            localChildren.push(children.pop());
16641
            localPositions.push(positions.pop() + base - from);
16642
        }
1441 ariadna 16643
        children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to, contextHash));
1 efrain 16644
        positions.push(from - base);
16645
    }
1441 ariadna 16646
    function makeTree(type, children, positions, length, lookAhead, contextHash, props) {
1 efrain 16647
        if (contextHash) {
16648
            let pair = [NodeProp.contextHash, contextHash];
16649
            props = props ? [pair].concat(props) : [pair];
16650
        }
16651
        if (lookAhead > 25) {
16652
            let pair = [NodeProp.lookAhead, lookAhead];
16653
            props = props ? [pair].concat(props) : [pair];
16654
        }
16655
        return new Tree(type, children, positions, length, props);
16656
    }
16657
    function findBufferSize(maxSize, inRepeat) {
16658
        // Scan through the buffer to find previous siblings that fit
16659
        // together in a TreeBuffer, and don't contain any reused nodes
16660
        // (which can't be stored in a buffer).
16661
        // If `inRepeat` is > -1, ignore node boundaries of that type for
16662
        // nesting, but make sure the end falls either at the start
16663
        // (`maxSize`) or before such a node.
16664
        let fork = cursor.fork();
16665
        let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
16666
        let result = { size: 0, start: 0, skip: 0 };
16667
        scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
16668
            let nodeSize = fork.size;
16669
            // Pretend nested repeat nodes of the same type don't exist
16670
            if (fork.id == inRepeat && nodeSize >= 0) {
16671
                // Except that we store the current state as a valid return
16672
                // value.
16673
                result.size = size;
16674
                result.start = start;
16675
                result.skip = skip;
16676
                skip += 4;
16677
                size += 4;
16678
                fork.next();
16679
                continue;
16680
            }
16681
            let startPos = fork.pos - nodeSize;
16682
            if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
16683
                break;
16684
            let localSkipped = fork.id >= minRepeatType ? 4 : 0;
16685
            let nodeStart = fork.start;
16686
            fork.next();
16687
            while (fork.pos > startPos) {
16688
                if (fork.size < 0) {
16689
                    if (fork.size == -3 /* SpecialRecord.ContextChange */)
16690
                        localSkipped += 4;
16691
                    else
16692
                        break scan;
16693
                }
16694
                else if (fork.id >= minRepeatType) {
16695
                    localSkipped += 4;
16696
                }
16697
                fork.next();
16698
            }
16699
            start = nodeStart;
16700
            size += nodeSize;
16701
            skip += localSkipped;
16702
        }
16703
        if (inRepeat < 0 || size == maxSize) {
16704
            result.size = size;
16705
            result.start = start;
16706
            result.skip = skip;
16707
        }
16708
        return result.size > 4 ? result : undefined;
16709
    }
16710
    function copyToBuffer(bufferStart, buffer, index) {
16711
        let { id, start, end, size } = cursor;
16712
        cursor.next();
16713
        if (size >= 0 && id < minRepeatType) {
16714
            let startIndex = index;
16715
            if (size > 4) {
16716
                let endPos = cursor.pos - (size - 4);
16717
                while (cursor.pos > endPos)
16718
                    index = copyToBuffer(bufferStart, buffer, index);
16719
            }
16720
            buffer[--index] = startIndex;
16721
            buffer[--index] = end - bufferStart;
16722
            buffer[--index] = start - bufferStart;
16723
            buffer[--index] = id;
16724
        }
16725
        else if (size == -3 /* SpecialRecord.ContextChange */) {
16726
            contextHash = id;
16727
        }
16728
        else if (size == -4 /* SpecialRecord.LookAhead */) {
16729
            lookAhead = id;
16730
        }
16731
        return index;
16732
    }
16733
    let children = [], positions = [];
16734
    while (cursor.pos > 0)
16735
        takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
16736
    let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
16737
    return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
16738
}
16739
const nodeSizeCache = new WeakMap;
16740
function nodeSize(balanceType, node) {
16741
    if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
16742
        return 1;
16743
    let size = nodeSizeCache.get(node);
16744
    if (size == null) {
16745
        size = 1;
16746
        for (let child of node.children) {
16747
            if (child.type != balanceType || !(child instanceof Tree)) {
16748
                size = 1;
16749
                break;
16750
            }
16751
            size += nodeSize(balanceType, child);
16752
        }
16753
        nodeSizeCache.set(node, size);
16754
    }
16755
    return size;
16756
}
16757
function balanceRange(
16758
// The type the balanced tree's inner nodes.
16759
balanceType,
16760
// The direct children and their positions
16761
children, positions,
16762
// The index range in children/positions to use
16763
from, to,
16764
// The start position of the nodes, relative to their parent.
16765
start,
16766
// Length of the outer node
16767
length,
16768
// Function to build the top node of the balanced tree
16769
mkTop,
16770
// Function to build internal nodes for the balanced tree
16771
mkTree) {
16772
    let total = 0;
16773
    for (let i = from; i < to; i++)
16774
        total += nodeSize(balanceType, children[i]);
16775
    let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);
16776
    let localChildren = [], localPositions = [];
16777
    function divide(children, positions, from, to, offset) {
16778
        for (let i = from; i < to;) {
16779
            let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
16780
            i++;
16781
            for (; i < to; i++) {
16782
                let nextSize = nodeSize(balanceType, children[i]);
16783
                if (groupSize + nextSize >= maxChild)
16784
                    break;
16785
                groupSize += nextSize;
16786
            }
16787
            if (i == groupFrom + 1) {
16788
                if (groupSize > maxChild) {
16789
                    let only = children[groupFrom]; // Only trees can have a size > 1
16790
                    divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
16791
                    continue;
16792
                }
16793
                localChildren.push(children[groupFrom]);
16794
            }
16795
            else {
16796
                let length = positions[i - 1] + children[i - 1].length - groupStart;
16797
                localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
16798
            }
16799
            localPositions.push(groupStart + offset - start);
16800
        }
16801
    }
16802
    divide(children, positions, from, to, 0);
16803
    return (mkTop || mkTree)(localChildren, localPositions, length);
16804
}
16805
/**
16806
Provides a way to associate values with pieces of trees. As long
16807
as that part of the tree is reused, the associated values can be
16808
retrieved from an updated tree.
16809
*/
16810
class NodeWeakMap {
16811
    constructor() {
16812
        this.map = new WeakMap();
16813
    }
16814
    setBuffer(buffer, index, value) {
16815
        let inner = this.map.get(buffer);
16816
        if (!inner)
16817
            this.map.set(buffer, inner = new Map);
16818
        inner.set(index, value);
16819
    }
16820
    getBuffer(buffer, index) {
16821
        let inner = this.map.get(buffer);
16822
        return inner && inner.get(index);
16823
    }
16824
    /**
16825
    Set the value for this syntax node.
16826
    */
16827
    set(node, value) {
16828
        if (node instanceof BufferNode)
16829
            this.setBuffer(node.context.buffer, node.index, value);
16830
        else if (node instanceof TreeNode)
16831
            this.map.set(node.tree, value);
16832
    }
16833
    /**
16834
    Retrieve value for this syntax node, if it exists in the map.
16835
    */
16836
    get(node) {
16837
        return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index)
16838
            : node instanceof TreeNode ? this.map.get(node.tree) : undefined;
16839
    }
16840
    /**
16841
    Set the value for the node that a cursor currently points to.
16842
    */
16843
    cursorSet(cursor, value) {
16844
        if (cursor.buffer)
16845
            this.setBuffer(cursor.buffer.buffer, cursor.index, value);
16846
        else
16847
            this.map.set(cursor.tree, value);
16848
    }
16849
    /**
16850
    Retrieve the value for the node that a cursor currently points
16851
    to.
16852
    */
16853
    cursorGet(cursor) {
16854
        return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
16855
    }
16856
}
16857
 
16858
/**
16859
Tree fragments are used during [incremental
16860
parsing](#common.Parser.startParse) to track parts of old trees
16861
that can be reused in a new parse. An array of fragments is used
16862
to track regions of an old tree whose nodes might be reused in new
16863
parses. Use the static
16864
[`applyChanges`](#common.TreeFragment^applyChanges) method to
16865
update fragments for document changes.
16866
*/
16867
class TreeFragment {
16868
    /**
16869
    Construct a tree fragment. You'll usually want to use
16870
    [`addTree`](#common.TreeFragment^addTree) and
16871
    [`applyChanges`](#common.TreeFragment^applyChanges) instead of
16872
    calling this directly.
16873
    */
16874
    constructor(
16875
    /**
16876
    The start of the unchanged range pointed to by this fragment.
16877
    This refers to an offset in the _updated_ document (as opposed
16878
    to the original tree).
16879
    */
16880
    from,
16881
    /**
16882
    The end of the unchanged range.
16883
    */
16884
    to,
16885
    /**
16886
    The tree that this fragment is based on.
16887
    */
16888
    tree,
16889
    /**
16890
    The offset between the fragment's tree and the document that
16891
    this fragment can be used against. Add this when going from
16892
    document to tree positions, subtract it to go from tree to
16893
    document positions.
16894
    */
16895
    offset, openStart = false, openEnd = false) {
16896
        this.from = from;
16897
        this.to = to;
16898
        this.tree = tree;
16899
        this.offset = offset;
16900
        this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);
16901
    }
16902
    /**
16903
    Whether the start of the fragment represents the start of a
16904
    parse, or the end of a change. (In the second case, it may not
16905
    be safe to reuse some nodes at the start, depending on the
16906
    parsing algorithm.)
16907
    */
16908
    get openStart() { return (this.open & 1 /* Open.Start */) > 0; }
16909
    /**
16910
    Whether the end of the fragment represents the end of a
16911
    full-document parse, or the start of a change.
16912
    */
16913
    get openEnd() { return (this.open & 2 /* Open.End */) > 0; }
16914
    /**
16915
    Create a set of fragments from a freshly parsed tree, or update
16916
    an existing set of fragments by replacing the ones that overlap
16917
    with a tree with content from the new tree. When `partial` is
16918
    true, the parse is treated as incomplete, and the resulting
16919
    fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
16920
    true.
16921
    */
16922
    static addTree(tree, fragments = [], partial = false) {
16923
        let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
16924
        for (let f of fragments)
16925
            if (f.to > tree.length)
16926
                result.push(f);
16927
        return result;
16928
    }
16929
    /**
16930
    Apply a set of edits to an array of fragments, removing or
16931
    splitting fragments as necessary to remove edited ranges, and
16932
    adjusting offsets for fragments that moved.
16933
    */
16934
    static applyChanges(fragments, changes, minGap = 128) {
16935
        if (!changes.length)
16936
            return fragments;
16937
        let result = [];
16938
        let fI = 1, nextF = fragments.length ? fragments[0] : null;
16939
        for (let cI = 0, pos = 0, off = 0;; cI++) {
16940
            let nextC = cI < changes.length ? changes[cI] : null;
16941
            let nextPos = nextC ? nextC.fromA : 1e9;
16942
            if (nextPos - pos >= minGap)
16943
                while (nextF && nextF.from < nextPos) {
16944
                    let cut = nextF;
16945
                    if (pos >= cut.from || nextPos <= cut.to || off) {
16946
                        let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
16947
                        cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
16948
                    }
16949
                    if (cut)
16950
                        result.push(cut);
16951
                    if (nextF.to > nextPos)
16952
                        break;
16953
                    nextF = fI < fragments.length ? fragments[fI++] : null;
16954
                }
16955
            if (!nextC)
16956
                break;
16957
            pos = nextC.toA;
16958
            off = nextC.toA - nextC.toB;
16959
        }
16960
        return result;
16961
    }
16962
}
16963
/**
16964
A superclass that parsers should extend.
16965
*/
16966
class Parser {
16967
    /**
16968
    Start a parse, returning a [partial parse](#common.PartialParse)
16969
    object. [`fragments`](#common.TreeFragment) can be passed in to
16970
    make the parse incremental.
16971
 
16972
    By default, the entire input is parsed. You can pass `ranges`,
16973
    which should be a sorted array of non-empty, non-overlapping
16974
    ranges, to parse only those ranges. The tree returned in that
16975
    case will start at `ranges[0].from`.
16976
    */
16977
    startParse(input, fragments, ranges) {
16978
        if (typeof input == "string")
16979
            input = new StringInput(input);
16980
        ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
16981
        return this.createParse(input, fragments || [], ranges);
16982
    }
16983
    /**
16984
    Run a full parse, returning the resulting tree.
16985
    */
16986
    parse(input, fragments, ranges) {
16987
        let parse = this.startParse(input, fragments, ranges);
16988
        for (;;) {
16989
            let done = parse.advance();
16990
            if (done)
16991
                return done;
16992
        }
16993
    }
16994
}
16995
class StringInput {
16996
    constructor(string) {
16997
        this.string = string;
16998
    }
16999
    get length() { return this.string.length; }
17000
    chunk(from) { return this.string.slice(from); }
17001
    get lineChunks() { return false; }
17002
    read(from, to) { return this.string.slice(from, to); }
17003
}
17004
 
17005
/**
17006
Create a parse wrapper that, after the inner parse completes,
17007
scans its tree for mixed language regions with the `nest`
17008
function, runs the resulting [inner parses](#common.NestedParse),
17009
and then [mounts](#common.NodeProp^mounted) their results onto the
17010
tree.
17011
*/
17012
function parseMixed(nest) {
17013
    return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
17014
}
17015
class InnerParse {
17016
    constructor(parser, parse, overlay, target, from) {
17017
        this.parser = parser;
17018
        this.parse = parse;
17019
        this.overlay = overlay;
17020
        this.target = target;
17021
        this.from = from;
17022
    }
17023
}
17024
function checkRanges(ranges) {
17025
    if (!ranges.length || ranges.some(r => r.from >= r.to))
17026
        throw new RangeError("Invalid inner parse ranges given: " + JSON.stringify(ranges));
17027
}
17028
class ActiveOverlay {
17029
    constructor(parser, predicate, mounts, index, start, target, prev) {
17030
        this.parser = parser;
17031
        this.predicate = predicate;
17032
        this.mounts = mounts;
17033
        this.index = index;
17034
        this.start = start;
17035
        this.target = target;
17036
        this.prev = prev;
17037
        this.depth = 0;
17038
        this.ranges = [];
17039
    }
17040
}
17041
const stoppedInner = new NodeProp({ perNode: true });
17042
class MixedParse {
17043
    constructor(base, nest, input, fragments, ranges) {
17044
        this.nest = nest;
17045
        this.input = input;
17046
        this.fragments = fragments;
17047
        this.ranges = ranges;
17048
        this.inner = [];
17049
        this.innerDone = 0;
17050
        this.baseTree = null;
17051
        this.stoppedAt = null;
17052
        this.baseParse = base;
17053
    }
17054
    advance() {
17055
        if (this.baseParse) {
17056
            let done = this.baseParse.advance();
17057
            if (!done)
17058
                return null;
17059
            this.baseParse = null;
17060
            this.baseTree = done;
17061
            this.startInner();
17062
            if (this.stoppedAt != null)
17063
                for (let inner of this.inner)
17064
                    inner.parse.stopAt(this.stoppedAt);
17065
        }
17066
        if (this.innerDone == this.inner.length) {
17067
            let result = this.baseTree;
17068
            if (this.stoppedAt != null)
17069
                result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
17070
            return result;
17071
        }
17072
        let inner = this.inner[this.innerDone], done = inner.parse.advance();
17073
        if (done) {
17074
            this.innerDone++;
17075
            // This is a somewhat dodgy but super helpful hack where we
17076
            // patch up nodes created by the inner parse (and thus
17077
            // presumably not aliased anywhere else) to hold the information
17078
            // about the inner parse.
17079
            let props = Object.assign(Object.create(null), inner.target.props);
17080
            props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
17081
            inner.target.props = props;
17082
        }
17083
        return null;
17084
    }
17085
    get parsedPos() {
17086
        if (this.baseParse)
17087
            return 0;
17088
        let pos = this.input.length;
17089
        for (let i = this.innerDone; i < this.inner.length; i++) {
17090
            if (this.inner[i].from < pos)
17091
                pos = Math.min(pos, this.inner[i].parse.parsedPos);
17092
        }
17093
        return pos;
17094
    }
17095
    stopAt(pos) {
17096
        this.stoppedAt = pos;
17097
        if (this.baseParse)
17098
            this.baseParse.stopAt(pos);
17099
        else
17100
            for (let i = this.innerDone; i < this.inner.length; i++)
17101
                this.inner[i].parse.stopAt(pos);
17102
    }
17103
    startInner() {
17104
        let fragmentCursor = new FragmentCursor$1(this.fragments);
17105
        let overlay = null;
17106
        let covered = null;
17107
        let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
17108
        scan: for (let nest, isCovered;;) {
17109
            let enter = true, range;
17110
            if (this.stoppedAt != null && cursor.from >= this.stoppedAt) {
17111
                enter = false;
17112
            }
17113
            else if (fragmentCursor.hasNode(cursor)) {
17114
                if (overlay) {
17115
                    let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
17116
                    if (match)
17117
                        for (let r of match.mount.overlay) {
17118
                            let from = r.from + match.pos, to = r.to + match.pos;
17119
                            if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r => r.from < to && r.to > from))
17120
                                overlay.ranges.push({ from, to });
17121
                        }
17122
                }
17123
                enter = false;
17124
            }
17125
            else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) {
17126
                enter = isCovered != 2 /* Cover.Full */;
17127
            }
17128
            else if (!cursor.type.isAnonymous && (nest = this.nest(cursor, this.input)) &&
17129
                (cursor.from < cursor.to || !nest.overlay)) {
17130
                if (!cursor.tree)
17131
                    materialize(cursor);
17132
                let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
17133
                if (typeof nest.overlay == "function") {
17134
                    overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);
17135
                }
17136
                else {
17137
                    let ranges = punchRanges(this.ranges, nest.overlay ||
17138
                        (cursor.from < cursor.to ? [new Range(cursor.from, cursor.to)] : []));
17139
                    if (ranges.length)
17140
                        checkRanges(ranges);
17141
                    if (ranges.length || !nest.overlay)
17142
                        this.inner.push(new InnerParse(nest.parser, ranges.length ? nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges)
17143
                            : 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));
17144
                    if (!nest.overlay)
17145
                        enter = false;
17146
                    else if (ranges.length)
17147
                        covered = { ranges, depth: 0, prev: covered };
17148
                }
17149
            }
17150
            else if (overlay && (range = overlay.predicate(cursor))) {
17151
                if (range === true)
17152
                    range = new Range(cursor.from, cursor.to);
1441 ariadna 17153
                if (range.from < range.to) {
17154
                    let last = overlay.ranges.length - 1;
17155
                    if (last >= 0 && overlay.ranges[last].to == range.from)
17156
                        overlay.ranges[last] = { from: overlay.ranges[last].from, to: range.to };
17157
                    else
17158
                        overlay.ranges.push(range);
17159
                }
1 efrain 17160
            }
17161
            if (enter && cursor.firstChild()) {
17162
                if (overlay)
17163
                    overlay.depth++;
17164
                if (covered)
17165
                    covered.depth++;
17166
            }
17167
            else {
17168
                for (;;) {
17169
                    if (cursor.nextSibling())
17170
                        break;
17171
                    if (!cursor.parent())
17172
                        break scan;
17173
                    if (overlay && !--overlay.depth) {
17174
                        let ranges = punchRanges(this.ranges, overlay.ranges);
17175
                        if (ranges.length) {
17176
                            checkRanges(ranges);
17177
                            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));
17178
                        }
17179
                        overlay = overlay.prev;
17180
                    }
17181
                    if (covered && !--covered.depth)
17182
                        covered = covered.prev;
17183
                }
17184
            }
17185
        }
17186
    }
17187
}
17188
function checkCover(covered, from, to) {
17189
    for (let range of covered) {
17190
        if (range.from >= to)
17191
            break;
17192
        if (range.to > from)
17193
            return range.from <= from && range.to >= to ? 2 /* Cover.Full */ : 1 /* Cover.Partial */;
17194
    }
17195
    return 0 /* Cover.None */;
17196
}
17197
// Take a piece of buffer and convert it into a stand-alone
17198
// TreeBuffer.
17199
function sliceBuf(buf, startI, endI, nodes, positions, off) {
17200
    if (startI < endI) {
17201
        let from = buf.buffer[startI + 1];
17202
        nodes.push(buf.slice(startI, endI, from));
17203
        positions.push(from - off);
17204
    }
17205
}
17206
// This function takes a node that's in a buffer, and converts it, and
17207
// its parent buffer nodes, into a Tree. This is again acting on the
17208
// assumption that the trees and buffers have been constructed by the
17209
// parse that was ran via the mix parser, and thus aren't shared with
17210
// any other code, making violations of the immutability safe.
17211
function materialize(cursor) {
17212
    let { node } = cursor, stack = [];
17213
    let buffer = node.context.buffer;
17214
    // Scan up to the nearest tree
17215
    do {
17216
        stack.push(cursor.index);
17217
        cursor.parent();
17218
    } while (!cursor.tree);
17219
    // Find the index of the buffer in that tree
17220
    let base = cursor.tree, i = base.children.indexOf(buffer);
17221
    let buf = base.children[i], b = buf.buffer, newStack = [i];
17222
    // Split a level in the buffer, putting the nodes before and after
17223
    // the child that contains `node` into new buffers.
17224
    function split(startI, endI, type, innerOffset, length, stackPos) {
17225
        let targetI = stack[stackPos];
17226
        let children = [], positions = [];
17227
        sliceBuf(buf, startI, targetI, children, positions, innerOffset);
17228
        let from = b[targetI + 1], to = b[targetI + 2];
17229
        newStack.push(children.length);
17230
        let child = stackPos
17231
            ? split(targetI + 4, b[targetI + 3], buf.set.types[b[targetI]], from, to - from, stackPos - 1)
17232
            : node.toTree();
17233
        children.push(child);
17234
        positions.push(from - innerOffset);
17235
        sliceBuf(buf, b[targetI + 3], endI, children, positions, innerOffset);
17236
        return new Tree(type, children, positions, length);
17237
    }
17238
    base.children[i] = split(0, b.length, NodeType.none, 0, buf.length, stack.length - 1);
17239
    // Move the cursor back to the target node
17240
    for (let index of newStack) {
17241
        let tree = cursor.tree.children[index], pos = cursor.tree.positions[index];
17242
        cursor.yield(new TreeNode(tree, pos + cursor.from, index, cursor._tree));
17243
    }
17244
}
17245
class StructureCursor {
17246
    constructor(root, offset) {
17247
        this.offset = offset;
17248
        this.done = false;
17249
        this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
17250
    }
17251
    // Move to the first node (in pre-order) that starts at or after `pos`.
17252
    moveTo(pos) {
17253
        let { cursor } = this, p = pos - this.offset;
17254
        while (!this.done && cursor.from < p) {
17255
            if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;
17256
            else if (!cursor.next(false))
17257
                this.done = true;
17258
        }
17259
    }
17260
    hasNode(cursor) {
17261
        this.moveTo(cursor.from);
17262
        if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) {
17263
            for (let tree = this.cursor.tree;;) {
17264
                if (tree == cursor.tree)
17265
                    return true;
17266
                if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree)
17267
                    tree = tree.children[0];
17268
                else
17269
                    break;
17270
            }
17271
        }
17272
        return false;
17273
    }
17274
}
17275
let FragmentCursor$1 = class FragmentCursor {
17276
    constructor(fragments) {
17277
        var _a;
17278
        this.fragments = fragments;
17279
        this.curTo = 0;
17280
        this.fragI = 0;
17281
        if (fragments.length) {
17282
            let first = this.curFrag = fragments[0];
17283
            this.curTo = (_a = first.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : first.to;
17284
            this.inner = new StructureCursor(first.tree, -first.offset);
17285
        }
17286
        else {
17287
            this.curFrag = this.inner = null;
17288
        }
17289
    }
17290
    hasNode(node) {
17291
        while (this.curFrag && node.from >= this.curTo)
17292
            this.nextFrag();
17293
        return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
17294
    }
17295
    nextFrag() {
17296
        var _a;
17297
        this.fragI++;
17298
        if (this.fragI == this.fragments.length) {
17299
            this.curFrag = this.inner = null;
17300
        }
17301
        else {
17302
            let frag = this.curFrag = this.fragments[this.fragI];
17303
            this.curTo = (_a = frag.tree.prop(stoppedInner)) !== null && _a !== void 0 ? _a : frag.to;
17304
            this.inner = new StructureCursor(frag.tree, -frag.offset);
17305
        }
17306
    }
17307
    findMounts(pos, parser) {
17308
        var _a;
17309
        let result = [];
17310
        if (this.inner) {
17311
            this.inner.cursor.moveTo(pos, 1);
17312
            for (let pos = this.inner.cursor.node; pos; pos = pos.parent) {
17313
                let mount = (_a = pos.tree) === null || _a === void 0 ? void 0 : _a.prop(NodeProp.mounted);
17314
                if (mount && mount.parser == parser) {
17315
                    for (let i = this.fragI; i < this.fragments.length; i++) {
17316
                        let frag = this.fragments[i];
17317
                        if (frag.from >= pos.to)
17318
                            break;
17319
                        if (frag.tree == this.curFrag.tree)
17320
                            result.push({
17321
                                frag,
17322
                                pos: pos.from - frag.offset,
17323
                                mount
17324
                            });
17325
                    }
17326
                }
17327
            }
17328
        }
17329
        return result;
17330
    }
17331
};
17332
function punchRanges(outer, ranges) {
17333
    let copy = null, current = ranges;
17334
    for (let i = 1, j = 0; i < outer.length; i++) {
17335
        let gapFrom = outer[i - 1].to, gapTo = outer[i].from;
17336
        for (; j < current.length; j++) {
17337
            let r = current[j];
17338
            if (r.from >= gapTo)
17339
                break;
17340
            if (r.to <= gapFrom)
17341
                continue;
17342
            if (!copy)
17343
                current = copy = ranges.slice();
17344
            if (r.from < gapFrom) {
17345
                copy[j] = new Range(r.from, gapFrom);
17346
                if (r.to > gapTo)
17347
                    copy.splice(j + 1, 0, new Range(gapTo, r.to));
17348
            }
17349
            else if (r.to > gapTo) {
17350
                copy[j--] = new Range(gapTo, r.to);
17351
            }
17352
            else {
17353
                copy.splice(j--, 1);
17354
            }
17355
        }
17356
    }
17357
    return current;
17358
}
17359
function findCoverChanges(a, b, from, to) {
17360
    let iA = 0, iB = 0, inA = false, inB = false, pos = -1e9;
17361
    let result = [];
17362
    for (;;) {
17363
        let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
17364
        let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
17365
        if (inA != inB) {
17366
            let start = Math.max(pos, from), end = Math.min(nextA, nextB, to);
17367
            if (start < end)
17368
                result.push(new Range(start, end));
17369
        }
17370
        pos = Math.min(nextA, nextB);
17371
        if (pos == 1e9)
17372
            break;
17373
        if (nextA == pos) {
17374
            if (!inA)
17375
                inA = true;
17376
            else {
17377
                inA = false;
17378
                iA++;
17379
            }
17380
        }
17381
        if (nextB == pos) {
17382
            if (!inB)
17383
                inB = true;
17384
            else {
17385
                inB = false;
17386
                iB++;
17387
            }
17388
        }
17389
    }
17390
    return result;
17391
}
17392
// Given a number of fragments for the outer tree, and a set of ranges
17393
// to parse, find fragments for inner trees mounted around those
17394
// ranges, if any.
17395
function enterFragments(mounts, ranges) {
17396
    let result = [];
17397
    for (let { pos, mount, frag } of mounts) {
17398
        let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0), endPos = startPos + mount.tree.length;
17399
        let from = Math.max(frag.from, startPos), to = Math.min(frag.to, endPos);
17400
        if (mount.overlay) {
17401
            let overlay = mount.overlay.map(r => new Range(r.from + pos, r.to + pos));
17402
            let changes = findCoverChanges(ranges, overlay, from, to);
17403
            for (let i = 0, pos = from;; i++) {
17404
                let last = i == changes.length, end = last ? to : changes[i].from;
17405
                if (end > pos)
17406
                    result.push(new TreeFragment(pos, end, mount.tree, -startPos, frag.from >= pos || frag.openStart, frag.to <= end || frag.openEnd));
17407
                if (last)
17408
                    break;
17409
                pos = changes[i].to;
17410
            }
17411
        }
17412
        else {
17413
            result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));
17414
        }
17415
    }
17416
    return result;
17417
}
17418
 
17419
let nextTagID = 0;
17420
/**
17421
Highlighting tags are markers that denote a highlighting category.
17422
They are [associated](#highlight.styleTags) with parts of a syntax
17423
tree by a language mode, and then mapped to an actual CSS style by
17424
a [highlighter](#highlight.Highlighter).
17425
 
17426
Because syntax tree node types and highlight styles have to be
17427
able to talk the same language, CodeMirror uses a mostly _closed_
17428
[vocabulary](#highlight.tags) of syntax tags (as opposed to
17429
traditional open string-based systems, which make it hard for
17430
highlighting themes to cover all the tokens produced by the
17431
various languages).
17432
 
17433
It _is_ possible to [define](#highlight.Tag^define) your own
17434
highlighting tags for system-internal use (where you control both
17435
the language package and the highlighter), but such tags will not
17436
be picked up by regular highlighters (though you can derive them
17437
from standard tags to allow highlighters to fall back to those).
17438
*/
17439
class Tag {
17440
    /**
17441
    @internal
17442
    */
17443
    constructor(
17444
    /**
1441 ariadna 17445
    The optional name of the base tag @internal
17446
    */
17447
    name,
17448
    /**
1 efrain 17449
    The set of this tag and all its parent tags, starting with
17450
    this one itself and sorted in order of decreasing specificity.
17451
    */
17452
    set,
17453
    /**
17454
    The base unmodified tag that this one is based on, if it's
17455
    modified @internal
17456
    */
17457
    base,
17458
    /**
17459
    The modifiers applied to this.base @internal
17460
    */
17461
    modified) {
1441 ariadna 17462
        this.name = name;
1 efrain 17463
        this.set = set;
17464
        this.base = base;
17465
        this.modified = modified;
17466
        /**
17467
        @internal
17468
        */
17469
        this.id = nextTagID++;
17470
    }
1441 ariadna 17471
    toString() {
17472
        let { name } = this;
17473
        for (let mod of this.modified)
17474
            if (mod.name)
17475
                name = `${mod.name}(${name})`;
17476
        return name;
17477
    }
17478
    static define(nameOrParent, parent) {
17479
        let name = typeof nameOrParent == "string" ? nameOrParent : "?";
17480
        if (nameOrParent instanceof Tag)
17481
            parent = nameOrParent;
1 efrain 17482
        if (parent === null || parent === void 0 ? void 0 : parent.base)
17483
            throw new Error("Can not derive from a modified tag");
1441 ariadna 17484
        let tag = new Tag(name, [], null, []);
1 efrain 17485
        tag.set.push(tag);
17486
        if (parent)
17487
            for (let t of parent.set)
17488
                tag.set.push(t);
17489
        return tag;
17490
    }
17491
    /**
17492
    Define a tag _modifier_, which is a function that, given a tag,
17493
    will return a tag that is a subtag of the original. Applying the
17494
    same modifier to a twice tag will return the same value (`m1(t1)
17495
    == m1(t1)`) and applying multiple modifiers will, regardless or
17496
    order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
17497
 
17498
    When multiple modifiers are applied to a given base tag, each
17499
    smaller set of modifiers is registered as a parent, so that for
17500
    example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
17501
    `m1(m3(t1)`, and so on.
17502
    */
1441 ariadna 17503
    static defineModifier(name) {
17504
        let mod = new Modifier(name);
1 efrain 17505
        return (tag) => {
17506
            if (tag.modified.indexOf(mod) > -1)
17507
                return tag;
17508
            return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
17509
        };
17510
    }
17511
}
17512
let nextModifierID = 0;
17513
class Modifier {
1441 ariadna 17514
    constructor(name) {
17515
        this.name = name;
1 efrain 17516
        this.instances = [];
17517
        this.id = nextModifierID++;
17518
    }
17519
    static get(base, mods) {
17520
        if (!mods.length)
17521
            return base;
17522
        let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
17523
        if (exists)
17524
            return exists;
1441 ariadna 17525
        let set = [], tag = new Tag(base.name, set, base, mods);
1 efrain 17526
        for (let m of mods)
17527
            m.instances.push(tag);
17528
        let configs = powerSet(mods);
17529
        for (let parent of base.set)
17530
            if (!parent.modified.length)
17531
                for (let config of configs)
17532
                    set.push(Modifier.get(parent, config));
17533
        return tag;
17534
    }
17535
}
17536
function sameArray(a, b) {
17537
    return a.length == b.length && a.every((x, i) => x == b[i]);
17538
}
17539
function powerSet(array) {
17540
    let sets = [[]];
17541
    for (let i = 0; i < array.length; i++) {
17542
        for (let j = 0, e = sets.length; j < e; j++) {
17543
            sets.push(sets[j].concat(array[i]));
17544
        }
17545
    }
17546
    return sets.sort((a, b) => b.length - a.length);
17547
}
17548
/**
17549
This function is used to add a set of tags to a language syntax
17550
via [`NodeSet.extend`](#common.NodeSet.extend) or
17551
[`LRParser.configure`](#lr.LRParser.configure).
17552
 
17553
The argument object maps node selectors to [highlighting
17554
tags](#highlight.Tag) or arrays of tags.
17555
 
17556
Node selectors may hold one or more (space-separated) node paths.
17557
Such a path can be a [node name](#common.NodeType.name), or
17558
multiple node names (or `*` wildcards) separated by slash
17559
characters, as in `"Block/Declaration/VariableName"`. Such a path
17560
matches the final node but only if its direct parent nodes are the
17561
other nodes mentioned. A `*` in such a path matches any parent,
17562
but only a single level—wildcards that match multiple parents
17563
aren't supported, both for efficiency reasons and because Lezer
17564
trees make it rather hard to reason about what they would match.)
17565
 
17566
A path can be ended with `/...` to indicate that the tag assigned
17567
to the node should also apply to all child nodes, even if they
17568
match their own style (by default, only the innermost style is
17569
used).
17570
 
17571
When a path ends in `!`, as in `Attribute!`, no further matching
17572
happens for the node's child nodes, and the entire node gets the
17573
given style.
17574
 
17575
In this notation, node names that contain `/`, `!`, `*`, or `...`
17576
must be quoted as JSON strings.
17577
 
17578
For example:
17579
 
17580
```javascript
17581
parser.withProps(
17582
  styleTags({
17583
    // Style Number and BigNumber nodes
17584
    "Number BigNumber": tags.number,
17585
    // Style Escape nodes whose parent is String
17586
    "String/Escape": tags.escape,
17587
    // Style anything inside Attributes nodes
17588
    "Attributes!": tags.meta,
17589
    // Add a style to all content inside Italic nodes
17590
    "Italic/...": tags.emphasis,
17591
    // Style InvalidString nodes as both `string` and `invalid`
17592
    "InvalidString": [tags.string, tags.invalid],
17593
    // Style the node named "/" as punctuation
17594
    '"/"': tags.punctuation
17595
  })
17596
)
17597
```
17598
*/
17599
function styleTags(spec) {
17600
    let byName = Object.create(null);
17601
    for (let prop in spec) {
17602
        let tags = spec[prop];
17603
        if (!Array.isArray(tags))
17604
            tags = [tags];
17605
        for (let part of prop.split(" "))
17606
            if (part) {
17607
                let pieces = [], mode = 2 /* Mode.Normal */, rest = part;
17608
                for (let pos = 0;;) {
17609
                    if (rest == "..." && pos > 0 && pos + 3 == part.length) {
17610
                        mode = 1 /* Mode.Inherit */;
17611
                        break;
17612
                    }
17613
                    let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
17614
                    if (!m)
17615
                        throw new RangeError("Invalid path: " + part);
17616
                    pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
17617
                    pos += m[0].length;
17618
                    if (pos == part.length)
17619
                        break;
17620
                    let next = part[pos++];
17621
                    if (pos == part.length && next == "!") {
17622
                        mode = 0 /* Mode.Opaque */;
17623
                        break;
17624
                    }
17625
                    if (next != "/")
17626
                        throw new RangeError("Invalid path: " + part);
17627
                    rest = part.slice(pos);
17628
                }
17629
                let last = pieces.length - 1, inner = pieces[last];
17630
                if (!inner)
17631
                    throw new RangeError("Invalid path: " + part);
17632
                let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
17633
                byName[inner] = rule.sort(byName[inner]);
17634
            }
17635
    }
17636
    return ruleNodeProp.add(byName);
17637
}
17638
const ruleNodeProp = new NodeProp();
17639
class Rule {
17640
    constructor(tags, mode, context, next) {
17641
        this.tags = tags;
17642
        this.mode = mode;
17643
        this.context = context;
17644
        this.next = next;
17645
    }
17646
    get opaque() { return this.mode == 0 /* Mode.Opaque */; }
17647
    get inherit() { return this.mode == 1 /* Mode.Inherit */; }
17648
    sort(other) {
17649
        if (!other || other.depth < this.depth) {
17650
            this.next = other;
17651
            return this;
17652
        }
17653
        other.next = this.sort(other.next);
17654
        return other;
17655
    }
17656
    get depth() { return this.context ? this.context.length : 0; }
17657
}
17658
Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
17659
/**
17660
Define a [highlighter](#highlight.Highlighter) from an array of
17661
tag/class pairs. Classes associated with more specific tags will
17662
take precedence.
17663
*/
17664
function tagHighlighter(tags, options) {
17665
    let map = Object.create(null);
17666
    for (let style of tags) {
17667
        if (!Array.isArray(style.tag))
17668
            map[style.tag.id] = style.class;
17669
        else
17670
            for (let tag of style.tag)
17671
                map[tag.id] = style.class;
17672
    }
17673
    let { scope, all = null } = options || {};
17674
    return {
17675
        style: (tags) => {
17676
            let cls = all;
17677
            for (let tag of tags) {
17678
                for (let sub of tag.set) {
17679
                    let tagClass = map[sub.id];
17680
                    if (tagClass) {
17681
                        cls = cls ? cls + " " + tagClass : tagClass;
17682
                        break;
17683
                    }
17684
                }
17685
            }
17686
            return cls;
17687
        },
17688
        scope
17689
    };
17690
}
17691
function highlightTags(highlighters, tags) {
17692
    let result = null;
17693
    for (let highlighter of highlighters) {
17694
        let value = highlighter.style(tags);
17695
        if (value)
17696
            result = result ? result + " " + value : value;
17697
    }
17698
    return result;
17699
}
17700
/**
17701
Highlight the given [tree](#common.Tree) with the given
17702
[highlighter](#highlight.Highlighter). Often, the higher-level
17703
[`highlightCode`](#highlight.highlightCode) function is easier to
17704
use.
17705
*/
17706
function highlightTree(tree, highlighter,
17707
/**
17708
Assign styling to a region of the text. Will be called, in order
17709
of position, for any ranges where more than zero classes apply.
17710
`classes` is a space separated string of CSS classes.
17711
*/
17712
putStyle,
17713
/**
17714
The start of the range to highlight.
17715
*/
17716
from = 0,
17717
/**
17718
The end of the range.
17719
*/
17720
to = tree.length) {
17721
    let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
17722
    builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
17723
    builder.flush(to);
17724
}
17725
class HighlightBuilder {
17726
    constructor(at, highlighters, span) {
17727
        this.at = at;
17728
        this.highlighters = highlighters;
17729
        this.span = span;
17730
        this.class = "";
17731
    }
17732
    startSpan(at, cls) {
17733
        if (cls != this.class) {
17734
            this.flush(at);
17735
            if (at > this.at)
17736
                this.at = at;
17737
            this.class = cls;
17738
        }
17739
    }
17740
    flush(to) {
17741
        if (to > this.at && this.class)
17742
            this.span(this.at, to, this.class);
17743
    }
17744
    highlightRange(cursor, from, to, inheritedClass, highlighters) {
17745
        let { type, from: start, to: end } = cursor;
17746
        if (start >= to || end <= from)
17747
            return;
17748
        if (type.isTop)
17749
            highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
17750
        let cls = inheritedClass;
17751
        let rule = getStyleTags(cursor) || Rule.empty;
17752
        let tagCls = highlightTags(highlighters, rule.tags);
17753
        if (tagCls) {
17754
            if (cls)
17755
                cls += " ";
17756
            cls += tagCls;
17757
            if (rule.mode == 1 /* Mode.Inherit */)
17758
                inheritedClass += (inheritedClass ? " " : "") + tagCls;
17759
        }
17760
        this.startSpan(Math.max(from, start), cls);
17761
        if (rule.opaque)
17762
            return;
17763
        let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
17764
        if (mounted && mounted.overlay) {
17765
            let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
17766
            let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
17767
            let hasChild = cursor.firstChild();
17768
            for (let i = 0, pos = start;; i++) {
17769
                let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
17770
                let nextPos = next ? next.from + start : end;
17771
                let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
17772
                if (rangeFrom < rangeTo && hasChild) {
17773
                    while (cursor.from < rangeTo) {
17774
                        this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
17775
                        this.startSpan(Math.min(rangeTo, cursor.to), cls);
17776
                        if (cursor.to >= nextPos || !cursor.nextSibling())
17777
                            break;
17778
                    }
17779
                }
17780
                if (!next || nextPos > to)
17781
                    break;
17782
                pos = next.to + start;
17783
                if (pos > from) {
17784
                    this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters);
17785
                    this.startSpan(Math.min(to, pos), cls);
17786
                }
17787
            }
17788
            if (hasChild)
17789
                cursor.parent();
17790
        }
17791
        else if (cursor.firstChild()) {
17792
            if (mounted)
17793
                inheritedClass = "";
17794
            do {
17795
                if (cursor.to <= from)
17796
                    continue;
17797
                if (cursor.from >= to)
17798
                    break;
17799
                this.highlightRange(cursor, from, to, inheritedClass, highlighters);
17800
                this.startSpan(Math.min(to, cursor.to), cls);
17801
            } while (cursor.nextSibling());
17802
            cursor.parent();
17803
        }
17804
    }
17805
}
17806
/**
17807
Match a syntax node's [highlight rules](#highlight.styleTags). If
17808
there's a match, return its set of tags, and whether it is
17809
opaque (uses a `!`) or applies to all child nodes (`/...`).
17810
*/
17811
function getStyleTags(node) {
17812
    let rule = node.type.prop(ruleNodeProp);
17813
    while (rule && rule.context && !node.matchContext(rule.context))
17814
        rule = rule.next;
17815
    return rule || null;
17816
}
17817
const t = Tag.define;
17818
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();
17819
/**
17820
The default set of highlighting [tags](#highlight.Tag).
17821
 
17822
This collection is heavily biased towards programming languages,
17823
and necessarily incomplete. A full ontology of syntactic
17824
constructs would fill a stack of books, and be impractical to
17825
write themes for. So try to make do with this set. If all else
17826
fails, [open an
17827
issue](https://github.com/codemirror/codemirror.next) to propose a
17828
new tag, or [define](#highlight.Tag^define) a local custom tag for
17829
your use case.
17830
 
17831
Note that it is not obligatory to always attach the most specific
17832
tag possible to an element—if your grammar can't easily
17833
distinguish a certain type of element (such as a local variable),
17834
it is okay to style it as its more general variant (a variable).
17835
 
17836
For tags that extend some parent tag, the documentation links to
17837
the parent.
17838
*/
17839
const tags$1 = {
17840
    /**
17841
    A comment.
17842
    */
17843
    comment,
17844
    /**
17845
    A line [comment](#highlight.tags.comment).
17846
    */
17847
    lineComment: t(comment),
17848
    /**
17849
    A block [comment](#highlight.tags.comment).
17850
    */
17851
    blockComment: t(comment),
17852
    /**
17853
    A documentation [comment](#highlight.tags.comment).
17854
    */
17855
    docComment: t(comment),
17856
    /**
17857
    Any kind of identifier.
17858
    */
17859
    name,
17860
    /**
17861
    The [name](#highlight.tags.name) of a variable.
17862
    */
17863
    variableName: t(name),
17864
    /**
17865
    A type [name](#highlight.tags.name).
17866
    */
17867
    typeName: typeName,
17868
    /**
17869
    A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
17870
    */
17871
    tagName: t(typeName),
17872
    /**
17873
    A property or field [name](#highlight.tags.name).
17874
    */
17875
    propertyName: propertyName,
17876
    /**
17877
    An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
17878
    */
17879
    attributeName: t(propertyName),
17880
    /**
17881
    The [name](#highlight.tags.name) of a class.
17882
    */
17883
    className: t(name),
17884
    /**
17885
    A label [name](#highlight.tags.name).
17886
    */
17887
    labelName: t(name),
17888
    /**
17889
    A namespace [name](#highlight.tags.name).
17890
    */
17891
    namespace: t(name),
17892
    /**
17893
    The [name](#highlight.tags.name) of a macro.
17894
    */
17895
    macroName: t(name),
17896
    /**
17897
    A literal value.
17898
    */
17899
    literal,
17900
    /**
17901
    A string [literal](#highlight.tags.literal).
17902
    */
17903
    string,
17904
    /**
17905
    A documentation [string](#highlight.tags.string).
17906
    */
17907
    docString: t(string),
17908
    /**
17909
    A character literal (subtag of [string](#highlight.tags.string)).
17910
    */
17911
    character: t(string),
17912
    /**
17913
    An attribute value (subtag of [string](#highlight.tags.string)).
17914
    */
17915
    attributeValue: t(string),
17916
    /**
17917
    A number [literal](#highlight.tags.literal).
17918
    */
17919
    number,
17920
    /**
17921
    An integer [number](#highlight.tags.number) literal.
17922
    */
17923
    integer: t(number),
17924
    /**
17925
    A floating-point [number](#highlight.tags.number) literal.
17926
    */
17927
    float: t(number),
17928
    /**
17929
    A boolean [literal](#highlight.tags.literal).
17930
    */
17931
    bool: t(literal),
17932
    /**
17933
    Regular expression [literal](#highlight.tags.literal).
17934
    */
17935
    regexp: t(literal),
17936
    /**
17937
    An escape [literal](#highlight.tags.literal), for example a
17938
    backslash escape in a string.
17939
    */
17940
    escape: t(literal),
17941
    /**
17942
    A color [literal](#highlight.tags.literal).
17943
    */
17944
    color: t(literal),
17945
    /**
17946
    A URL [literal](#highlight.tags.literal).
17947
    */
17948
    url: t(literal),
17949
    /**
17950
    A language keyword.
17951
    */
17952
    keyword,
17953
    /**
17954
    The [keyword](#highlight.tags.keyword) for the self or this
17955
    object.
17956
    */
17957
    self: t(keyword),
17958
    /**
17959
    The [keyword](#highlight.tags.keyword) for null.
17960
    */
17961
    null: t(keyword),
17962
    /**
17963
    A [keyword](#highlight.tags.keyword) denoting some atomic value.
17964
    */
17965
    atom: t(keyword),
17966
    /**
17967
    A [keyword](#highlight.tags.keyword) that represents a unit.
17968
    */
17969
    unit: t(keyword),
17970
    /**
17971
    A modifier [keyword](#highlight.tags.keyword).
17972
    */
17973
    modifier: t(keyword),
17974
    /**
17975
    A [keyword](#highlight.tags.keyword) that acts as an operator.
17976
    */
17977
    operatorKeyword: t(keyword),
17978
    /**
17979
    A control-flow related [keyword](#highlight.tags.keyword).
17980
    */
17981
    controlKeyword: t(keyword),
17982
    /**
17983
    A [keyword](#highlight.tags.keyword) that defines something.
17984
    */
17985
    definitionKeyword: t(keyword),
17986
    /**
17987
    A [keyword](#highlight.tags.keyword) related to defining or
17988
    interfacing with modules.
17989
    */
17990
    moduleKeyword: t(keyword),
17991
    /**
17992
    An operator.
17993
    */
17994
    operator,
17995
    /**
17996
    An [operator](#highlight.tags.operator) that dereferences something.
17997
    */
17998
    derefOperator: t(operator),
17999
    /**
18000
    Arithmetic-related [operator](#highlight.tags.operator).
18001
    */
18002
    arithmeticOperator: t(operator),
18003
    /**
18004
    Logical [operator](#highlight.tags.operator).
18005
    */
18006
    logicOperator: t(operator),
18007
    /**
18008
    Bit [operator](#highlight.tags.operator).
18009
    */
18010
    bitwiseOperator: t(operator),
18011
    /**
18012
    Comparison [operator](#highlight.tags.operator).
18013
    */
18014
    compareOperator: t(operator),
18015
    /**
18016
    [Operator](#highlight.tags.operator) that updates its operand.
18017
    */
18018
    updateOperator: t(operator),
18019
    /**
18020
    [Operator](#highlight.tags.operator) that defines something.
18021
    */
18022
    definitionOperator: t(operator),
18023
    /**
18024
    Type-related [operator](#highlight.tags.operator).
18025
    */
18026
    typeOperator: t(operator),
18027
    /**
18028
    Control-flow [operator](#highlight.tags.operator).
18029
    */
18030
    controlOperator: t(operator),
18031
    /**
18032
    Program or markup punctuation.
18033
    */
18034
    punctuation,
18035
    /**
18036
    [Punctuation](#highlight.tags.punctuation) that separates
18037
    things.
18038
    */
18039
    separator: t(punctuation),
18040
    /**
18041
    Bracket-style [punctuation](#highlight.tags.punctuation).
18042
    */
18043
    bracket,
18044
    /**
18045
    Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
18046
    tokens).
18047
    */
18048
    angleBracket: t(bracket),
18049
    /**
18050
    Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
18051
    tokens).
18052
    */
18053
    squareBracket: t(bracket),
18054
    /**
18055
    Parentheses (usually `(` and `)` tokens). Subtag of
18056
    [bracket](#highlight.tags.bracket).
18057
    */
18058
    paren: t(bracket),
18059
    /**
18060
    Braces (usually `{` and `}` tokens). Subtag of
18061
    [bracket](#highlight.tags.bracket).
18062
    */
18063
    brace: t(bracket),
18064
    /**
18065
    Content, for example plain text in XML or markup documents.
18066
    */
18067
    content,
18068
    /**
18069
    [Content](#highlight.tags.content) that represents a heading.
18070
    */
18071
    heading,
18072
    /**
18073
    A level 1 [heading](#highlight.tags.heading).
18074
    */
18075
    heading1: t(heading),
18076
    /**
18077
    A level 2 [heading](#highlight.tags.heading).
18078
    */
18079
    heading2: t(heading),
18080
    /**
18081
    A level 3 [heading](#highlight.tags.heading).
18082
    */
18083
    heading3: t(heading),
18084
    /**
18085
    A level 4 [heading](#highlight.tags.heading).
18086
    */
18087
    heading4: t(heading),
18088
    /**
18089
    A level 5 [heading](#highlight.tags.heading).
18090
    */
18091
    heading5: t(heading),
18092
    /**
18093
    A level 6 [heading](#highlight.tags.heading).
18094
    */
18095
    heading6: t(heading),
18096
    /**
1441 ariadna 18097
    A prose [content](#highlight.tags.content) separator (such as a horizontal rule).
1 efrain 18098
    */
18099
    contentSeparator: t(content),
18100
    /**
18101
    [Content](#highlight.tags.content) that represents a list.
18102
    */
18103
    list: t(content),
18104
    /**
18105
    [Content](#highlight.tags.content) that represents a quote.
18106
    */
18107
    quote: t(content),
18108
    /**
18109
    [Content](#highlight.tags.content) that is emphasized.
18110
    */
18111
    emphasis: t(content),
18112
    /**
18113
    [Content](#highlight.tags.content) that is styled strong.
18114
    */
18115
    strong: t(content),
18116
    /**
18117
    [Content](#highlight.tags.content) that is part of a link.
18118
    */
18119
    link: t(content),
18120
    /**
18121
    [Content](#highlight.tags.content) that is styled as code or
18122
    monospace.
18123
    */
18124
    monospace: t(content),
18125
    /**
18126
    [Content](#highlight.tags.content) that has a strike-through
18127
    style.
18128
    */
18129
    strikethrough: t(content),
18130
    /**
18131
    Inserted text in a change-tracking format.
18132
    */
18133
    inserted: t(),
18134
    /**
18135
    Deleted text.
18136
    */
18137
    deleted: t(),
18138
    /**
18139
    Changed text.
18140
    */
18141
    changed: t(),
18142
    /**
18143
    An invalid or unsyntactic element.
18144
    */
18145
    invalid: t(),
18146
    /**
18147
    Metadata or meta-instruction.
18148
    */
18149
    meta,
18150
    /**
18151
    [Metadata](#highlight.tags.meta) that applies to the entire
18152
    document.
18153
    */
18154
    documentMeta: t(meta),
18155
    /**
18156
    [Metadata](#highlight.tags.meta) that annotates or adds
18157
    attributes to a given syntactic element.
18158
    */
18159
    annotation: t(meta),
18160
    /**
18161
    Processing instruction or preprocessor directive. Subtag of
18162
    [meta](#highlight.tags.meta).
18163
    */
18164
    processingInstruction: t(meta),
18165
    /**
18166
    [Modifier](#highlight.Tag^defineModifier) that indicates that a
18167
    given element is being defined. Expected to be used with the
18168
    various [name](#highlight.tags.name) tags.
18169
    */
1441 ariadna 18170
    definition: Tag.defineModifier("definition"),
1 efrain 18171
    /**
18172
    [Modifier](#highlight.Tag^defineModifier) that indicates that
18173
    something is constant. Mostly expected to be used with
18174
    [variable names](#highlight.tags.variableName).
18175
    */
1441 ariadna 18176
    constant: Tag.defineModifier("constant"),
1 efrain 18177
    /**
18178
    [Modifier](#highlight.Tag^defineModifier) used to indicate that
18179
    a [variable](#highlight.tags.variableName) or [property
18180
    name](#highlight.tags.propertyName) is being called or defined
18181
    as a function.
18182
    */
1441 ariadna 18183
    function: Tag.defineModifier("function"),
1 efrain 18184
    /**
18185
    [Modifier](#highlight.Tag^defineModifier) that can be applied to
18186
    [names](#highlight.tags.name) to indicate that they belong to
18187
    the language's standard environment.
18188
    */
1441 ariadna 18189
    standard: Tag.defineModifier("standard"),
1 efrain 18190
    /**
18191
    [Modifier](#highlight.Tag^defineModifier) that indicates a given
18192
    [names](#highlight.tags.name) is local to some scope.
18193
    */
1441 ariadna 18194
    local: Tag.defineModifier("local"),
1 efrain 18195
    /**
18196
    A generic variant [modifier](#highlight.Tag^defineModifier) that
18197
    can be used to tag language-specific alternative variants of
18198
    some common tag. It is recommended for themes to define special
18199
    forms of at least the [string](#highlight.tags.string) and
18200
    [variable name](#highlight.tags.variableName) tags, since those
18201
    come up a lot.
18202
    */
1441 ariadna 18203
    special: Tag.defineModifier("special")
1 efrain 18204
};
1441 ariadna 18205
for (let name in tags$1) {
18206
    let val = tags$1[name];
18207
    if (val instanceof Tag)
18208
        val.name = name;
18209
}
1 efrain 18210
/**
18211
This is a highlighter that adds stable, predictable classes to
18212
tokens, for styling with external CSS.
18213
 
18214
The following tags are mapped to their name prefixed with `"tok-"`
18215
(for example `"tok-comment"`):
18216
 
18217
* [`link`](#highlight.tags.link)
18218
* [`heading`](#highlight.tags.heading)
18219
* [`emphasis`](#highlight.tags.emphasis)
18220
* [`strong`](#highlight.tags.strong)
18221
* [`keyword`](#highlight.tags.keyword)
18222
* [`atom`](#highlight.tags.atom)
18223
* [`bool`](#highlight.tags.bool)
18224
* [`url`](#highlight.tags.url)
18225
* [`labelName`](#highlight.tags.labelName)
18226
* [`inserted`](#highlight.tags.inserted)
18227
* [`deleted`](#highlight.tags.deleted)
18228
* [`literal`](#highlight.tags.literal)
18229
* [`string`](#highlight.tags.string)
18230
* [`number`](#highlight.tags.number)
18231
* [`variableName`](#highlight.tags.variableName)
18232
* [`typeName`](#highlight.tags.typeName)
18233
* [`namespace`](#highlight.tags.namespace)
18234
* [`className`](#highlight.tags.className)
18235
* [`macroName`](#highlight.tags.macroName)
18236
* [`propertyName`](#highlight.tags.propertyName)
18237
* [`operator`](#highlight.tags.operator)
18238
* [`comment`](#highlight.tags.comment)
18239
* [`meta`](#highlight.tags.meta)
18240
* [`punctuation`](#highlight.tags.punctuation)
18241
* [`invalid`](#highlight.tags.invalid)
18242
 
18243
In addition, these mappings are provided:
18244
 
18245
* [`regexp`](#highlight.tags.regexp),
18246
  [`escape`](#highlight.tags.escape), and
18247
  [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
18248
  are mapped to `"tok-string2"`
18249
* [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
18250
  to `"tok-variableName2"`
18251
* [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
18252
  to `"tok-variableName tok-local"`
18253
* [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
18254
  to `"tok-variableName tok-definition"`
18255
* [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
18256
  to `"tok-propertyName tok-definition"`
18257
*/
18258
tagHighlighter([
18259
    { tag: tags$1.link, class: "tok-link" },
18260
    { tag: tags$1.heading, class: "tok-heading" },
18261
    { tag: tags$1.emphasis, class: "tok-emphasis" },
18262
    { tag: tags$1.strong, class: "tok-strong" },
18263
    { tag: tags$1.keyword, class: "tok-keyword" },
18264
    { tag: tags$1.atom, class: "tok-atom" },
18265
    { tag: tags$1.bool, class: "tok-bool" },
18266
    { tag: tags$1.url, class: "tok-url" },
18267
    { tag: tags$1.labelName, class: "tok-labelName" },
18268
    { tag: tags$1.inserted, class: "tok-inserted" },
18269
    { tag: tags$1.deleted, class: "tok-deleted" },
18270
    { tag: tags$1.literal, class: "tok-literal" },
18271
    { tag: tags$1.string, class: "tok-string" },
18272
    { tag: tags$1.number, class: "tok-number" },
18273
    { tag: [tags$1.regexp, tags$1.escape, tags$1.special(tags$1.string)], class: "tok-string2" },
18274
    { tag: tags$1.variableName, class: "tok-variableName" },
18275
    { tag: tags$1.local(tags$1.variableName), class: "tok-variableName tok-local" },
18276
    { tag: tags$1.definition(tags$1.variableName), class: "tok-variableName tok-definition" },
18277
    { tag: tags$1.special(tags$1.variableName), class: "tok-variableName2" },
18278
    { tag: tags$1.definition(tags$1.propertyName), class: "tok-propertyName tok-definition" },
18279
    { tag: tags$1.typeName, class: "tok-typeName" },
18280
    { tag: tags$1.namespace, class: "tok-namespace" },
18281
    { tag: tags$1.className, class: "tok-className" },
18282
    { tag: tags$1.macroName, class: "tok-macroName" },
18283
    { tag: tags$1.propertyName, class: "tok-propertyName" },
18284
    { tag: tags$1.operator, class: "tok-operator" },
18285
    { tag: tags$1.comment, class: "tok-comment" },
18286
    { tag: tags$1.meta, class: "tok-meta" },
18287
    { tag: tags$1.invalid, class: "tok-invalid" },
18288
    { tag: tags$1.punctuation, class: "tok-punctuation" }
18289
]);
18290
 
18291
var _a;
18292
/**
18293
Node prop stored in a parser's top syntax node to provide the
18294
facet that stores language-specific data for that language.
18295
*/
18296
const languageDataProp = /*@__PURE__*/new NodeProp();
18297
/**
18298
Helper function to define a facet (to be added to the top syntax
18299
node(s) for a language via
18300
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
18301
used to associate language data with the language. You
18302
probably only need this when subclassing
18303
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
18304
*/
18305
function defineLanguageFacet(baseData) {
18306
    return Facet.define({
18307
        combine: baseData ? values => values.concat(baseData) : undefined
18308
    });
18309
}
18310
/**
18311
Syntax node prop used to register sublanguages. Should be added to
18312
the top level node type for the language.
18313
*/
18314
const sublanguageProp = /*@__PURE__*/new NodeProp();
18315
/**
18316
A language object manages parsing and per-language
18317
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
18318
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
18319
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
18320
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
18321
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
18322
for stream parsers.
18323
*/
18324
class Language {
18325
    /**
18326
    Construct a language object. If you need to invoke this
18327
    directly, first define a data facet with
18328
    [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
18329
    configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
18330
    to the language's outer syntax node.
18331
    */
18332
    constructor(
18333
    /**
18334
    The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
18335
    used for this language.
18336
    */
18337
    data, parser, extraExtensions = [],
18338
    /**
18339
    A language name.
18340
    */
18341
    name = "") {
18342
        this.data = data;
18343
        this.name = name;
18344
        // Kludge to define EditorState.tree as a debugging helper,
18345
        // without the EditorState package actually knowing about
18346
        // languages and lezer trees.
18347
        if (!EditorState.prototype.hasOwnProperty("tree"))
18348
            Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
18349
        this.parser = parser;
18350
        this.extension = [
18351
            language.of(this),
18352
            EditorState.languageData.of((state, pos, side) => {
18353
                let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);
18354
                if (!data)
18355
                    return [];
18356
                let base = state.facet(data), sub = top.type.prop(sublanguageProp);
18357
                if (sub) {
18358
                    let innerNode = top.resolve(pos - top.from, side);
18359
                    for (let sublang of sub)
18360
                        if (sublang.test(innerNode, state)) {
18361
                            let data = state.facet(sublang.facet);
18362
                            return sublang.type == "replace" ? data : data.concat(base);
18363
                        }
18364
                }
18365
                return base;
18366
            })
18367
        ].concat(extraExtensions);
18368
    }
18369
    /**
18370
    Query whether this language is active at the given position.
18371
    */
18372
    isActiveAt(state, pos, side = -1) {
18373
        return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
18374
    }
18375
    /**
18376
    Find the document regions that were parsed using this language.
18377
    The returned regions will _include_ any nested languages rooted
18378
    in this language, when those exist.
18379
    */
18380
    findRegions(state) {
18381
        let lang = state.facet(language);
18382
        if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
18383
            return [{ from: 0, to: state.doc.length }];
18384
        if (!lang || !lang.allowsNesting)
18385
            return [];
18386
        let result = [];
18387
        let explore = (tree, from) => {
18388
            if (tree.prop(languageDataProp) == this.data) {
18389
                result.push({ from, to: from + tree.length });
18390
                return;
18391
            }
18392
            let mount = tree.prop(NodeProp.mounted);
18393
            if (mount) {
18394
                if (mount.tree.prop(languageDataProp) == this.data) {
18395
                    if (mount.overlay)
18396
                        for (let r of mount.overlay)
18397
                            result.push({ from: r.from + from, to: r.to + from });
18398
                    else
18399
                        result.push({ from: from, to: from + tree.length });
18400
                    return;
18401
                }
18402
                else if (mount.overlay) {
18403
                    let size = result.length;
18404
                    explore(mount.tree, mount.overlay[0].from + from);
18405
                    if (result.length > size)
18406
                        return;
18407
                }
18408
            }
18409
            for (let i = 0; i < tree.children.length; i++) {
18410
                let ch = tree.children[i];
18411
                if (ch instanceof Tree)
18412
                    explore(ch, tree.positions[i] + from);
18413
            }
18414
        };
18415
        explore(syntaxTree(state), 0);
18416
        return result;
18417
    }
18418
    /**
18419
    Indicates whether this language allows nested languages. The
18420
    default implementation returns true.
18421
    */
18422
    get allowsNesting() { return true; }
18423
}
18424
/**
18425
@internal
18426
*/
18427
Language.setState = /*@__PURE__*/StateEffect.define();
18428
function topNodeAt(state, pos, side) {
18429
    let topLang = state.facet(language), tree = syntaxTree(state).topNode;
18430
    if (!topLang || topLang.allowsNesting) {
18431
        for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
18432
            if (node.type.isTop)
18433
                tree = node;
18434
    }
18435
    return tree;
18436
}
18437
/**
18438
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
18439
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
18440
parsers.
18441
*/
18442
class LRLanguage extends Language {
18443
    constructor(data, parser, name) {
18444
        super(data, parser, [], name);
18445
        this.parser = parser;
18446
    }
18447
    /**
18448
    Define a language from a parser.
18449
    */
18450
    static define(spec) {
18451
        let data = defineLanguageFacet(spec.languageData);
18452
        return new LRLanguage(data, spec.parser.configure({
18453
            props: [languageDataProp.add(type => type.isTop ? data : undefined)]
18454
        }), spec.name);
18455
    }
18456
    /**
18457
    Create a new instance of this language with a reconfigured
18458
    version of its parser and optionally a new name.
18459
    */
18460
    configure(options, name) {
18461
        return new LRLanguage(this.data, this.parser.configure(options), name || this.name);
18462
    }
18463
    get allowsNesting() { return this.parser.hasWrappers(); }
18464
}
18465
/**
18466
Get the syntax tree for a state, which is the current (possibly
18467
incomplete) parse tree of the active
18468
[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
18469
language available.
18470
*/
18471
function syntaxTree(state) {
18472
    let field = state.field(Language.state, false);
18473
    return field ? field.tree : Tree.empty;
18474
}
18475
/**
18476
Lezer-style
18477
[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
18478
object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
18479
*/
18480
class DocInput {
18481
    /**
18482
    Create an input object for the given document.
18483
    */
18484
    constructor(doc) {
18485
        this.doc = doc;
18486
        this.cursorPos = 0;
18487
        this.string = "";
18488
        this.cursor = doc.iter();
18489
    }
18490
    get length() { return this.doc.length; }
18491
    syncTo(pos) {
18492
        this.string = this.cursor.next(pos - this.cursorPos).value;
18493
        this.cursorPos = pos + this.string.length;
18494
        return this.cursorPos - this.string.length;
18495
    }
18496
    chunk(pos) {
18497
        this.syncTo(pos);
18498
        return this.string;
18499
    }
18500
    get lineChunks() { return true; }
18501
    read(from, to) {
18502
        let stringStart = this.cursorPos - this.string.length;
18503
        if (from < stringStart || to >= this.cursorPos)
18504
            return this.doc.sliceString(from, to);
18505
        else
18506
            return this.string.slice(from - stringStart, to - stringStart);
18507
    }
18508
}
18509
let currentContext = null;
18510
/**
18511
A parse context provided to parsers working on the editor content.
18512
*/
18513
class ParseContext {
18514
    constructor(parser,
18515
    /**
18516
    The current editor state.
18517
    */
18518
    state,
18519
    /**
18520
    Tree fragments that can be reused by incremental re-parses.
18521
    */
18522
    fragments = [],
18523
    /**
18524
    @internal
18525
    */
18526
    tree,
18527
    /**
18528
    @internal
18529
    */
18530
    treeLen,
18531
    /**
18532
    The current editor viewport (or some overapproximation
18533
    thereof). Intended to be used for opportunistically avoiding
18534
    work (in which case
18535
    [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
18536
    should be called to make sure the parser is restarted when the
18537
    skipped region becomes visible).
18538
    */
18539
    viewport,
18540
    /**
18541
    @internal
18542
    */
18543
    skipped,
18544
    /**
18545
    This is where skipping parsers can register a promise that,
18546
    when resolved, will schedule a new parse. It is cleared when
18547
    the parse worker picks up the promise. @internal
18548
    */
18549
    scheduleOn) {
18550
        this.parser = parser;
18551
        this.state = state;
18552
        this.fragments = fragments;
18553
        this.tree = tree;
18554
        this.treeLen = treeLen;
18555
        this.viewport = viewport;
18556
        this.skipped = skipped;
18557
        this.scheduleOn = scheduleOn;
18558
        this.parse = null;
18559
        /**
18560
        @internal
18561
        */
18562
        this.tempSkipped = [];
18563
    }
18564
    /**
18565
    @internal
18566
    */
18567
    static create(parser, state, viewport) {
18568
        return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
18569
    }
18570
    startParse() {
18571
        return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
18572
    }
18573
    /**
18574
    @internal
18575
    */
18576
    work(until, upto) {
18577
        if (upto != null && upto >= this.state.doc.length)
18578
            upto = undefined;
18579
        if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
18580
            this.takeTree();
18581
            return true;
18582
        }
18583
        return this.withContext(() => {
18584
            var _a;
18585
            if (typeof until == "number") {
18586
                let endTime = Date.now() + until;
18587
                until = () => Date.now() > endTime;
18588
            }
18589
            if (!this.parse)
18590
                this.parse = this.startParse();
18591
            if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&
18592
                upto < this.state.doc.length)
18593
                this.parse.stopAt(upto);
18594
            for (;;) {
18595
                let done = this.parse.advance();
18596
                if (done) {
18597
                    this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
18598
                    this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
18599
                    this.tree = done;
18600
                    this.parse = null;
18601
                    if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
18602
                        this.parse = this.startParse();
18603
                    else
18604
                        return true;
18605
                }
18606
                if (until())
18607
                    return false;
18608
            }
18609
        });
18610
    }
18611
    /**
18612
    @internal
18613
    */
18614
    takeTree() {
18615
        let pos, tree;
18616
        if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
18617
            if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
18618
                this.parse.stopAt(pos);
18619
            this.withContext(() => { while (!(tree = this.parse.advance())) { } });
18620
            this.treeLen = pos;
18621
            this.tree = tree;
18622
            this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
18623
            this.parse = null;
18624
        }
18625
    }
18626
    withContext(f) {
18627
        let prev = currentContext;
18628
        currentContext = this;
18629
        try {
18630
            return f();
18631
        }
18632
        finally {
18633
            currentContext = prev;
18634
        }
18635
    }
18636
    withoutTempSkipped(fragments) {
18637
        for (let r; r = this.tempSkipped.pop();)
18638
            fragments = cutFragments(fragments, r.from, r.to);
18639
        return fragments;
18640
    }
18641
    /**
18642
    @internal
18643
    */
18644
    changes(changes, newState) {
18645
        let { fragments, tree, treeLen, viewport, skipped } = this;
18646
        this.takeTree();
18647
        if (!changes.empty) {
18648
            let ranges = [];
18649
            changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
18650
            fragments = TreeFragment.applyChanges(fragments, ranges);
18651
            tree = Tree.empty;
18652
            treeLen = 0;
18653
            viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
18654
            if (this.skipped.length) {
18655
                skipped = [];
18656
                for (let r of this.skipped) {
18657
                    let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
18658
                    if (from < to)
18659
                        skipped.push({ from, to });
18660
                }
18661
            }
18662
        }
18663
        return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
18664
    }
18665
    /**
18666
    @internal
18667
    */
18668
    updateViewport(viewport) {
18669
        if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
18670
            return false;
18671
        this.viewport = viewport;
18672
        let startLen = this.skipped.length;
18673
        for (let i = 0; i < this.skipped.length; i++) {
18674
            let { from, to } = this.skipped[i];
18675
            if (from < viewport.to && to > viewport.from) {
18676
                this.fragments = cutFragments(this.fragments, from, to);
18677
                this.skipped.splice(i--, 1);
18678
            }
18679
        }
18680
        if (this.skipped.length >= startLen)
18681
            return false;
18682
        this.reset();
18683
        return true;
18684
    }
18685
    /**
18686
    @internal
18687
    */
18688
    reset() {
18689
        if (this.parse) {
18690
            this.takeTree();
18691
            this.parse = null;
18692
        }
18693
    }
18694
    /**
18695
    Notify the parse scheduler that the given region was skipped
18696
    because it wasn't in view, and the parse should be restarted
18697
    when it comes into view.
18698
    */
18699
    skipUntilInView(from, to) {
18700
        this.skipped.push({ from, to });
18701
    }
18702
    /**
18703
    Returns a parser intended to be used as placeholder when
18704
    asynchronously loading a nested parser. It'll skip its input and
18705
    mark it as not-really-parsed, so that the next update will parse
18706
    it again.
18707
 
18708
    When `until` is given, a reparse will be scheduled when that
18709
    promise resolves.
18710
    */
18711
    static getSkippingParser(until) {
18712
        return new class extends Parser {
18713
            createParse(input, fragments, ranges) {
18714
                let from = ranges[0].from, to = ranges[ranges.length - 1].to;
18715
                let parser = {
18716
                    parsedPos: from,
18717
                    advance() {
18718
                        let cx = currentContext;
18719
                        if (cx) {
18720
                            for (let r of ranges)
18721
                                cx.tempSkipped.push(r);
18722
                            if (until)
18723
                                cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
18724
                        }
18725
                        this.parsedPos = to;
18726
                        return new Tree(NodeType.none, [], [], to - from);
18727
                    },
18728
                    stoppedAt: null,
18729
                    stopAt() { }
18730
                };
18731
                return parser;
18732
            }
18733
        };
18734
    }
18735
    /**
18736
    @internal
18737
    */
18738
    isDone(upto) {
18739
        upto = Math.min(upto, this.state.doc.length);
18740
        let frags = this.fragments;
18741
        return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
18742
    }
18743
    /**
18744
    Get the context for the current parse, or `null` if no editor
18745
    parse is in progress.
18746
    */
18747
    static get() { return currentContext; }
18748
}
18749
function cutFragments(fragments, from, to) {
18750
    return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
18751
}
18752
class LanguageState {
18753
    constructor(
18754
    // A mutable parse state that is used to preserve work done during
18755
    // the lifetime of a state when moving to the next state.
18756
    context) {
18757
        this.context = context;
18758
        this.tree = context.tree;
18759
    }
18760
    apply(tr) {
18761
        if (!tr.docChanged && this.tree == this.context.tree)
18762
            return this;
18763
        let newCx = this.context.changes(tr.changes, tr.state);
18764
        // If the previous parse wasn't done, go forward only up to its
18765
        // end position or the end of the viewport, to avoid slowing down
18766
        // state updates with parse work beyond the viewport.
18767
        let upto = this.context.treeLen == tr.startState.doc.length ? undefined
18768
            : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
18769
        if (!newCx.work(20 /* Work.Apply */, upto))
18770
            newCx.takeTree();
18771
        return new LanguageState(newCx);
18772
    }
18773
    static init(state) {
18774
        let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);
18775
        let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
18776
        if (!parseState.work(20 /* Work.Apply */, vpTo))
18777
            parseState.takeTree();
18778
        return new LanguageState(parseState);
18779
    }
18780
}
18781
Language.state = /*@__PURE__*/StateField.define({
18782
    create: LanguageState.init,
18783
    update(value, tr) {
18784
        for (let e of tr.effects)
18785
            if (e.is(Language.setState))
18786
                return e.value;
18787
        if (tr.startState.facet(language) != tr.state.facet(language))
18788
            return LanguageState.init(tr.state);
18789
        return value.apply(tr);
18790
    }
18791
});
18792
let requestIdle = (callback) => {
18793
    let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);
18794
    return () => clearTimeout(timeout);
18795
};
18796
if (typeof requestIdleCallback != "undefined")
18797
    requestIdle = (callback) => {
18798
        let idle = -1, timeout = setTimeout(() => {
18799
            idle = requestIdleCallback(callback, { timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */ });
18800
        }, 100 /* Work.MinPause */);
18801
        return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
18802
    };
18803
const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)
18804
    ? () => navigator.scheduling.isInputPending() : null;
18805
const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker {
18806
    constructor(view) {
18807
        this.view = view;
18808
        this.working = null;
18809
        this.workScheduled = 0;
18810
        // End of the current time chunk
18811
        this.chunkEnd = -1;
18812
        // Milliseconds of budget left for this chunk
18813
        this.chunkBudget = -1;
18814
        this.work = this.work.bind(this);
18815
        this.scheduleWork();
18816
    }
18817
    update(update) {
18818
        let cx = this.view.state.field(Language.state).context;
18819
        if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
18820
            this.scheduleWork();
18821
        if (update.docChanged || update.selectionSet) {
18822
            if (this.view.hasFocus)
18823
                this.chunkBudget += 50 /* Work.ChangeBonus */;
18824
            this.scheduleWork();
18825
        }
18826
        this.checkAsyncSchedule(cx);
18827
    }
18828
    scheduleWork() {
18829
        if (this.working)
18830
            return;
18831
        let { state } = this.view, field = state.field(Language.state);
18832
        if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
18833
            this.working = requestIdle(this.work);
18834
    }
18835
    work(deadline) {
18836
        this.working = null;
18837
        let now = Date.now();
18838
        if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
18839
            this.chunkEnd = now + 30000 /* Work.ChunkTime */;
18840
            this.chunkBudget = 3000 /* Work.ChunkBudget */;
18841
        }
18842
        if (this.chunkBudget <= 0)
18843
            return; // No more budget
18844
        let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
18845
        if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */))
18846
            return;
18847
        let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);
18848
        let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
18849
        let done = field.context.work(() => {
18850
            return isInputPending && isInputPending() || Date.now() > endTime;
18851
        }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));
18852
        this.chunkBudget -= Date.now() - now;
18853
        if (done || this.chunkBudget <= 0) {
18854
            field.context.takeTree();
18855
            this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
18856
        }
18857
        if (this.chunkBudget > 0 && !(done && !viewportFirst))
18858
            this.scheduleWork();
18859
        this.checkAsyncSchedule(field.context);
18860
    }
18861
    checkAsyncSchedule(cx) {
18862
        if (cx.scheduleOn) {
18863
            this.workScheduled++;
18864
            cx.scheduleOn
18865
                .then(() => this.scheduleWork())
18866
                .catch(err => logException(this.view.state, err))
18867
                .then(() => this.workScheduled--);
18868
            cx.scheduleOn = null;
18869
        }
18870
    }
18871
    destroy() {
18872
        if (this.working)
18873
            this.working();
18874
    }
18875
    isWorking() {
18876
        return !!(this.working || this.workScheduled > 0);
18877
    }
18878
}, {
18879
    eventHandlers: { focus() { this.scheduleWork(); } }
18880
});
18881
/**
18882
The facet used to associate a language with an editor state. Used
18883
by `Language` object's `extension` property (so you don't need to
18884
manually wrap your languages in this). Can be used to access the
18885
current language on a state.
18886
*/
18887
const language = /*@__PURE__*/Facet.define({
18888
    combine(languages) { return languages.length ? languages[0] : null; },
18889
    enables: language => [
18890
        Language.state,
18891
        parseWorker,
18892
        EditorView.contentAttributes.compute([language], state => {
18893
            let lang = state.facet(language);
18894
            return lang && lang.name ? { "data-language": lang.name } : {};
18895
        })
18896
    ]
18897
});
18898
/**
18899
This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
18900
optional set of supporting extensions. Language packages are
18901
encouraged to export a function that optionally takes a
18902
configuration object and returns a `LanguageSupport` instance, as
18903
the main way for client code to use the package.
18904
*/
18905
class LanguageSupport {
18906
    /**
18907
    Create a language support object.
18908
    */
18909
    constructor(
18910
    /**
18911
    The language object.
18912
    */
18913
    language,
18914
    /**
18915
    An optional set of supporting extensions. When nesting a
18916
    language in another language, the outer language is encouraged
18917
    to include the supporting extensions for its inner languages
18918
    in its own set of support extensions.
18919
    */
18920
    support = []) {
18921
        this.language = language;
18922
        this.support = support;
18923
        this.extension = [language, support];
18924
    }
18925
}
18926
 
18927
/**
18928
Facet that defines a way to provide a function that computes the
18929
appropriate indentation depth, as a column number (see
18930
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
18931
line. A return value of `null` indicates no indentation can be
18932
determined, and the line should inherit the indentation of the one
18933
above it. A return value of `undefined` defers to the next indent
18934
service.
18935
*/
18936
const indentService = /*@__PURE__*/Facet.define();
18937
/**
18938
Facet for overriding the unit by which indentation happens. Should
18939
be a string consisting either entirely of the same whitespace
18940
character. When not set, this defaults to 2 spaces.
18941
*/
18942
const indentUnit = /*@__PURE__*/Facet.define({
18943
    combine: values => {
18944
        if (!values.length)
18945
            return "  ";
18946
        let unit = values[0];
18947
        if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0]))
18948
            throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
18949
        return unit;
18950
    }
18951
});
18952
/**
18953
Return the _column width_ of an indent unit in the state.
18954
Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
18955
facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
18956
contains tabs.
18957
*/
18958
function getIndentUnit(state) {
18959
    let unit = state.facet(indentUnit);
18960
    return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
18961
}
18962
/**
18963
Create an indentation string that covers columns 0 to `cols`.
18964
Will use tabs for as much of the columns as possible when the
18965
[`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
18966
tabs.
18967
*/
18968
function indentString(state, cols) {
18969
    let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0];
18970
    if (ch == "\t") {
18971
        while (cols >= ts) {
18972
            result += "\t";
18973
            cols -= ts;
18974
        }
18975
        ch = " ";
18976
    }
18977
    for (let i = 0; i < cols; i++)
18978
        result += ch;
18979
    return result;
18980
}
18981
/**
18982
Get the indentation, as a column number, at the given position.
18983
Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
18984
that are registered, and if none of those return an indentation,
18985
this will check the syntax tree for the [indent node
18986
prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
18987
number when an indentation could be determined, and null
18988
otherwise.
18989
*/
18990
function getIndentation(context, pos) {
18991
    if (context instanceof EditorState)
18992
        context = new IndentContext(context);
18993
    for (let service of context.state.facet(indentService)) {
18994
        let result = service(context, pos);
18995
        if (result !== undefined)
18996
            return result;
18997
    }
18998
    let tree = syntaxTree(context.state);
18999
    return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
19000
}
19001
/**
19002
Indentation contexts are used when calling [indentation
19003
services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
19004
useful in indentation logic, and can selectively override the
19005
indentation reported for some lines.
19006
*/
19007
class IndentContext {
19008
    /**
19009
    Create an indent context.
19010
    */
19011
    constructor(
19012
    /**
19013
    The editor state.
19014
    */
19015
    state,
19016
    /**
19017
    @internal
19018
    */
19019
    options = {}) {
19020
        this.state = state;
19021
        this.options = options;
19022
        this.unit = getIndentUnit(state);
19023
    }
19024
    /**
19025
    Get a description of the line at the given position, taking
19026
    [simulated line
19027
    breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
19028
    into account. If there is such a break at `pos`, the `bias`
19029
    argument determines whether the part of the line line before or
19030
    after the break is used.
19031
    */
19032
    lineAt(pos, bias = 1) {
19033
        let line = this.state.doc.lineAt(pos);
19034
        let { simulateBreak, simulateDoubleBreak } = this.options;
19035
        if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
19036
            if (simulateDoubleBreak && simulateBreak == pos)
19037
                return { text: "", from: pos };
19038
            else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
19039
                return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
19040
            else
19041
                return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
19042
        }
19043
        return line;
19044
    }
19045
    /**
19046
    Get the text directly after `pos`, either the entire line
19047
    or the next 100 characters, whichever is shorter.
19048
    */
19049
    textAfterPos(pos, bias = 1) {
19050
        if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
19051
            return "";
19052
        let { text, from } = this.lineAt(pos, bias);
19053
        return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
19054
    }
19055
    /**
19056
    Find the column for the given position.
19057
    */
19058
    column(pos, bias = 1) {
19059
        let { text, from } = this.lineAt(pos, bias);
19060
        let result = this.countColumn(text, pos - from);
19061
        let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
19062
        if (override > -1)
19063
            result += override - this.countColumn(text, text.search(/\S|$/));
19064
        return result;
19065
    }
19066
    /**
19067
    Find the column position (taking tabs into account) of the given
19068
    position in the given string.
19069
    */
19070
    countColumn(line, pos = line.length) {
19071
        return countColumn(line, this.state.tabSize, pos);
19072
    }
19073
    /**
19074
    Find the indentation column of the line at the given point.
19075
    */
19076
    lineIndent(pos, bias = 1) {
19077
        let { text, from } = this.lineAt(pos, bias);
19078
        let override = this.options.overrideIndentation;
19079
        if (override) {
19080
            let overriden = override(from);
19081
            if (overriden > -1)
19082
                return overriden;
19083
        }
19084
        return this.countColumn(text, text.search(/\S|$/));
19085
    }
19086
    /**
19087
    Returns the [simulated line
19088
    break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
19089
    for this context, if any.
19090
    */
19091
    get simulatedBreak() {
19092
        return this.options.simulateBreak || null;
19093
    }
19094
}
19095
/**
19096
A syntax tree node prop used to associate indentation strategies
19097
with node types. Such a strategy is a function from an indentation
19098
context to a column number (see also
19099
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
19100
indicates that no definitive indentation can be determined.
19101
*/
19102
const indentNodeProp = /*@__PURE__*/new NodeProp();
19103
// Compute the indentation for a given position from the syntax tree.
19104
function syntaxIndentation(cx, ast, pos) {
19105
    let stack = ast.resolveStack(pos);
1441 ariadna 19106
    let inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos);
1 efrain 19107
    if (inner != stack.node) {
19108
        let add = [];
1441 ariadna 19109
        for (let cur = inner; cur && !(cur.from == stack.node.from && cur.type == stack.node.type); cur = cur.parent)
1 efrain 19110
            add.push(cur);
19111
        for (let i = add.length - 1; i >= 0; i--)
19112
            stack = { node: add[i], next: stack };
19113
    }
19114
    return indentFor(stack, cx, pos);
19115
}
19116
function indentFor(stack, cx, pos) {
19117
    for (let cur = stack; cur; cur = cur.next) {
19118
        let strategy = indentStrategy(cur.node);
19119
        if (strategy)
19120
            return strategy(TreeIndentContext.create(cx, pos, cur));
19121
    }
19122
    return 0;
19123
}
19124
function ignoreClosed(cx) {
19125
    return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
19126
}
19127
function indentStrategy(tree) {
19128
    let strategy = tree.type.prop(indentNodeProp);
19129
    if (strategy)
19130
        return strategy;
19131
    let first = tree.firstChild, close;
19132
    if (first && (close = first.type.prop(NodeProp.closedBy))) {
19133
        let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
19134
        return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
19135
    }
19136
    return tree.parent == null ? topIndent : null;
19137
}
19138
function topIndent() { return 0; }
19139
/**
19140
Objects of this type provide context information and helper
19141
methods to indentation functions registered on syntax nodes.
19142
*/
19143
class TreeIndentContext extends IndentContext {
19144
    constructor(base,
19145
    /**
19146
    The position at which indentation is being computed.
19147
    */
19148
    pos,
19149
    /**
19150
    @internal
19151
    */
19152
    context) {
19153
        super(base.state, base.options);
19154
        this.base = base;
19155
        this.pos = pos;
19156
        this.context = context;
19157
    }
19158
    /**
19159
    The syntax tree node to which the indentation strategy
19160
    applies.
19161
    */
19162
    get node() { return this.context.node; }
19163
    /**
19164
    @internal
19165
    */
19166
    static create(base, pos, context) {
19167
        return new TreeIndentContext(base, pos, context);
19168
    }
19169
    /**
19170
    Get the text directly after `this.pos`, either the entire line
19171
    or the next 100 characters, whichever is shorter.
19172
    */
19173
    get textAfter() {
19174
        return this.textAfterPos(this.pos);
19175
    }
19176
    /**
19177
    Get the indentation at the reference line for `this.node`, which
19178
    is the line on which it starts, unless there is a node that is
19179
    _not_ a parent of this node covering the start of that line. If
19180
    so, the line at the start of that node is tried, again skipping
19181
    on if it is covered by another such node.
19182
    */
19183
    get baseIndent() {
19184
        return this.baseIndentFor(this.node);
19185
    }
19186
    /**
19187
    Get the indentation for the reference line of the given node
19188
    (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
19189
    */
19190
    baseIndentFor(node) {
19191
        let line = this.state.doc.lineAt(node.from);
19192
        // Skip line starts that are covered by a sibling (or cousin, etc)
19193
        for (;;) {
19194
            let atBreak = node.resolve(line.from);
19195
            while (atBreak.parent && atBreak.parent.from == atBreak.from)
19196
                atBreak = atBreak.parent;
19197
            if (isParent(atBreak, node))
19198
                break;
19199
            line = this.state.doc.lineAt(atBreak.from);
19200
        }
19201
        return this.lineIndent(line.from);
19202
    }
19203
    /**
19204
    Continue looking for indentations in the node's parent nodes,
19205
    and return the result of that.
19206
    */
19207
    continue() {
19208
        return indentFor(this.context.next, this.base, this.pos);
19209
    }
19210
}
19211
function isParent(parent, of) {
19212
    for (let cur = of; cur; cur = cur.parent)
19213
        if (parent == cur)
19214
            return true;
19215
    return false;
19216
}
19217
// Check whether a delimited node is aligned (meaning there are
19218
// non-skipped nodes on the same line as the opening delimiter). And
19219
// if so, return the opening token.
19220
function bracketedAligned(context) {
19221
    let tree = context.node;
19222
    let openToken = tree.childAfter(tree.from), last = tree.lastChild;
19223
    if (!openToken)
19224
        return null;
19225
    let sim = context.options.simulateBreak;
19226
    let openLine = context.state.doc.lineAt(openToken.from);
19227
    let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
19228
    for (let pos = openToken.to;;) {
19229
        let next = tree.childAfter(pos);
19230
        if (!next || next == last)
19231
            return null;
1441 ariadna 19232
        if (!next.type.isSkipped) {
19233
            if (next.from >= lineEnd)
19234
                return null;
19235
            let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length;
19236
            return { from: openToken.from, to: openToken.to + space };
19237
        }
1 efrain 19238
        pos = next.to;
19239
    }
19240
}
19241
/**
19242
An indentation strategy for delimited (usually bracketed) nodes.
19243
Will, by default, indent one unit more than the parent's base
19244
indent unless the line starts with a closing token. When `align`
19245
is true and there are non-skipped nodes on the node's opening
19246
line, the content of the node will be aligned with the end of the
19247
opening node, like this:
19248
 
19249
    foo(bar,
19250
        baz)
19251
*/
19252
function delimitedIndent({ closing, align = true, units = 1 }) {
19253
    return (context) => delimitedStrategy(context, align, units, closing);
19254
}
19255
function delimitedStrategy(context, align, units, closing, closedAt) {
19256
    let after = context.textAfter, space = after.match(/^\s*/)[0].length;
19257
    let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
19258
    let aligned = align ? bracketedAligned(context) : null;
19259
    if (aligned)
19260
        return closed ? context.column(aligned.from) : context.column(aligned.to);
19261
    return context.baseIndent + (closed ? 0 : context.unit * units);
19262
}
19263
/**
19264
An indentation strategy that aligns a node's content to its base
19265
indentation.
19266
*/
19267
const flatIndent = (context) => context.baseIndent;
19268
/**
19269
Creates an indentation strategy that, by default, indents
19270
continued lines one unit more than the node's base indentation.
19271
You can provide `except` to prevent indentation of lines that
19272
match a pattern (for example `/^else\b/` in `if`/`else`
19273
constructs), and you can change the amount of units used with the
19274
`units` option.
19275
*/
19276
function continuedIndent({ except, units = 1 } = {}) {
19277
    return (context) => {
19278
        let matchExcept = except && except.test(context.textAfter);
19279
        return context.baseIndent + (matchExcept ? 0 : units * context.unit);
19280
    };
19281
}
19282
const DontIndentBeyond = 200;
19283
/**
19284
Enables reindentation on input. When a language defines an
19285
`indentOnInput` field in its [language
19286
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
19287
expression, the line at the cursor will be reindented whenever new
19288
text is typed and the input from the start of the line up to the
19289
cursor matches that regexp.
19290
 
19291
To avoid unneccesary reindents, it is recommended to start the
19292
regexp with `^` (usually followed by `\s*`), and end it with `$`.
19293
For example, `/^\s*\}$/` will reindent when a closing brace is
19294
added at the start of a line.
19295
*/
19296
function indentOnInput() {
19297
    return EditorState.transactionFilter.of(tr => {
19298
        if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
19299
            return tr;
19300
        let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
19301
        if (!rules.length)
19302
            return tr;
19303
        let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
19304
        if (head > line.from + DontIndentBeyond)
19305
            return tr;
19306
        let lineStart = doc.sliceString(line.from, head);
19307
        if (!rules.some(r => r.test(lineStart)))
19308
            return tr;
19309
        let { state } = tr, last = -1, changes = [];
19310
        for (let { head } of state.selection.ranges) {
19311
            let line = state.doc.lineAt(head);
19312
            if (line.from == last)
19313
                continue;
19314
            last = line.from;
19315
            let indent = getIndentation(state, line.from);
19316
            if (indent == null)
19317
                continue;
19318
            let cur = /^\s*/.exec(line.text)[0];
19319
            let norm = indentString(state, indent);
19320
            if (cur != norm)
19321
                changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
19322
        }
19323
        return changes.length ? [tr, { changes, sequential: true }] : tr;
19324
    });
19325
}
19326
 
19327
/**
19328
A facet that registers a code folding service. When called with
19329
the extent of a line, such a function should return a foldable
19330
range that starts on that line (but continues beyond it), if one
19331
can be found.
19332
*/
19333
const foldService = /*@__PURE__*/Facet.define();
19334
/**
19335
This node prop is used to associate folding information with
19336
syntax node types. Given a syntax node, it should check whether
19337
that tree is foldable and return the range that can be collapsed
19338
when it is.
19339
*/
19340
const foldNodeProp = /*@__PURE__*/new NodeProp();
19341
/**
19342
[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
19343
the first and the last child of a syntax node. Useful for nodes
19344
that start and end with delimiters.
19345
*/
19346
function foldInside(node) {
19347
    let first = node.firstChild, last = node.lastChild;
19348
    return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
19349
}
19350
function syntaxFolding(state, start, end) {
19351
    let tree = syntaxTree(state);
19352
    if (tree.length < end)
19353
        return null;
19354
    let stack = tree.resolveStack(end, 1);
19355
    let found = null;
19356
    for (let iter = stack; iter; iter = iter.next) {
19357
        let cur = iter.node;
19358
        if (cur.to <= end || cur.from > end)
19359
            continue;
19360
        if (found && cur.from < start)
19361
            break;
19362
        let prop = cur.type.prop(foldNodeProp);
19363
        if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
19364
            let value = prop(cur, state);
19365
            if (value && value.from <= end && value.from >= start && value.to > end)
19366
                found = value;
19367
        }
19368
    }
19369
    return found;
19370
}
19371
function isUnfinished(node) {
19372
    let ch = node.lastChild;
19373
    return ch && ch.to == node.to && ch.type.isError;
19374
}
19375
/**
19376
Check whether the given line is foldable. First asks any fold
19377
services registered through
19378
[`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
19379
a result, tries to query the [fold node
19380
prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
19381
of the line.
19382
*/
19383
function foldable(state, lineStart, lineEnd) {
19384
    for (let service of state.facet(foldService)) {
19385
        let result = service(state, lineStart, lineEnd);
19386
        if (result)
19387
            return result;
19388
    }
19389
    return syntaxFolding(state, lineStart, lineEnd);
19390
}
19391
function mapRange(range, mapping) {
19392
    let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
19393
    return from >= to ? undefined : { from, to };
19394
}
19395
/**
19396
State effect that can be attached to a transaction to fold the
19397
given range. (You probably only need this in exceptional
19398
circumstances—usually you'll just want to let
19399
[`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
19400
gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
19401
*/
19402
const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
19403
/**
19404
State effect that unfolds the given range (if it was folded).
19405
*/
19406
const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
19407
function selectedLines(view) {
19408
    let lines = [];
19409
    for (let { head } of view.state.selection.ranges) {
19410
        if (lines.some(l => l.from <= head && l.to >= head))
19411
            continue;
19412
        lines.push(view.lineBlockAt(head));
19413
    }
19414
    return lines;
19415
}
19416
/**
19417
The state field that stores the folded ranges (as a [decoration
19418
set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
19419
[`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
19420
[`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
19421
state.
19422
*/
19423
const foldState = /*@__PURE__*/StateField.define({
19424
    create() {
19425
        return Decoration.none;
19426
    },
19427
    update(folded, tr) {
19428
        folded = folded.map(tr.changes);
19429
        for (let e of tr.effects) {
19430
            if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
19431
                let { preparePlaceholder } = tr.state.facet(foldConfig);
19432
                let widget = !preparePlaceholder ? foldWidget :
19433
                    Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
19434
                folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
19435
            }
19436
            else if (e.is(unfoldEffect)) {
19437
                folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
19438
                    filterFrom: e.value.from, filterTo: e.value.to });
19439
            }
19440
        }
19441
        // Clear folded ranges that cover the selection head
19442
        if (tr.selection) {
19443
            let onSelection = false, { head } = tr.selection.main;
19444
            folded.between(head, head, (a, b) => { if (a < head && b > head)
19445
                onSelection = true; });
19446
            if (onSelection)
19447
                folded = folded.update({
19448
                    filterFrom: head,
19449
                    filterTo: head,
19450
                    filter: (a, b) => b <= head || a >= head
19451
                });
19452
        }
19453
        return folded;
19454
    },
19455
    provide: f => EditorView.decorations.from(f),
19456
    toJSON(folded, state) {
19457
        let ranges = [];
19458
        folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });
19459
        return ranges;
19460
    },
19461
    fromJSON(value) {
19462
        if (!Array.isArray(value) || value.length % 2)
19463
            throw new RangeError("Invalid JSON for fold state");
19464
        let ranges = [];
19465
        for (let i = 0; i < value.length;) {
19466
            let from = value[i++], to = value[i++];
19467
            if (typeof from != "number" || typeof to != "number")
19468
                throw new RangeError("Invalid JSON for fold state");
19469
            ranges.push(foldWidget.range(from, to));
19470
        }
19471
        return Decoration.set(ranges, true);
19472
    }
19473
});
19474
function findFold(state, from, to) {
19475
    var _a;
19476
    let found = null;
19477
    (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
19478
        if (!found || found.from > from)
19479
            found = { from, to };
19480
    });
19481
    return found;
19482
}
19483
function foldExists(folded, from, to) {
19484
    let found = false;
19485
    folded.between(from, from, (a, b) => { if (a == from && b == to)
19486
        found = true; });
19487
    return found;
19488
}
19489
function maybeEnable(state, other) {
19490
    return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
19491
}
19492
/**
19493
Fold the lines that are selected, if possible.
19494
*/
19495
const foldCode = view => {
19496
    for (let line of selectedLines(view)) {
19497
        let range = foldable(view.state, line.from, line.to);
19498
        if (range) {
19499
            view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
19500
            return true;
19501
        }
19502
    }
19503
    return false;
19504
};
19505
/**
19506
Unfold folded ranges on selected lines.
19507
*/
19508
const unfoldCode = view => {
19509
    if (!view.state.field(foldState, false))
19510
        return false;
19511
    let effects = [];
19512
    for (let line of selectedLines(view)) {
19513
        let folded = findFold(view.state, line.from, line.to);
19514
        if (folded)
19515
            effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
19516
    }
19517
    if (effects.length)
19518
        view.dispatch({ effects });
19519
    return effects.length > 0;
19520
};
19521
function announceFold(view, range, fold = true) {
19522
    let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
19523
    return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
19524
}
19525
/**
19526
Fold all top-level foldable ranges. Note that, in most cases,
19527
folding information will depend on the [syntax
19528
tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
19529
reliably when the document hasn't been fully parsed (either
19530
because the editor state was only just initialized, or because the
19531
document is so big that the parser decided not to parse it
19532
entirely).
19533
*/
19534
const foldAll = view => {
19535
    let { state } = view, effects = [];
19536
    for (let pos = 0; pos < state.doc.length;) {
19537
        let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
19538
        if (range)
19539
            effects.push(foldEffect.of(range));
19540
        pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
19541
    }
19542
    if (effects.length)
19543
        view.dispatch({ effects: maybeEnable(view.state, effects) });
19544
    return !!effects.length;
19545
};
19546
/**
19547
Unfold all folded code.
19548
*/
19549
const unfoldAll = view => {
19550
    let field = view.state.field(foldState, false);
19551
    if (!field || !field.size)
19552
        return false;
19553
    let effects = [];
19554
    field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
19555
    view.dispatch({ effects });
19556
    return true;
19557
};
19558
/**
19559
Default fold-related key bindings.
19560
 
19561
 - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
19562
 - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
19563
 - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
19564
 - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
19565
*/
19566
const foldKeymap = [
19567
    { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
19568
    { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
19569
    { key: "Ctrl-Alt-[", run: foldAll },
19570
    { key: "Ctrl-Alt-]", run: unfoldAll }
19571
];
19572
const defaultConfig = {
19573
    placeholderDOM: null,
19574
    preparePlaceholder: null,
19575
    placeholderText: "…"
19576
};
19577
const foldConfig = /*@__PURE__*/Facet.define({
19578
    combine(values) { return combineConfig(values, defaultConfig); }
19579
});
19580
/**
19581
Create an extension that configures code folding.
19582
*/
19583
function codeFolding(config) {
19584
    let result = [foldState, baseTheme$1$2];
19585
    return result;
19586
}
19587
function widgetToDOM(view, prepared) {
19588
    let { state } = view, conf = state.facet(foldConfig);
19589
    let onclick = (event) => {
19590
        let line = view.lineBlockAt(view.posAtDOM(event.target));
19591
        let folded = findFold(view.state, line.from, line.to);
19592
        if (folded)
19593
            view.dispatch({ effects: unfoldEffect.of(folded) });
19594
        event.preventDefault();
19595
    };
19596
    if (conf.placeholderDOM)
19597
        return conf.placeholderDOM(view, onclick, prepared);
19598
    let element = document.createElement("span");
19599
    element.textContent = conf.placeholderText;
19600
    element.setAttribute("aria-label", state.phrase("folded code"));
19601
    element.title = state.phrase("unfold");
19602
    element.className = "cm-foldPlaceholder";
19603
    element.onclick = onclick;
19604
    return element;
19605
}
19606
const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {
19607
        toDOM(view) { return widgetToDOM(view, null); }
19608
    } });
19609
class PreparedFoldWidget extends WidgetType {
19610
    constructor(value) {
19611
        super();
19612
        this.value = value;
19613
    }
19614
    eq(other) { return this.value == other.value; }
19615
    toDOM(view) { return widgetToDOM(view, this.value); }
19616
}
19617
const foldGutterDefaults = {
19618
    openText: "⌄",
19619
    closedText: "›",
19620
    markerDOM: null,
19621
    domEventHandlers: {},
19622
    foldingChanged: () => false
19623
};
19624
class FoldMarker extends GutterMarker {
19625
    constructor(config, open) {
19626
        super();
19627
        this.config = config;
19628
        this.open = open;
19629
    }
19630
    eq(other) { return this.config == other.config && this.open == other.open; }
19631
    toDOM(view) {
19632
        if (this.config.markerDOM)
19633
            return this.config.markerDOM(this.open);
19634
        let span = document.createElement("span");
19635
        span.textContent = this.open ? this.config.openText : this.config.closedText;
19636
        span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
19637
        return span;
19638
    }
19639
}
19640
/**
19641
Create an extension that registers a fold gutter, which shows a
19642
fold status indicator before foldable lines (which can be clicked
19643
to fold or unfold the line).
19644
*/
19645
function foldGutter(config = {}) {
19646
    let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
19647
    let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
19648
    let markers = ViewPlugin.fromClass(class {
19649
        constructor(view) {
19650
            this.from = view.viewport.from;
19651
            this.markers = this.buildMarkers(view);
19652
        }
19653
        update(update) {
19654
            if (update.docChanged || update.viewportChanged ||
19655
                update.startState.facet(language) != update.state.facet(language) ||
19656
                update.startState.field(foldState, false) != update.state.field(foldState, false) ||
19657
                syntaxTree(update.startState) != syntaxTree(update.state) ||
19658
                fullConfig.foldingChanged(update))
19659
                this.markers = this.buildMarkers(update.view);
19660
        }
19661
        buildMarkers(view) {
19662
            let builder = new RangeSetBuilder();
19663
            for (let line of view.viewportLineBlocks) {
19664
                let mark = findFold(view.state, line.from, line.to) ? canUnfold
19665
                    : foldable(view.state, line.from, line.to) ? canFold : null;
19666
                if (mark)
19667
                    builder.add(line.from, line.from, mark);
19668
            }
19669
            return builder.finish();
19670
        }
19671
    });
19672
    let { domEventHandlers } = fullConfig;
19673
    return [
19674
        markers,
19675
        gutter({
19676
            class: "cm-foldGutter",
19677
            markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },
19678
            initialSpacer() {
19679
                return new FoldMarker(fullConfig, false);
19680
            },
19681
            domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
19682
                    if (domEventHandlers.click && domEventHandlers.click(view, line, event))
19683
                        return true;
19684
                    let folded = findFold(view.state, line.from, line.to);
19685
                    if (folded) {
19686
                        view.dispatch({ effects: unfoldEffect.of(folded) });
19687
                        return true;
19688
                    }
19689
                    let range = foldable(view.state, line.from, line.to);
19690
                    if (range) {
19691
                        view.dispatch({ effects: foldEffect.of(range) });
19692
                        return true;
19693
                    }
19694
                    return false;
19695
                } })
19696
        }),
19697
        codeFolding()
19698
    ];
19699
}
19700
const baseTheme$1$2 = /*@__PURE__*/EditorView.baseTheme({
19701
    ".cm-foldPlaceholder": {
19702
        backgroundColor: "#eee",
19703
        border: "1px solid #ddd",
19704
        color: "#888",
19705
        borderRadius: ".2em",
19706
        margin: "0 1px",
19707
        padding: "0 1px",
19708
        cursor: "pointer"
19709
    },
19710
    ".cm-foldGutter span": {
19711
        padding: "0 1px",
19712
        cursor: "pointer"
19713
    }
19714
});
19715
 
19716
/**
19717
A highlight style associates CSS styles with higlighting
19718
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
19719
*/
19720
class HighlightStyle {
19721
    constructor(
19722
    /**
19723
    The tag styles used to create this highlight style.
19724
    */
19725
    specs, options) {
19726
        this.specs = specs;
19727
        let modSpec;
19728
        function def(spec) {
19729
            let cls = StyleModule.newName();
19730
            (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
19731
            return cls;
19732
        }
19733
        const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
19734
        const scopeOpt = options.scope;
19735
        this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
19736
            : scopeOpt ? (type) => type == scopeOpt : undefined;
19737
        this.style = tagHighlighter(specs.map(style => ({
19738
            tag: style.tag,
19739
            class: style.class || def(Object.assign({}, style, { tag: null }))
19740
        })), {
19741
            all,
19742
        }).style;
19743
        this.module = modSpec ? new StyleModule(modSpec) : null;
19744
        this.themeType = options.themeType;
19745
    }
19746
    /**
19747
    Create a highlighter style that associates the given styles to
19748
    the given tags. The specs must be objects that hold a style tag
19749
    or array of tags in their `tag` property, and either a single
19750
    `class` property providing a static CSS class (for highlighter
19751
    that rely on external styling), or a
19752
    [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
19753
    set of CSS properties (which define the styling for those tags).
19754
 
19755
    The CSS rules created for a highlighter will be emitted in the
19756
    order of the spec's properties. That means that for elements that
19757
    have multiple tags associated with them, styles defined further
19758
    down in the list will have a higher CSS precedence than styles
19759
    defined earlier.
19760
    */
19761
    static define(specs, options) {
19762
        return new HighlightStyle(specs, options || {});
19763
    }
19764
}
19765
const highlighterFacet = /*@__PURE__*/Facet.define();
19766
const fallbackHighlighter = /*@__PURE__*/Facet.define({
19767
    combine(values) { return values.length ? [values[0]] : null; }
19768
});
19769
function getHighlighters(state) {
19770
    let main = state.facet(highlighterFacet);
19771
    return main.length ? main : state.facet(fallbackHighlighter);
19772
}
19773
/**
19774
Wrap a highlighter in an editor extension that uses it to apply
19775
syntax highlighting to the editor content.
19776
 
19777
When multiple (non-fallback) styles are provided, the styling
19778
applied is the union of the classes they emit.
19779
*/
19780
function syntaxHighlighting(highlighter, options) {
19781
    let ext = [treeHighlighter], themeType;
19782
    if (highlighter instanceof HighlightStyle) {
19783
        if (highlighter.module)
19784
            ext.push(EditorView.styleModule.of(highlighter.module));
19785
        themeType = highlighter.themeType;
19786
    }
19787
    if (options === null || options === void 0 ? void 0 : options.fallback)
19788
        ext.push(fallbackHighlighter.of(highlighter));
19789
    else if (themeType)
19790
        ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
19791
            return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
19792
        }));
19793
    else
19794
        ext.push(highlighterFacet.of(highlighter));
19795
    return ext;
19796
}
19797
class TreeHighlighter {
19798
    constructor(view) {
19799
        this.markCache = Object.create(null);
19800
        this.tree = syntaxTree(view.state);
19801
        this.decorations = this.buildDeco(view, getHighlighters(view.state));
19802
        this.decoratedTo = view.viewport.to;
19803
    }
19804
    update(update) {
19805
        let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
19806
        let styleChange = highlighters != getHighlighters(update.startState);
19807
        let { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1);
19808
        if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
19809
            this.decorations = this.decorations.map(update.changes);
19810
            this.decoratedTo = decoratedToMapped;
19811
        }
19812
        else if (tree != this.tree || update.viewportChanged || styleChange) {
19813
            this.tree = tree;
19814
            this.decorations = this.buildDeco(update.view, highlighters);
19815
            this.decoratedTo = viewport.to;
19816
        }
19817
    }
19818
    buildDeco(view, highlighters) {
19819
        if (!highlighters || !this.tree.length)
19820
            return Decoration.none;
19821
        let builder = new RangeSetBuilder();
19822
        for (let { from, to } of view.visibleRanges) {
19823
            highlightTree(this.tree, highlighters, (from, to, style) => {
19824
                builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
19825
            }, from, to);
19826
        }
19827
        return builder.finish();
19828
    }
19829
}
19830
const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {
19831
    decorations: v => v.decorations
19832
}));
19833
/**
19834
A default highlight style (works well with light themes).
19835
*/
19836
const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([
19837
    { tag: tags$1.meta,
19838
        color: "#404740" },
19839
    { tag: tags$1.link,
19840
        textDecoration: "underline" },
19841
    { tag: tags$1.heading,
19842
        textDecoration: "underline",
19843
        fontWeight: "bold" },
19844
    { tag: tags$1.emphasis,
19845
        fontStyle: "italic" },
19846
    { tag: tags$1.strong,
19847
        fontWeight: "bold" },
19848
    { tag: tags$1.strikethrough,
19849
        textDecoration: "line-through" },
19850
    { tag: tags$1.keyword,
19851
        color: "#708" },
19852
    { tag: [tags$1.atom, tags$1.bool, tags$1.url, tags$1.contentSeparator, tags$1.labelName],
19853
        color: "#219" },
19854
    { tag: [tags$1.literal, tags$1.inserted],
19855
        color: "#164" },
19856
    { tag: [tags$1.string, tags$1.deleted],
19857
        color: "#a11" },
19858
    { tag: [tags$1.regexp, tags$1.escape, /*@__PURE__*/tags$1.special(tags$1.string)],
19859
        color: "#e40" },
19860
    { tag: /*@__PURE__*/tags$1.definition(tags$1.variableName),
19861
        color: "#00f" },
19862
    { tag: /*@__PURE__*/tags$1.local(tags$1.variableName),
19863
        color: "#30a" },
19864
    { tag: [tags$1.typeName, tags$1.namespace],
19865
        color: "#085" },
19866
    { tag: tags$1.className,
19867
        color: "#167" },
19868
    { tag: [/*@__PURE__*/tags$1.special(tags$1.variableName), tags$1.macroName],
19869
        color: "#256" },
19870
    { tag: /*@__PURE__*/tags$1.definition(tags$1.propertyName),
19871
        color: "#00c" },
19872
    { tag: tags$1.comment,
19873
        color: "#940" },
19874
    { tag: tags$1.invalid,
19875
        color: "#f00" }
19876
]);
19877
 
19878
const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({
19879
    "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
19880
    "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
19881
});
19882
const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
19883
const bracketMatchingConfig = /*@__PURE__*/Facet.define({
19884
    combine(configs) {
19885
        return combineConfig(configs, {
19886
            afterCursor: true,
19887
            brackets: DefaultBrackets,
19888
            maxScanDistance: DefaultScanDist,
19889
            renderMatch: defaultRenderMatch
19890
        });
19891
    }
19892
});
19893
const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" });
19894
function defaultRenderMatch(match) {
19895
    let decorations = [];
19896
    let mark = match.matched ? matchingMark : nonmatchingMark;
19897
    decorations.push(mark.range(match.start.from, match.start.to));
19898
    if (match.end)
19899
        decorations.push(mark.range(match.end.from, match.end.to));
19900
    return decorations;
19901
}
19902
const bracketMatchingState = /*@__PURE__*/StateField.define({
19903
    create() { return Decoration.none; },
19904
    update(deco, tr) {
19905
        if (!tr.docChanged && !tr.selection)
19906
            return deco;
19907
        let decorations = [];
19908
        let config = tr.state.facet(bracketMatchingConfig);
19909
        for (let range of tr.state.selection.ranges) {
19910
            if (!range.empty)
19911
                continue;
19912
            let match = matchBrackets(tr.state, range.head, -1, config)
19913
                || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
19914
                || (config.afterCursor &&
19915
                    (matchBrackets(tr.state, range.head, 1, config) ||
19916
                        (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
19917
            if (match)
19918
                decorations = decorations.concat(config.renderMatch(match, tr.state));
19919
        }
19920
        return Decoration.set(decorations, true);
19921
    },
19922
    provide: f => EditorView.decorations.from(f)
19923
});
19924
const bracketMatchingUnique = [
19925
    bracketMatchingState,
19926
    baseTheme$3
19927
];
19928
/**
19929
Create an extension that enables bracket matching. Whenever the
19930
cursor is next to a bracket, that bracket and the one it matches
19931
are highlighted. Or, when no matching bracket is found, another
19932
highlighting style is used to indicate this.
19933
*/
19934
function bracketMatching(config = {}) {
19935
    return [bracketMatchingConfig.of(config), bracketMatchingUnique];
19936
}
19937
/**
19938
When larger syntax nodes, such as HTML tags, are marked as
19939
opening/closing, it can be a bit messy to treat the whole node as
19940
a matchable bracket. This node prop allows you to define, for such
19941
a node, a ‘handle’—the part of the node that is highlighted, and
19942
that the cursor must be on to activate highlighting in the first
19943
place.
19944
*/
19945
const bracketMatchingHandle = /*@__PURE__*/new NodeProp();
19946
function matchingNodes(node, dir, brackets) {
19947
    let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
19948
    if (byProp)
19949
        return byProp;
19950
    if (node.name.length == 1) {
19951
        let index = brackets.indexOf(node.name);
19952
        if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
19953
            return [brackets[index + dir]];
19954
    }
19955
    return null;
19956
}
19957
function findHandle(node) {
19958
    let hasHandle = node.type.prop(bracketMatchingHandle);
19959
    return hasHandle ? hasHandle(node.node) : node;
19960
}
19961
/**
19962
Find the matching bracket for the token at `pos`, scanning
19963
direction `dir`. Only the `brackets` and `maxScanDistance`
19964
properties are used from `config`, if given. Returns null if no
19965
bracket was found at `pos`, or a match result otherwise.
19966
*/
19967
function matchBrackets(state, pos, dir, config = {}) {
19968
    let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
19969
    let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
19970
    for (let cur = node; cur; cur = cur.parent) {
19971
        let matches = matchingNodes(cur.type, dir, brackets);
19972
        if (matches && cur.from < cur.to) {
19973
            let handle = findHandle(cur);
19974
            if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))
19975
                return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);
19976
        }
19977
    }
19978
    return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
19979
}
19980
function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
19981
    let parent = token.parent, firstToken = { from: handle.from, to: handle.to };
19982
    let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
19983
    if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
19984
        do {
19985
            if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
19986
                if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
19987
                    let endHandle = findHandle(cursor);
19988
                    return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : undefined, matched: true };
19989
                }
19990
                else if (matchingNodes(cursor.type, dir, brackets)) {
19991
                    depth++;
19992
                }
19993
                else if (matchingNodes(cursor.type, -dir, brackets)) {
19994
                    if (depth == 0) {
19995
                        let endHandle = findHandle(cursor);
19996
                        return {
19997
                            start: firstToken,
19998
                            end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : undefined,
19999
                            matched: false
20000
                        };
20001
                    }
20002
                    depth--;
20003
                }
20004
            }
20005
        } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
20006
    return { start: firstToken, matched: false };
20007
}
20008
function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
20009
    let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
20010
    let bracket = brackets.indexOf(startCh);
20011
    if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
20012
        return null;
20013
    let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
20014
    let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
20015
    for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
20016
        let text = iter.value;
20017
        if (dir < 0)
20018
            distance += text.length;
20019
        let basePos = pos + distance * dir;
20020
        for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
20021
            let found = brackets.indexOf(text[pos]);
20022
            if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)
20023
                continue;
20024
            if ((found % 2 == 0) == (dir > 0)) {
20025
                depth++;
20026
            }
20027
            else if (depth == 1) { // Closing
20028
                return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
20029
            }
20030
            else {
20031
                depth--;
20032
            }
20033
        }
20034
        if (dir > 0)
20035
            distance += text.length;
20036
    }
20037
    return iter.done ? { start: startToken, matched: false } : null;
20038
}
20039
const noTokens = /*@__PURE__*/Object.create(null);
20040
const typeArray = [NodeType.none];
20041
const warned = [];
20042
// Cache of node types by name and tags
20043
const byTag = /*@__PURE__*/Object.create(null);
20044
const defaultTable = /*@__PURE__*/Object.create(null);
20045
for (let [legacyName, name] of [
20046
    ["variable", "variableName"],
20047
    ["variable-2", "variableName.special"],
20048
    ["string-2", "string.special"],
20049
    ["def", "variableName.definition"],
20050
    ["tag", "tagName"],
20051
    ["attribute", "attributeName"],
20052
    ["type", "typeName"],
20053
    ["builtin", "variableName.standard"],
20054
    ["qualifier", "modifier"],
20055
    ["error", "invalid"],
20056
    ["header", "heading"],
20057
    ["property", "propertyName"]
20058
])
20059
    defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
20060
function warnForPart(part, msg) {
20061
    if (warned.indexOf(part) > -1)
20062
        return;
20063
    warned.push(part);
20064
    console.warn(msg);
20065
}
20066
function createTokenType(extra, tagStr) {
20067
    let tags$1$1 = [];
20068
    for (let name of tagStr.split(" ")) {
20069
        let found = [];
20070
        for (let part of name.split(".")) {
20071
            let value = (extra[part] || tags$1[part]);
20072
            if (!value) {
20073
                warnForPart(part, `Unknown highlighting tag ${part}`);
20074
            }
20075
            else if (typeof value == "function") {
20076
                if (!found.length)
20077
                    warnForPart(part, `Modifier ${part} used at start of tag`);
20078
                else
20079
                    found = found.map(value);
20080
            }
20081
            else {
20082
                if (found.length)
20083
                    warnForPart(part, `Tag ${part} used as modifier`);
20084
                else
20085
                    found = Array.isArray(value) ? value : [value];
20086
            }
20087
        }
20088
        for (let tag of found)
20089
            tags$1$1.push(tag);
20090
    }
20091
    if (!tags$1$1.length)
20092
        return 0;
20093
    let name = tagStr.replace(/ /g, "_"), key = name + " " + tags$1$1.map(t => t.id);
20094
    let known = byTag[key];
20095
    if (known)
20096
        return known.id;
20097
    let type = byTag[key] = NodeType.define({
20098
        id: typeArray.length,
20099
        name,
20100
        props: [styleTags({ [name]: tags$1$1 })]
20101
    });
20102
    typeArray.push(type);
20103
    return type.id;
20104
}
20105
({
20106
    rtl: /*@__PURE__*/Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "rtl" }, bidiIsolate: Direction.RTL }),
1441 ariadna 20107
    ltr: /*@__PURE__*/Decoration.mark({ class: "cm-iso", inclusive: true, attributes: { dir: "ltr" }, bidiIsolate: Direction.LTR })});
1 efrain 20108
 
20109
/**
20110
Comment or uncomment the current selection. Will use line comments
20111
if available, otherwise falling back to block comments.
20112
*/
20113
const toggleComment = target => {
20114
    let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from);
20115
    return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false;
20116
};
20117
function command(f, option) {
20118
    return ({ state, dispatch }) => {
20119
        if (state.readOnly)
20120
            return false;
20121
        let tr = f(option, state);
20122
        if (!tr)
20123
            return false;
20124
        dispatch(state.update(tr));
20125
        return true;
20126
    };
20127
}
20128
/**
20129
Comment or uncomment the current selection using line comments.
20130
The line comment syntax is taken from the
20131
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
20132
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
20133
*/
20134
const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */);
20135
/**
20136
Comment or uncomment the current selection using block comments.
20137
The block comment syntax is taken from the
20138
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
20139
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
20140
*/
20141
const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */);
20142
/**
20143
Comment or uncomment the lines around the current selection using
20144
block comments.
20145
*/
20146
const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */);
20147
function getConfig(state, pos) {
20148
    let data = state.languageDataAt("commentTokens", pos);
20149
    return data.length ? data[0] : {};
20150
}
20151
const SearchMargin = 50;
20152
/**
20153
Determines if the given range is block-commented in the given
20154
state.
20155
*/
20156
function findBlockComment(state, { open, close }, from, to) {
20157
    let textBefore = state.sliceDoc(from - SearchMargin, from);
20158
    let textAfter = state.sliceDoc(to, to + SearchMargin);
20159
    let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
20160
    let beforeOff = textBefore.length - spaceBefore;
20161
    if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&
20162
        textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
20163
        return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
20164
            close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };
20165
    }
20166
    let startText, endText;
20167
    if (to - from <= 2 * SearchMargin) {
20168
        startText = endText = state.sliceDoc(from, to);
20169
    }
20170
    else {
20171
        startText = state.sliceDoc(from, from + SearchMargin);
20172
        endText = state.sliceDoc(to - SearchMargin, to);
20173
    }
20174
    let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
20175
    let endOff = endText.length - endSpace - close.length;
20176
    if (startText.slice(startSpace, startSpace + open.length) == open &&
20177
        endText.slice(endOff, endOff + close.length) == close) {
20178
        return { open: { pos: from + startSpace + open.length,
20179
                margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },
20180
            close: { pos: to - endSpace - close.length,
20181
                margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };
20182
    }
20183
    return null;
20184
}
20185
function selectedLineRanges(state) {
20186
    let ranges = [];
20187
    for (let r of state.selection.ranges) {
20188
        let fromLine = state.doc.lineAt(r.from);
20189
        let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
1441 ariadna 20190
        if (toLine.from > fromLine.from && toLine.from == r.to)
20191
            toLine = r.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r.to - 1);
1 efrain 20192
        let last = ranges.length - 1;
20193
        if (last >= 0 && ranges[last].to > fromLine.from)
20194
            ranges[last].to = toLine.to;
20195
        else
20196
            ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
20197
    }
20198
    return ranges;
20199
}
20200
// Performs toggle, comment and uncomment of block comments in
20201
// languages that support them.
20202
function changeBlockComment(option, state, ranges = state.selection.ranges) {
20203
    let tokens = ranges.map(r => getConfig(state, r.from).block);
20204
    if (!tokens.every(c => c))
20205
        return null;
20206
    let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
20207
    if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) {
20208
        return { changes: state.changes(ranges.map((range, i) => {
20209
                if (comments[i])
20210
                    return [];
20211
                return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }];
20212
            })) };
20213
    }
20214
    else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) {
20215
        let changes = [];
20216
        for (let i = 0, comment; i < comments.length; i++)
20217
            if (comment = comments[i]) {
20218
                let token = tokens[i], { open, close } = comment;
20219
                changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
20220
            }
20221
        return { changes };
20222
    }
20223
    return null;
20224
}
20225
// Performs toggle, comment and uncomment of line comments.
20226
function changeLineComment(option, state, ranges = state.selection.ranges) {
20227
    let lines = [];
20228
    let prevLine = -1;
20229
    for (let { from, to } of ranges) {
20230
        let startI = lines.length, minIndent = 1e9;
20231
        let token = getConfig(state, from).line;
20232
        if (!token)
20233
            continue;
20234
        for (let pos = from; pos <= to;) {
20235
            let line = state.doc.lineAt(pos);
20236
            if (line.from > prevLine && (from == to || to > line.from)) {
20237
                prevLine = line.from;
20238
                let indent = /^\s*/.exec(line.text)[0].length;
20239
                let empty = indent == line.length;
20240
                let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1;
20241
                if (indent < line.text.length && indent < minIndent)
20242
                    minIndent = indent;
20243
                lines.push({ line, comment, token, indent, empty, single: false });
20244
            }
20245
            pos = line.to + 1;
20246
        }
20247
        if (minIndent < 1e9)
20248
            for (let i = startI; i < lines.length; i++)
20249
                if (lines[i].indent < lines[i].line.text.length)
20250
                    lines[i].indent = minIndent;
20251
        if (lines.length == startI + 1)
20252
            lines[startI].single = true;
20253
    }
20254
    if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {
20255
        let changes = [];
20256
        for (let { line, token, indent, empty, single } of lines)
20257
            if (single || !empty)
20258
                changes.push({ from: line.from + indent, insert: token + " " });
20259
        let changeSet = state.changes(changes);
20260
        return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
20261
    }
20262
    else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) {
20263
        let changes = [];
20264
        for (let { line, comment, token } of lines)
20265
            if (comment >= 0) {
20266
                let from = line.from + comment, to = from + token.length;
20267
                if (line.text[to - line.from] == " ")
20268
                    to++;
20269
                changes.push({ from, to });
20270
            }
20271
        return { changes };
20272
    }
20273
    return null;
20274
}
20275
 
20276
const fromHistory = /*@__PURE__*/Annotation.define();
20277
/**
20278
Transaction annotation that will prevent that transaction from
20279
being combined with other transactions in the undo history. Given
20280
`"before"`, it'll prevent merging with previous transactions. With
20281
`"after"`, subsequent transactions won't be combined with this
20282
one. With `"full"`, the transaction is isolated on both sides.
20283
*/
20284
const isolateHistory = /*@__PURE__*/Annotation.define();
20285
/**
20286
This facet provides a way to register functions that, given a
20287
transaction, provide a set of effects that the history should
20288
store when inverting the transaction. This can be used to
20289
integrate some kinds of effects in the history, so that they can
20290
be undone (and redone again).
20291
*/
20292
const invertedEffects = /*@__PURE__*/Facet.define();
20293
const historyConfig = /*@__PURE__*/Facet.define({
20294
    combine(configs) {
20295
        return combineConfig(configs, {
20296
            minDepth: 100,
20297
            newGroupDelay: 500,
20298
            joinToEvent: (_t, isAdjacent) => isAdjacent,
20299
        }, {
20300
            minDepth: Math.max,
20301
            newGroupDelay: Math.min,
20302
            joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
20303
        });
20304
    }
20305
});
20306
const historyField_ = /*@__PURE__*/StateField.define({
20307
    create() {
20308
        return HistoryState.empty;
20309
    },
20310
    update(state, tr) {
20311
        let config = tr.state.facet(historyConfig);
20312
        let fromHist = tr.annotation(fromHistory);
20313
        if (fromHist) {
20314
            let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side;
20315
            let other = from == 0 /* BranchName.Done */ ? state.undone : state.done;
20316
            if (item)
20317
                other = updateBranch(other, other.length, config.minDepth, item);
20318
            else
20319
                other = addSelection(other, tr.startState.selection);
20320
            return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest);
20321
        }
20322
        let isolate = tr.annotation(isolateHistory);
20323
        if (isolate == "full" || isolate == "before")
20324
            state = state.isolate();
20325
        if (tr.annotation(Transaction.addToHistory) === false)
20326
            return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
20327
        let event = HistEvent.fromTransaction(tr);
20328
        let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
20329
        if (event)
20330
            state = state.addChanges(event, time, userEvent, config, tr);
20331
        else if (tr.selection)
20332
            state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
20333
        if (isolate == "full" || isolate == "after")
20334
            state = state.isolate();
20335
        return state;
20336
    },
20337
    toJSON(value) {
20338
        return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) };
20339
    },
20340
    fromJSON(json) {
20341
        return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
20342
    }
20343
});
20344
/**
20345
Create a history extension with the given configuration.
20346
*/
20347
function history(config = {}) {
20348
    return [
20349
        historyField_,
20350
        historyConfig.of(config),
20351
        EditorView.domEventHandlers({
20352
            beforeinput(e, view) {
20353
                let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
20354
                if (!command)
20355
                    return false;
20356
                e.preventDefault();
20357
                return command(view);
20358
            }
20359
        })
20360
    ];
20361
}
20362
function cmd(side, selection) {
20363
    return function ({ state, dispatch }) {
20364
        if (!selection && state.readOnly)
20365
            return false;
20366
        let historyState = state.field(historyField_, false);
20367
        if (!historyState)
20368
            return false;
20369
        let tr = historyState.pop(side, state, selection);
20370
        if (!tr)
20371
            return false;
20372
        dispatch(tr);
20373
        return true;
20374
    };
20375
}
20376
/**
20377
Undo a single group of history events. Returns false if no group
20378
was available.
20379
*/
20380
const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false);
20381
/**
20382
Redo a group of history events. Returns false if no group was
20383
available.
20384
*/
20385
const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false);
20386
/**
20387
Undo a change or selection change.
20388
*/
20389
const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true);
20390
/**
20391
Redo a change or selection change.
20392
*/
20393
const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true);
20394
// History events store groups of changes or effects that need to be
20395
// undone/redone together.
20396
class HistEvent {
20397
    constructor(
20398
    // The changes in this event. Normal events hold at least one
20399
    // change or effect. But it may be necessary to store selection
20400
    // events before the first change, in which case a special type of
20401
    // instance is created which doesn't hold any changes, with
20402
    // changes == startSelection == undefined
20403
    changes,
20404
    // The effects associated with this event
20405
    effects,
20406
    // Accumulated mapping (from addToHistory==false) that should be
20407
    // applied to events below this one.
20408
    mapped,
20409
    // The selection before this event
20410
    startSelection,
20411
    // Stores selection changes after this event, to be used for
20412
    // selection undo/redo.
20413
    selectionsAfter) {
20414
        this.changes = changes;
20415
        this.effects = effects;
20416
        this.mapped = mapped;
20417
        this.startSelection = startSelection;
20418
        this.selectionsAfter = selectionsAfter;
20419
    }
20420
    setSelAfter(after) {
20421
        return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
20422
    }
20423
    toJSON() {
20424
        var _a, _b, _c;
20425
        return {
20426
            changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),
20427
            mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
20428
            startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
20429
            selectionsAfter: this.selectionsAfter.map(s => s.toJSON())
20430
        };
20431
    }
20432
    static fromJSON(json) {
20433
        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));
20434
    }
20435
    // This does not check `addToHistory` and such, it assumes the
20436
    // transaction needs to be converted to an item. Returns null when
20437
    // there are no changes or effects in the transaction.
20438
    static fromTransaction(tr, selection) {
20439
        let effects = none$1;
20440
        for (let invert of tr.startState.facet(invertedEffects)) {
20441
            let result = invert(tr);
20442
            if (result.length)
20443
                effects = effects.concat(result);
20444
        }
20445
        if (!effects.length && tr.changes.empty)
20446
            return null;
20447
        return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none$1);
20448
    }
20449
    static selection(selections) {
20450
        return new HistEvent(undefined, none$1, undefined, undefined, selections);
20451
    }
20452
}
20453
function updateBranch(branch, to, maxLen, newEvent) {
20454
    let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
20455
    let newBranch = branch.slice(start, to);
20456
    newBranch.push(newEvent);
20457
    return newBranch;
20458
}
20459
function isAdjacent(a, b) {
20460
    let ranges = [], isAdjacent = false;
20461
    a.iterChangedRanges((f, t) => ranges.push(f, t));
20462
    b.iterChangedRanges((_f, _t, f, t) => {
20463
        for (let i = 0; i < ranges.length;) {
20464
            let from = ranges[i++], to = ranges[i++];
20465
            if (t >= from && f <= to)
20466
                isAdjacent = true;
20467
        }
20468
    });
20469
    return isAdjacent;
20470
}
20471
function eqSelectionShape(a, b) {
20472
    return a.ranges.length == b.ranges.length &&
20473
        a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
20474
}
20475
function conc(a, b) {
20476
    return !a.length ? b : !b.length ? a : a.concat(b);
20477
}
20478
const none$1 = [];
20479
const MaxSelectionsPerEvent = 200;
20480
function addSelection(branch, selection) {
20481
    if (!branch.length) {
20482
        return [HistEvent.selection([selection])];
20483
    }
20484
    else {
20485
        let lastEvent = branch[branch.length - 1];
20486
        let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
20487
        if (sels.length && sels[sels.length - 1].eq(selection))
20488
            return branch;
20489
        sels.push(selection);
20490
        return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
20491
    }
20492
}
20493
// Assumes the top item has one or more selectionAfter values
20494
function popSelection(branch) {
20495
    let last = branch[branch.length - 1];
20496
    let newBranch = branch.slice();
20497
    newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
20498
    return newBranch;
20499
}
20500
// Add a mapping to the top event in the given branch. If this maps
20501
// away all the changes and effects in that item, drop it and
20502
// propagate the mapping to the next item.
20503
function addMappingToBranch(branch, mapping) {
20504
    if (!branch.length)
20505
        return branch;
20506
    let length = branch.length, selections = none$1;
20507
    while (length) {
20508
        let event = mapEvent(branch[length - 1], mapping, selections);
20509
        if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping
20510
            let result = branch.slice(0, length);
20511
            result[length - 1] = event;
20512
            return result;
20513
        }
20514
        else { // Drop this event, since there's no changes or effects left
20515
            mapping = event.mapped;
20516
            length--;
20517
            selections = event.selectionsAfter;
20518
        }
20519
    }
20520
    return selections.length ? [HistEvent.selection(selections)] : none$1;
20521
}
20522
function mapEvent(event, mapping, extraSelections) {
20523
    let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$1, extraSelections);
20524
    // Change-less events don't store mappings (they are always the last event in a branch)
20525
    if (!event.changes)
20526
        return HistEvent.selection(selections);
20527
    let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
20528
    let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
20529
    return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
20530
}
20531
const joinableUserEvent = /^(input\.type|delete)($|\.)/;
20532
class HistoryState {
20533
    constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {
20534
        this.done = done;
20535
        this.undone = undone;
20536
        this.prevTime = prevTime;
20537
        this.prevUserEvent = prevUserEvent;
20538
    }
20539
    isolate() {
20540
        return this.prevTime ? new HistoryState(this.done, this.undone) : this;
20541
    }
20542
    addChanges(event, time, userEvent, config, tr) {
20543
        let done = this.done, lastEvent = done[done.length - 1];
20544
        if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes &&
20545
            (!userEvent || joinableUserEvent.test(userEvent)) &&
20546
            ((!lastEvent.selectionsAfter.length &&
20547
                time - this.prevTime < config.newGroupDelay &&
20548
                config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes))) ||
20549
                // For compose (but not compose.start) events, always join with previous event
20550
                userEvent == "input.type.compose")) {
1441 ariadna 20551
            done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$1));
1 efrain 20552
        }
20553
        else {
20554
            done = updateBranch(done, done.length, config.minDepth, event);
20555
        }
20556
        return new HistoryState(done, none$1, time, userEvent);
20557
    }
20558
    addSelection(selection, time, userEvent, newGroupDelay) {
20559
        let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$1;
20560
        if (last.length > 0 &&
20561
            time - this.prevTime < newGroupDelay &&
20562
            userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) &&
20563
            eqSelectionShape(last[last.length - 1], selection))
20564
            return this;
20565
        return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
20566
    }
20567
    addMapping(mapping) {
20568
        return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
20569
    }
20570
    pop(side, state, onlySelection) {
20571
        let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone;
20572
        if (branch.length == 0)
20573
            return null;
20574
        let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || state.selection;
20575
        if (onlySelection && event.selectionsAfter.length) {
20576
            return state.update({
20577
                selection: event.selectionsAfter[event.selectionsAfter.length - 1],
20578
                annotations: fromHistory.of({ side, rest: popSelection(branch), selection }),
20579
                userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo",
20580
                scrollIntoView: true
20581
            });
20582
        }
20583
        else if (!event.changes) {
20584
            return null;
20585
        }
20586
        else {
20587
            let rest = branch.length == 1 ? none$1 : branch.slice(0, branch.length - 1);
20588
            if (event.mapped)
20589
                rest = addMappingToBranch(rest, event.mapped);
20590
            return state.update({
20591
                changes: event.changes,
20592
                selection: event.startSelection,
20593
                effects: event.effects,
20594
                annotations: fromHistory.of({ side, rest, selection }),
20595
                filter: false,
20596
                userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo",
20597
                scrollIntoView: true
20598
            });
20599
        }
20600
    }
20601
}
20602
HistoryState.empty = /*@__PURE__*/new HistoryState(none$1, none$1);
20603
/**
20604
Default key bindings for the undo history.
20605
 
20606
- Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo).
20607
- Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo).
20608
- Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection).
20609
- Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection).
20610
*/
20611
const historyKeymap = [
20612
    { key: "Mod-z", run: undo, preventDefault: true },
20613
    { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
20614
    { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
20615
    { key: "Mod-u", run: undoSelection, preventDefault: true },
20616
    { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
20617
];
20618
 
20619
function updateSel(sel, by) {
20620
    return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
20621
}
20622
function setSel(state, selection) {
20623
    return state.update({ selection, scrollIntoView: true, userEvent: "select" });
20624
}
20625
function moveSel({ state, dispatch }, how) {
20626
    let selection = updateSel(state.selection, how);
20627
    if (selection.eq(state.selection, true))
20628
        return false;
20629
    dispatch(setSel(state, selection));
20630
    return true;
20631
}
20632
function rangeEnd(range, forward) {
20633
    return EditorSelection.cursor(forward ? range.to : range.from);
20634
}
20635
function cursorByChar(view, forward) {
20636
    return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
20637
}
20638
function ltrAtCursor(view) {
20639
    return view.textDirectionAt(view.state.selection.main.head) == Direction.LTR;
20640
}
20641
/**
20642
Move the selection one character to the left (which is backward in
20643
left-to-right text, forward in right-to-left text).
20644
*/
20645
const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));
20646
/**
20647
Move the selection one character to the right.
20648
*/
20649
const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));
20650
function cursorByGroup(view, forward) {
20651
    return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
20652
}
20653
/**
20654
Move the selection to the left across one group of word or
20655
non-word (but also non-space) characters.
20656
*/
20657
const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));
20658
/**
20659
Move the selection one group to the right.
20660
*/
20661
const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));
20662
function interestingNode(state, node, bracketProp) {
20663
    if (node.type.prop(bracketProp))
20664
        return true;
20665
    let len = node.to - node.from;
20666
    return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
20667
}
20668
function moveBySyntax(state, start, forward) {
20669
    let pos = syntaxTree(state).resolveInner(start.head);
20670
    let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
20671
    // Scan forward through child nodes to see if there's an interesting
20672
    // node ahead.
20673
    for (let at = start.head;;) {
20674
        let next = forward ? pos.childAfter(at) : pos.childBefore(at);
20675
        if (!next)
20676
            break;
20677
        if (interestingNode(state, next, bracketProp))
20678
            pos = next;
20679
        else
20680
            at = forward ? next.to : next.from;
20681
    }
20682
    let bracket = pos.type.prop(bracketProp), match, newPos;
20683
    if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
20684
        newPos = forward ? match.end.to : match.end.from;
20685
    else
20686
        newPos = forward ? pos.to : pos.from;
20687
    return EditorSelection.cursor(newPos, forward ? -1 : 1);
20688
}
20689
/**
20690
Move the cursor over the next syntactic element to the left.
20691
*/
20692
const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20693
/**
20694
Move the cursor over the next syntactic element to the right.
20695
*/
20696
const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20697
function cursorByLine(view, forward) {
20698
    return moveSel(view, range => {
20699
        if (!range.empty)
20700
            return rangeEnd(range, forward);
20701
        let moved = view.moveVertically(range, forward);
20702
        return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
20703
    });
20704
}
20705
/**
20706
Move the selection one line up.
20707
*/
20708
const cursorLineUp = view => cursorByLine(view, false);
20709
/**
20710
Move the selection one line down.
20711
*/
20712
const cursorLineDown = view => cursorByLine(view, true);
20713
function pageInfo(view) {
20714
    let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
20715
    let marginTop = 0, marginBottom = 0, height;
20716
    if (selfScroll) {
20717
        for (let source of view.state.facet(EditorView.scrollMargins)) {
20718
            let margins = source(view);
20719
            if (margins === null || margins === void 0 ? void 0 : margins.top)
20720
                marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
20721
            if (margins === null || margins === void 0 ? void 0 : margins.bottom)
20722
                marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
20723
        }
20724
        height = view.scrollDOM.clientHeight - marginTop - marginBottom;
20725
    }
20726
    else {
20727
        height = (view.dom.ownerDocument.defaultView || window).innerHeight;
20728
    }
20729
    return { marginTop, marginBottom, selfScroll,
20730
        height: Math.max(view.defaultLineHeight, height - 5) };
20731
}
20732
function cursorByPage(view, forward) {
20733
    let page = pageInfo(view);
20734
    let { state } = view, selection = updateSel(state.selection, range => {
20735
        return range.empty ? view.moveVertically(range, forward, page.height)
20736
            : rangeEnd(range, forward);
20737
    });
20738
    if (selection.eq(state.selection))
20739
        return false;
20740
    let effect;
20741
    if (page.selfScroll) {
20742
        let startPos = view.coordsAtPos(state.selection.main.head);
20743
        let scrollRect = view.scrollDOM.getBoundingClientRect();
20744
        let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
20745
        if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
20746
            effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
20747
    }
20748
    view.dispatch(setSel(state, selection), { effects: effect });
20749
    return true;
20750
}
20751
/**
20752
Move the selection one page up.
20753
*/
20754
const cursorPageUp = view => cursorByPage(view, false);
20755
/**
20756
Move the selection one page down.
20757
*/
20758
const cursorPageDown = view => cursorByPage(view, true);
20759
function moveByLineBoundary(view, start, forward) {
20760
    let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
20761
    if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
20762
        moved = view.moveToLineBoundary(start, forward, false);
20763
    if (!forward && moved.head == line.from && line.length) {
20764
        let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
20765
        if (space && start.head != line.from + space)
20766
            moved = EditorSelection.cursor(line.from + space);
20767
    }
20768
    return moved;
20769
}
20770
/**
20771
Move the selection to the next line wrap point, or to the end of
20772
the line if there isn't one left on this line.
20773
*/
20774
const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
20775
/**
20776
Move the selection to previous line wrap point, or failing that to
20777
the start of the line. If the line is indented, and the cursor
20778
isn't already at the end of the indentation, this will move to the
20779
end of the indentation instead of the start of the line.
20780
*/
20781
const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
20782
/**
20783
Move the selection one line wrap point to the left.
20784
*/
20785
const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20786
/**
20787
Move the selection one line wrap point to the right.
20788
*/
20789
const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20790
/**
20791
Move the selection to the start of the line.
20792
*/
20793
const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
20794
/**
20795
Move the selection to the end of the line.
20796
*/
20797
const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
20798
function toMatchingBracket(state, dispatch, extend) {
20799
    let found = false, selection = updateSel(state.selection, range => {
20800
        let matching = matchBrackets(state, range.head, -1)
20801
            || matchBrackets(state, range.head, 1)
20802
            || (range.head > 0 && matchBrackets(state, range.head - 1, 1))
20803
            || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));
20804
        if (!matching || !matching.end)
20805
            return range;
20806
        found = true;
20807
        let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
1441 ariadna 20808
        return EditorSelection.cursor(head);
1 efrain 20809
    });
20810
    if (!found)
20811
        return false;
20812
    dispatch(setSel(state, selection));
20813
    return true;
20814
}
20815
/**
20816
Move the selection to the bracket matching the one it is currently
20817
on, if any.
20818
*/
1441 ariadna 20819
const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch);
20820
function extendSel(target, how) {
20821
    let selection = updateSel(target.state.selection, range => {
1 efrain 20822
        let head = how(range);
20823
        return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || undefined);
20824
    });
1441 ariadna 20825
    if (selection.eq(target.state.selection))
1 efrain 20826
        return false;
1441 ariadna 20827
    target.dispatch(setSel(target.state, selection));
1 efrain 20828
    return true;
20829
}
20830
function selectByChar(view, forward) {
20831
    return extendSel(view, range => view.moveByChar(range, forward));
20832
}
20833
/**
20834
Move the selection head one character to the left, while leaving
20835
the anchor in place.
20836
*/
20837
const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));
20838
/**
20839
Move the selection head one character to the right.
20840
*/
20841
const selectCharRight = view => selectByChar(view, ltrAtCursor(view));
20842
function selectByGroup(view, forward) {
20843
    return extendSel(view, range => view.moveByGroup(range, forward));
20844
}
20845
/**
20846
Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to
20847
the left.
20848
*/
20849
const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));
20850
/**
20851
Move the selection head one group to the right.
20852
*/
20853
const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));
20854
/**
20855
Move the selection head over the next syntactic element to the left.
20856
*/
20857
const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20858
/**
20859
Move the selection head over the next syntactic element to the right.
20860
*/
20861
const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20862
function selectByLine(view, forward) {
20863
    return extendSel(view, range => view.moveVertically(range, forward));
20864
}
20865
/**
20866
Move the selection head one line up.
20867
*/
20868
const selectLineUp = view => selectByLine(view, false);
20869
/**
20870
Move the selection head one line down.
20871
*/
20872
const selectLineDown = view => selectByLine(view, true);
20873
function selectByPage(view, forward) {
20874
    return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));
20875
}
20876
/**
20877
Move the selection head one page up.
20878
*/
20879
const selectPageUp = view => selectByPage(view, false);
20880
/**
20881
Move the selection head one page down.
20882
*/
20883
const selectPageDown = view => selectByPage(view, true);
20884
/**
20885
Move the selection head to the next line boundary.
20886
*/
20887
const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
20888
/**
20889
Move the selection head to the previous line boundary.
20890
*/
20891
const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
20892
/**
20893
Move the selection head one line boundary to the left.
20894
*/
20895
const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20896
/**
20897
Move the selection head one line boundary to the right.
20898
*/
20899
const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20900
/**
20901
Move the selection head to the start of the line.
20902
*/
20903
const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from));
20904
/**
20905
Move the selection head to the end of the line.
20906
*/
20907
const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to));
20908
/**
20909
Move the selection to the start of the document.
20910
*/
20911
const cursorDocStart = ({ state, dispatch }) => {
20912
    dispatch(setSel(state, { anchor: 0 }));
20913
    return true;
20914
};
20915
/**
20916
Move the selection to the end of the document.
20917
*/
20918
const cursorDocEnd = ({ state, dispatch }) => {
20919
    dispatch(setSel(state, { anchor: state.doc.length }));
20920
    return true;
20921
};
20922
/**
20923
Move the selection head to the start of the document.
20924
*/
20925
const selectDocStart = ({ state, dispatch }) => {
20926
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
20927
    return true;
20928
};
20929
/**
20930
Move the selection head to the end of the document.
20931
*/
20932
const selectDocEnd = ({ state, dispatch }) => {
20933
    dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
20934
    return true;
20935
};
20936
/**
20937
Select the entire document.
20938
*/
20939
const selectAll = ({ state, dispatch }) => {
20940
    dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
20941
    return true;
20942
};
20943
/**
20944
Expand the selection to cover entire lines.
20945
*/
20946
const selectLine = ({ state, dispatch }) => {
20947
    let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
20948
    dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
20949
    return true;
20950
};
20951
/**
20952
Select the next syntactic construct that is larger than the
20953
selection. Note that this will only work insofar as the language
20954
[provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full
20955
syntax tree.
20956
*/
20957
const selectParentSyntax = ({ state, dispatch }) => {
20958
    let selection = updateSel(state.selection, range => {
1441 ariadna 20959
        let tree = syntaxTree(state), stack = tree.resolveStack(range.from, 1);
20960
        if (range.empty) {
20961
            let stackBefore = tree.resolveStack(range.from, -1);
20962
            if (stackBefore.node.from >= stack.node.from && stackBefore.node.to <= stack.node.to)
20963
                stack = stackBefore;
20964
        }
1 efrain 20965
        for (let cur = stack; cur; cur = cur.next) {
20966
            let { node } = cur;
20967
            if (((node.from < range.from && node.to >= range.to) ||
20968
                (node.to > range.to && node.from <= range.from)) &&
1441 ariadna 20969
                cur.next)
1 efrain 20970
                return EditorSelection.range(node.to, node.from);
20971
        }
20972
        return range;
20973
    });
1441 ariadna 20974
    if (selection.eq(state.selection))
20975
        return false;
1 efrain 20976
    dispatch(setSel(state, selection));
20977
    return true;
20978
};
20979
/**
20980
Simplify the current selection. When multiple ranges are selected,
20981
reduce it to its main range. Otherwise, if the selection is
20982
non-empty, convert it to a cursor selection.
20983
*/
20984
const simplifySelection = ({ state, dispatch }) => {
20985
    let cur = state.selection, selection = null;
20986
    if (cur.ranges.length > 1)
20987
        selection = EditorSelection.create([cur.main]);
20988
    else if (!cur.main.empty)
20989
        selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]);
20990
    if (!selection)
20991
        return false;
20992
    dispatch(setSel(state, selection));
20993
    return true;
20994
};
20995
function deleteBy(target, by) {
20996
    if (target.state.readOnly)
20997
        return false;
20998
    let event = "delete.selection", { state } = target;
20999
    let changes = state.changeByRange(range => {
21000
        let { from, to } = range;
21001
        if (from == to) {
21002
            let towards = by(range);
21003
            if (towards < from) {
21004
                event = "delete.backward";
21005
                towards = skipAtomic(target, towards, false);
21006
            }
21007
            else if (towards > from) {
21008
                event = "delete.forward";
21009
                towards = skipAtomic(target, towards, true);
21010
            }
21011
            from = Math.min(from, towards);
21012
            to = Math.max(to, towards);
21013
        }
21014
        else {
21015
            from = skipAtomic(target, from, false);
21016
            to = skipAtomic(target, to, true);
21017
        }
21018
        return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) };
21019
    });
21020
    if (changes.changes.empty)
21021
        return false;
21022
    target.dispatch(state.update(changes, {
21023
        scrollIntoView: true,
21024
        userEvent: event,
21025
        effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined
21026
    }));
21027
    return true;
21028
}
21029
function skipAtomic(target, pos, forward) {
21030
    if (target instanceof EditorView)
21031
        for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target)))
21032
            ranges.between(pos, pos, (from, to) => {
21033
                if (from < pos && to > pos)
21034
                    pos = forward ? to : from;
21035
            });
21036
    return pos;
21037
}
1441 ariadna 21038
const deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, range => {
1 efrain 21039
    let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos;
1441 ariadna 21040
    if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 &&
1 efrain 21041
        !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
21042
        if (before[before.length - 1] == "\t")
21043
            return pos - 1;
21044
        let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
21045
        for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
21046
            pos--;
21047
        targetPos = pos;
21048
    }
21049
    else {
21050
        targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
21051
        if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))
21052
            targetPos += forward ? 1 : -1;
21053
        else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)))
21054
            targetPos = findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
21055
    }
21056
    return targetPos;
21057
});
21058
/**
1441 ariadna 21059
Delete the selection, or, for cursor selections, the character or
21060
indentation unit before the cursor.
1 efrain 21061
*/
1441 ariadna 21062
const deleteCharBackward = view => deleteByChar(view, false, true);
1 efrain 21063
/**
21064
Delete the selection or the character after the cursor.
21065
*/
1441 ariadna 21066
const deleteCharForward = view => deleteByChar(view, true, false);
1 efrain 21067
const deleteByGroup = (target, forward) => deleteBy(target, range => {
21068
    let pos = range.head, { state } = target, line = state.doc.lineAt(pos);
21069
    let categorize = state.charCategorizer(pos);
21070
    for (let cat = null;;) {
21071
        if (pos == (forward ? line.to : line.from)) {
21072
            if (pos == range.head && line.number != (forward ? state.doc.lines : 1))
21073
                pos += forward ? 1 : -1;
21074
            break;
21075
        }
21076
        let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
21077
        let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
21078
        let nextCat = categorize(nextChar);
21079
        if (cat != null && nextCat != cat)
21080
            break;
21081
        if (nextChar != " " || pos != range.head)
21082
            cat = nextCat;
21083
        pos = next;
21084
    }
21085
    return pos;
21086
});
21087
/**
21088
Delete the selection or backward until the end of the next
21089
[group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of
21090
whitespace when they consist of a single space.
21091
*/
21092
const deleteGroupBackward = target => deleteByGroup(target, false);
21093
/**
21094
Delete the selection or forward until the end of the next group.
21095
*/
21096
const deleteGroupForward = target => deleteByGroup(target, true);
21097
/**
21098
Delete the selection, or, if it is a cursor selection, delete to
21099
the end of the line. If the cursor is directly at the end of the
21100
line, delete the line break after it.
21101
*/
21102
const deleteToLineEnd = view => deleteBy(view, range => {
21103
    let lineEnd = view.lineBlockAt(range.head).to;
21104
    return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
21105
});
21106
/**
21107
Delete the selection, or, if it is a cursor selection, delete to
21108
the start of the line or the next line wrap before the cursor.
21109
*/
21110
const deleteLineBoundaryBackward = view => deleteBy(view, range => {
21111
    let lineStart = view.moveToLineBoundary(range, false).head;
21112
    return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
21113
});
21114
/**
21115
Delete the selection, or, if it is a cursor selection, delete to
21116
the end of the line or the next line wrap after the cursor.
21117
*/
21118
const deleteLineBoundaryForward = view => deleteBy(view, range => {
21119
    let lineStart = view.moveToLineBoundary(range, true).head;
21120
    return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1);
21121
});
21122
/**
21123
Replace each selection range with a line break, leaving the cursor
21124
on the line before the break.
21125
*/
21126
const splitLine = ({ state, dispatch }) => {
21127
    if (state.readOnly)
21128
        return false;
21129
    let changes = state.changeByRange(range => {
21130
        return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) },
21131
            range: EditorSelection.cursor(range.from) };
21132
    });
21133
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
21134
    return true;
21135
};
21136
/**
21137
Flip the characters before and after the cursor(s).
21138
*/
21139
const transposeChars = ({ state, dispatch }) => {
21140
    if (state.readOnly)
21141
        return false;
21142
    let changes = state.changeByRange(range => {
21143
        if (!range.empty || range.from == 0 || range.from == state.doc.length)
21144
            return { range };
21145
        let pos = range.from, line = state.doc.lineAt(pos);
21146
        let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
21147
        let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
21148
        return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
21149
            range: EditorSelection.cursor(to) };
21150
    });
21151
    if (changes.changes.empty)
21152
        return false;
21153
    dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
21154
    return true;
21155
};
21156
function selectedLineBlocks(state) {
21157
    let blocks = [], upto = -1;
21158
    for (let range of state.selection.ranges) {
21159
        let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
21160
        if (!range.empty && range.to == endLine.from)
21161
            endLine = state.doc.lineAt(range.to - 1);
21162
        if (upto >= startLine.number) {
21163
            let prev = blocks[blocks.length - 1];
21164
            prev.to = endLine.to;
21165
            prev.ranges.push(range);
21166
        }
21167
        else {
21168
            blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
21169
        }
21170
        upto = endLine.number + 1;
21171
    }
21172
    return blocks;
21173
}
21174
function moveLine(state, dispatch, forward) {
21175
    if (state.readOnly)
21176
        return false;
21177
    let changes = [], ranges = [];
21178
    for (let block of selectedLineBlocks(state)) {
21179
        if (forward ? block.to == state.doc.length : block.from == 0)
21180
            continue;
21181
        let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
21182
        let size = nextLine.length + 1;
21183
        if (forward) {
21184
            changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
21185
            for (let r of block.ranges)
21186
                ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
21187
        }
21188
        else {
21189
            changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
21190
            for (let r of block.ranges)
21191
                ranges.push(EditorSelection.range(r.anchor - size, r.head - size));
21192
        }
21193
    }
21194
    if (!changes.length)
21195
        return false;
21196
    dispatch(state.update({
21197
        changes,
21198
        scrollIntoView: true,
21199
        selection: EditorSelection.create(ranges, state.selection.mainIndex),
21200
        userEvent: "move.line"
21201
    }));
21202
    return true;
21203
}
21204
/**
21205
Move the selected lines up one line.
21206
*/
21207
const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
21208
/**
21209
Move the selected lines down one line.
21210
*/
21211
const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
21212
function copyLine(state, dispatch, forward) {
21213
    if (state.readOnly)
21214
        return false;
21215
    let changes = [];
21216
    for (let block of selectedLineBlocks(state)) {
21217
        if (forward)
21218
            changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
21219
        else
21220
            changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
21221
    }
21222
    dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
21223
    return true;
21224
}
21225
/**
21226
Create a copy of the selected lines. Keep the selection in the top copy.
21227
*/
21228
const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
21229
/**
21230
Create a copy of the selected lines. Keep the selection in the bottom copy.
21231
*/
21232
const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
21233
/**
21234
Delete selected lines.
21235
*/
21236
const deleteLine = view => {
21237
    if (view.state.readOnly)
21238
        return false;
21239
    let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
21240
        if (from > 0)
21241
            from--;
21242
        else if (to < state.doc.length)
21243
            to++;
21244
        return { from, to };
21245
    }));
1441 ariadna 21246
    let selection = updateSel(state.selection, range => {
21247
        let dist = undefined;
21248
        if (view.lineWrapping) {
21249
            let block = view.lineBlockAt(range.head), pos = view.coordsAtPos(range.head, range.assoc || 1);
21250
            if (pos)
21251
                dist = (block.bottom + view.documentTop) - pos.bottom + view.defaultLineHeight / 2;
21252
        }
21253
        return view.moveVertically(range, true, dist);
21254
    }).map(changes);
1 efrain 21255
    view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
21256
    return true;
21257
};
21258
function isBetweenBrackets(state, pos) {
21259
    if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
21260
        return { from: pos, to: pos };
21261
    let context = syntaxTree(state).resolveInner(pos);
21262
    let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
21263
    if (before && after && before.to <= pos && after.from >= pos &&
21264
        (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 &&
21265
        state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from &&
21266
        !/\S/.test(state.sliceDoc(before.to, after.from)))
21267
        return { from: before.to, to: after.from };
21268
    return null;
21269
}
21270
/**
21271
Replace the selection with a newline and indent the newly created
21272
line(s). If the current line consists only of whitespace, this
21273
will also delete that whitespace. When the cursor is between
21274
matching brackets, an additional newline will be inserted after
21275
the cursor.
21276
*/
21277
const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false);
21278
/**
21279
Create a blank, indented line below the current line.
21280
*/
21281
const insertBlankLine = /*@__PURE__*/newlineAndIndent(true);
21282
function newlineAndIndent(atEof) {
21283
    return ({ state, dispatch }) => {
21284
        if (state.readOnly)
21285
            return false;
21286
        let changes = state.changeByRange(range => {
21287
            let { from, to } = range, line = state.doc.lineAt(from);
21288
            let explode = !atEof && from == to && isBetweenBrackets(state, from);
21289
            if (atEof)
21290
                from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
21291
            let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
21292
            let indent = getIndentation(cx, from);
21293
            if (indent == null)
21294
                indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
21295
            while (to < line.to && /\s/.test(line.text[to - line.from]))
21296
                to++;
21297
            if (explode)
21298
                ({ from, to } = explode);
21299
            else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
21300
                from = line.from;
21301
            let insert = ["", indentString(state, indent)];
21302
            if (explode)
21303
                insert.push(indentString(state, cx.lineIndent(line.from, -1)));
21304
            return { changes: { from, to, insert: Text.of(insert) },
21305
                range: EditorSelection.cursor(from + 1 + insert[1].length) };
21306
        });
21307
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
21308
        return true;
21309
    };
21310
}
21311
function changeBySelectedLine(state, f) {
21312
    let atLine = -1;
21313
    return state.changeByRange(range => {
21314
        let changes = [];
21315
        for (let pos = range.from; pos <= range.to;) {
21316
            let line = state.doc.lineAt(pos);
21317
            if (line.number > atLine && (range.empty || range.to > line.from)) {
21318
                f(line, changes, range);
21319
                atLine = line.number;
21320
            }
21321
            pos = line.to + 1;
21322
        }
21323
        let changeSet = state.changes(changes);
21324
        return { changes,
21325
            range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };
21326
    });
21327
}
21328
/**
21329
Auto-indent the selected lines. This uses the [indentation service
21330
facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent
21331
information.
21332
*/
21333
const indentSelection = ({ state, dispatch }) => {
21334
    if (state.readOnly)
21335
        return false;
21336
    let updated = Object.create(null);
21337
    let context = new IndentContext(state, { overrideIndentation: start => {
21338
            let found = updated[start];
21339
            return found == null ? -1 : found;
21340
        } });
21341
    let changes = changeBySelectedLine(state, (line, changes, range) => {
21342
        let indent = getIndentation(context, line.from);
21343
        if (indent == null)
21344
            return;
21345
        if (!/\S/.test(line.text))
21346
            indent = 0;
21347
        let cur = /^\s*/.exec(line.text)[0];
21348
        let norm = indentString(state, indent);
21349
        if (cur != norm || range.from < line.from + cur.length) {
21350
            updated[line.from] = indent;
21351
            changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
21352
        }
21353
    });
21354
    if (!changes.changes.empty)
21355
        dispatch(state.update(changes, { userEvent: "indent" }));
21356
    return true;
21357
};
21358
/**
21359
Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected
21360
lines.
21361
*/
21362
const indentMore = ({ state, dispatch }) => {
21363
    if (state.readOnly)
21364
        return false;
21365
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
21366
        changes.push({ from: line.from, insert: state.facet(indentUnit) });
21367
    }), { userEvent: "input.indent" }));
21368
    return true;
21369
};
21370
/**
21371
Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all
21372
selected lines.
21373
*/
21374
const indentLess = ({ state, dispatch }) => {
21375
    if (state.readOnly)
21376
        return false;
21377
    dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
21378
        let space = /^\s*/.exec(line.text)[0];
21379
        if (!space)
21380
            return;
21381
        let col = countColumn(space, state.tabSize), keep = 0;
21382
        let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));
21383
        while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))
21384
            keep++;
21385
        changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });
21386
    }), { userEvent: "delete.dedent" }));
21387
    return true;
21388
};
21389
/**
1441 ariadna 21390
Enables or disables
21391
[tab-focus mode](https://codemirror.net/6/docs/ref/#view.EditorView.setTabFocusMode). While on, this
21392
prevents the editor's key bindings from capturing Tab or
21393
Shift-Tab, making it possible for the user to move focus out of
21394
the editor with the keyboard.
21395
*/
21396
const toggleTabFocusMode = view => {
21397
    view.setTabFocusMode();
21398
    return true;
21399
};
21400
/**
1 efrain 21401
Array of key bindings containing the Emacs-style bindings that are
21402
available on macOS by default.
21403
 
21404
 - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
21405
 - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
21406
 - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
21407
 - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
21408
 - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
21409
 - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
21410
 - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
21411
 - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
21412
 - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd)
21413
 - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
21414
 - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine)
21415
 - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars)
21416
 - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown)
21417
 - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp)
21418
*/
21419
const emacsStyleKeymap = [
21420
    { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
21421
    { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
21422
    { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
21423
    { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
21424
    { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
21425
    { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
21426
    { key: "Ctrl-d", run: deleteCharForward },
21427
    { key: "Ctrl-h", run: deleteCharBackward },
21428
    { key: "Ctrl-k", run: deleteToLineEnd },
21429
    { key: "Ctrl-Alt-h", run: deleteGroupBackward },
21430
    { key: "Ctrl-o", run: splitLine },
21431
    { key: "Ctrl-t", run: transposeChars },
21432
    { key: "Ctrl-v", run: cursorPageDown },
21433
];
21434
/**
21435
An array of key bindings closely sticking to platform-standard or
21436
widely used bindings. (This includes the bindings from
21437
[`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key`
21438
property changed to `mac`.)
21439
 
21440
 - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
21441
 - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
21442
 - 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)
21443
 - 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)
21444
 - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
21445
 - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
21446
 - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
21447
 - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
21448
 - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
21449
 - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
21450
 - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
21451
 - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
21452
 - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
21453
 - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
21454
 - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift)
21455
 - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift)
21456
 - 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)
21457
 - 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)
1441 ariadna 21458
 - Enter and Shift-Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent)
1 efrain 21459
 - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll)
21460
 - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
21461
 - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
21462
 - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
21463
 - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)
21464
 - Cmd-Backspace (macOS): [`deleteLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryBackward).
21465
 - Cmd-Delete (macOS): [`deleteLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.deleteLineBoundaryForward).
21466
*/
21467
const standardKeymap = /*@__PURE__*/[
21468
    { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
21469
    { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
21470
    { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
21471
    { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
21472
    { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
21473
    { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
21474
    { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
21475
    { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
21476
    { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
21477
    { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
21478
    { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
21479
    { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
21480
    { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
21481
    { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
21482
    { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
21483
    { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
21484
    { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
21485
    { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
1441 ariadna 21486
    { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent },
1 efrain 21487
    { key: "Mod-a", run: selectAll },
21488
    { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward },
21489
    { key: "Delete", run: deleteCharForward },
21490
    { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
21491
    { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
21492
    { mac: "Mod-Backspace", run: deleteLineBoundaryBackward },
21493
    { mac: "Mod-Delete", run: deleteLineBoundaryForward }
21494
].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));
21495
/**
21496
The default keymap. Includes all bindings from
21497
[`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following:
21498
 
21499
- 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)
21500
- 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)
21501
- Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp)
21502
- Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown)
21503
- Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp)
21504
- Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown)
21505
- Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection)
21506
- Ctrl-Enter (Cmd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine)
21507
- Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine)
21508
- Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax)
21509
- Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess)
21510
- Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore)
21511
- Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection)
21512
- Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine)
21513
- Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket)
21514
- Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment).
21515
- Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
1441 ariadna 21516
- Ctrl-m (Alt-Shift-m on macOS): [`toggleTabFocusMode`](https://codemirror.net/6/docs/ref/#commands.toggleTabFocusMode).
1 efrain 21517
*/
21518
const defaultKeymap = /*@__PURE__*/[
21519
    { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
21520
    { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
21521
    { key: "Alt-ArrowUp", run: moveLineUp },
21522
    { key: "Shift-Alt-ArrowUp", run: copyLineUp },
21523
    { key: "Alt-ArrowDown", run: moveLineDown },
21524
    { key: "Shift-Alt-ArrowDown", run: copyLineDown },
21525
    { key: "Escape", run: simplifySelection },
21526
    { key: "Mod-Enter", run: insertBlankLine },
21527
    { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
21528
    { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
21529
    { key: "Mod-[", run: indentLess },
21530
    { key: "Mod-]", run: indentMore },
21531
    { key: "Mod-Alt-\\", run: indentSelection },
21532
    { key: "Shift-Mod-k", run: deleteLine },
21533
    { key: "Shift-Mod-\\", run: cursorMatchingBracket },
21534
    { key: "Mod-/", run: toggleComment },
1441 ariadna 21535
    { key: "Alt-A", run: toggleBlockComment },
21536
    { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode },
1 efrain 21537
].concat(standardKeymap);
21538
 
21539
function crelt() {
21540
  var elt = arguments[0];
21541
  if (typeof elt == "string") elt = document.createElement(elt);
21542
  var i = 1, next = arguments[1];
21543
  if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
21544
    for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
21545
      var value = next[name];
21546
      if (typeof value == "string") elt.setAttribute(name, value);
21547
      else if (value != null) elt[name] = value;
21548
    }
21549
    i++;
21550
  }
21551
  for (; i < arguments.length; i++) add(elt, arguments[i]);
21552
  return elt
21553
}
21554
 
21555
function add(elt, child) {
21556
  if (typeof child == "string") {
21557
    elt.appendChild(document.createTextNode(child));
21558
  } else if (child == null) ; else if (child.nodeType != null) {
21559
    elt.appendChild(child);
21560
  } else if (Array.isArray(child)) {
21561
    for (var i = 0; i < child.length; i++) add(elt, child[i]);
21562
  } else {
21563
    throw new RangeError("Unsupported child node: " + child)
21564
  }
21565
}
21566
 
21567
const basicNormalize = typeof String.prototype.normalize == "function"
21568
    ? x => x.normalize("NFKD") : x => x;
21569
/**
21570
A search cursor provides an iterator over text matches in a
21571
document.
21572
*/
21573
class SearchCursor {
21574
    /**
21575
    Create a text cursor. The query is the search string, `from` to
21576
    `to` provides the region to search.
21577
 
21578
    When `normalize` is given, it will be called, on both the query
21579
    string and the content it is matched against, before comparing.
21580
    You can, for example, create a case-insensitive search by
21581
    passing `s => s.toLowerCase()`.
21582
 
21583
    Text is always normalized with
21584
    [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
21585
    (when supported).
21586
    */
21587
    constructor(text, query, from = 0, to = text.length, normalize, test) {
21588
        this.test = test;
21589
        /**
21590
        The current match (only holds a meaningful value after
21591
        [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when
21592
        `done` is false).
21593
        */
21594
        this.value = { from: 0, to: 0 };
21595
        /**
21596
        Whether the end of the iterated region has been reached.
21597
        */
21598
        this.done = false;
21599
        this.matches = [];
21600
        this.buffer = "";
21601
        this.bufferPos = 0;
21602
        this.iter = text.iterRange(from, to);
21603
        this.bufferStart = from;
21604
        this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
21605
        this.query = this.normalize(query);
21606
    }
21607
    peek() {
21608
        if (this.bufferPos == this.buffer.length) {
21609
            this.bufferStart += this.buffer.length;
21610
            this.iter.next();
21611
            if (this.iter.done)
21612
                return -1;
21613
            this.bufferPos = 0;
21614
            this.buffer = this.iter.value;
21615
        }
21616
        return codePointAt(this.buffer, this.bufferPos);
21617
    }
21618
    /**
21619
    Look for the next match. Updates the iterator's
21620
    [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
21621
    [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
21622
    at least once before using the cursor.
21623
    */
21624
    next() {
21625
        while (this.matches.length)
21626
            this.matches.pop();
21627
        return this.nextOverlapping();
21628
    }
21629
    /**
21630
    The `next` method will ignore matches that partially overlap a
21631
    previous match. This method behaves like `next`, but includes
21632
    such matches.
21633
    */
21634
    nextOverlapping() {
21635
        for (;;) {
21636
            let next = this.peek();
21637
            if (next < 0) {
21638
                this.done = true;
21639
                return this;
21640
            }
21641
            let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos;
21642
            this.bufferPos += codePointSize(next);
21643
            let norm = this.normalize(str);
1441 ariadna 21644
            if (norm.length)
21645
                for (let i = 0, pos = start;; i++) {
21646
                    let code = norm.charCodeAt(i);
21647
                    let match = this.match(code, pos, this.bufferPos + this.bufferStart);
21648
                    if (i == norm.length - 1) {
21649
                        if (match) {
21650
                            this.value = match;
21651
                            return this;
21652
                        }
21653
                        break;
1 efrain 21654
                    }
1441 ariadna 21655
                    if (pos == start && i < str.length && str.charCodeAt(i) == code)
21656
                        pos++;
1 efrain 21657
                }
21658
        }
21659
    }
21660
    match(code, pos, end) {
21661
        let match = null;
21662
        for (let i = 0; i < this.matches.length; i += 2) {
21663
            let index = this.matches[i], keep = false;
21664
            if (this.query.charCodeAt(index) == code) {
21665
                if (index == this.query.length - 1) {
21666
                    match = { from: this.matches[i + 1], to: end };
21667
                }
21668
                else {
21669
                    this.matches[i]++;
21670
                    keep = true;
21671
                }
21672
            }
21673
            if (!keep) {
21674
                this.matches.splice(i, 2);
21675
                i -= 2;
21676
            }
21677
        }
21678
        if (this.query.charCodeAt(0) == code) {
21679
            if (this.query.length == 1)
21680
                match = { from: pos, to: end };
21681
            else
21682
                this.matches.push(1, pos);
21683
        }
21684
        if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
21685
            match = null;
21686
        return match;
21687
    }
21688
}
21689
if (typeof Symbol != "undefined")
21690
    SearchCursor.prototype[Symbol.iterator] = function () { return this; };
21691
 
21692
const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") };
21693
const baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
21694
/**
21695
This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor)
21696
but searches for a regular expression pattern instead of a plain
21697
string.
21698
*/
21699
class RegExpCursor {
21700
    /**
21701
    Create a cursor that will search the given range in the given
21702
    document. `query` should be the raw pattern (as you'd pass it to
21703
    `new RegExp`).
21704
    */
21705
    constructor(text, query, options, from = 0, to = text.length) {
21706
        this.text = text;
21707
        this.to = to;
21708
        this.curLine = "";
21709
        /**
21710
        Set to `true` when the cursor has reached the end of the search
21711
        range.
21712
        */
21713
        this.done = false;
21714
        /**
21715
        Will contain an object with the extent of the match and the
21716
        match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)
21717
        sucessfully finds a match.
21718
        */
21719
        this.value = empty;
21720
        if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
21721
            return new MultilineRegExpCursor(text, query, options, from, to);
21722
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21723
        this.test = options === null || options === void 0 ? void 0 : options.test;
21724
        this.iter = text.iter();
21725
        let startLine = text.lineAt(from);
21726
        this.curLineStart = startLine.from;
21727
        this.matchPos = toCharEnd(text, from);
21728
        this.getLine(this.curLineStart);
21729
    }
21730
    getLine(skip) {
21731
        this.iter.next(skip);
21732
        if (this.iter.lineBreak) {
21733
            this.curLine = "";
21734
        }
21735
        else {
21736
            this.curLine = this.iter.value;
21737
            if (this.curLineStart + this.curLine.length > this.to)
21738
                this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
21739
            this.iter.next();
21740
        }
21741
    }
21742
    nextLine() {
21743
        this.curLineStart = this.curLineStart + this.curLine.length + 1;
21744
        if (this.curLineStart > this.to)
21745
            this.curLine = "";
21746
        else
21747
            this.getLine(0);
21748
    }
21749
    /**
21750
    Move to the next match, if there is one.
21751
    */
21752
    next() {
21753
        for (let off = this.matchPos - this.curLineStart;;) {
21754
            this.re.lastIndex = off;
21755
            let match = this.matchPos <= this.to && this.re.exec(this.curLine);
21756
            if (match) {
21757
                let from = this.curLineStart + match.index, to = from + match[0].length;
21758
                this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21759
                if (from == this.curLineStart + this.curLine.length)
21760
                    this.nextLine();
21761
                if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
21762
                    this.value = { from, to, match };
21763
                    return this;
21764
                }
21765
                off = this.matchPos - this.curLineStart;
21766
            }
21767
            else if (this.curLineStart + this.curLine.length < this.to) {
21768
                this.nextLine();
21769
                off = 0;
21770
            }
21771
            else {
21772
                this.done = true;
21773
                return this;
21774
            }
21775
        }
21776
    }
21777
}
21778
const flattened = /*@__PURE__*/new WeakMap();
21779
// Reusable (partially) flattened document strings
21780
class FlattenedDoc {
21781
    constructor(from, text) {
21782
        this.from = from;
21783
        this.text = text;
21784
    }
21785
    get to() { return this.from + this.text.length; }
21786
    static get(doc, from, to) {
21787
        let cached = flattened.get(doc);
21788
        if (!cached || cached.from >= to || cached.to <= from) {
21789
            let flat = new FlattenedDoc(from, doc.sliceString(from, to));
21790
            flattened.set(doc, flat);
21791
            return flat;
21792
        }
21793
        if (cached.from == from && cached.to == to)
21794
            return cached;
21795
        let { text, from: cachedFrom } = cached;
21796
        if (cachedFrom > from) {
21797
            text = doc.sliceString(from, cachedFrom) + text;
21798
            cachedFrom = from;
21799
        }
21800
        if (cached.to < to)
21801
            text += doc.sliceString(cached.to, to);
21802
        flattened.set(doc, new FlattenedDoc(cachedFrom, text));
21803
        return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom));
21804
    }
21805
}
21806
class MultilineRegExpCursor {
21807
    constructor(text, query, options, from, to) {
21808
        this.text = text;
21809
        this.to = to;
21810
        this.done = false;
21811
        this.value = empty;
21812
        this.matchPos = toCharEnd(text, from);
21813
        this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21814
        this.test = options === null || options === void 0 ? void 0 : options.test;
21815
        this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */));
21816
    }
21817
    chunkEnd(pos) {
21818
        return pos >= this.to ? this.to : this.text.lineAt(pos).to;
21819
    }
21820
    next() {
21821
        for (;;) {
21822
            let off = this.re.lastIndex = this.matchPos - this.flat.from;
21823
            let match = this.re.exec(this.flat.text);
21824
            // Skip empty matches directly after the last match
21825
            if (match && !match[0] && match.index == off) {
21826
                this.re.lastIndex = off + 1;
21827
                match = this.re.exec(this.flat.text);
21828
            }
21829
            if (match) {
21830
                let from = this.flat.from + match.index, to = from + match[0].length;
21831
                // If a match goes almost to the end of a noncomplete chunk, try
21832
                // again, since it'll likely be able to match more
21833
                if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) &&
21834
                    (!this.test || this.test(from, to, match))) {
21835
                    this.value = { from, to, match };
21836
                    this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21837
                    return this;
21838
                }
21839
            }
21840
            if (this.flat.to == this.to) {
21841
                this.done = true;
21842
                return this;
21843
            }
21844
            // Grow the flattened doc
21845
            this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
21846
        }
21847
    }
21848
}
21849
if (typeof Symbol != "undefined") {
21850
    RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] =
21851
        function () { return this; };
21852
}
21853
function validRegExp(source) {
21854
    try {
21855
        new RegExp(source, baseFlags);
21856
        return true;
21857
    }
21858
    catch (_a) {
21859
        return false;
21860
    }
21861
}
21862
function toCharEnd(text, pos) {
21863
    if (pos >= text.length)
21864
        return pos;
21865
    let line = text.lineAt(pos), next;
21866
    while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000)
21867
        pos++;
21868
    return pos;
21869
}
21870
 
21871
function createLineDialog(view) {
21872
    let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
21873
    let input = crelt("input", { class: "cm-textfield", name: "line", value: line });
21874
    let dom = crelt("form", {
21875
        class: "cm-gotoLine",
21876
        onkeydown: (event) => {
21877
            if (event.keyCode == 27) { // Escape
21878
                event.preventDefault();
21879
                view.dispatch({ effects: dialogEffect.of(false) });
21880
                view.focus();
21881
            }
21882
            else if (event.keyCode == 13) { // Enter
21883
                event.preventDefault();
21884
                go();
21885
            }
21886
        },
21887
        onsubmit: (event) => {
21888
            event.preventDefault();
21889
            go();
21890
        }
1441 ariadna 21891
    }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")), crelt("button", {
21892
        name: "close",
21893
        onclick: () => {
21894
            view.dispatch({ effects: dialogEffect.of(false) });
21895
            view.focus();
21896
        },
21897
        "aria-label": view.state.phrase("close"),
21898
        type: "button"
21899
    }, ["×"]));
1 efrain 21900
    function go() {
21901
        let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
21902
        if (!match)
21903
            return;
21904
        let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
21905
        let [, sign, ln, cl, percent] = match;
21906
        let col = cl ? +cl.slice(1) : 0;
21907
        let line = ln ? +ln : startLine.number;
21908
        if (ln && percent) {
21909
            let pc = line / 100;
21910
            if (sign)
21911
                pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines);
21912
            line = Math.round(state.doc.lines * pc);
21913
        }
21914
        else if (ln && sign) {
21915
            line = line * (sign == "-" ? -1 : 1) + startLine.number;
21916
        }
21917
        let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
21918
        let selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
21919
        view.dispatch({
21920
            effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection.from, { y: 'center' })],
21921
            selection,
21922
        });
21923
        view.focus();
21924
    }
21925
    return { dom };
21926
}
21927
const dialogEffect = /*@__PURE__*/StateEffect.define();
21928
const dialogField = /*@__PURE__*/StateField.define({
21929
    create() { return true; },
21930
    update(value, tr) {
21931
        for (let e of tr.effects)
21932
            if (e.is(dialogEffect))
21933
                value = e.value;
21934
        return value;
21935
    },
21936
    provide: f => showPanel.from(f, val => val ? createLineDialog : null)
21937
});
21938
/**
21939
Command that shows a dialog asking the user for a line number, and
21940
when a valid position is provided, moves the cursor to that line.
21941
 
21942
Supports line numbers, relative line offsets prefixed with `+` or
21943
`-`, document percentages suffixed with `%`, and an optional
21944
column position by adding `:` and a second number after the line
21945
number.
21946
*/
21947
const gotoLine = view => {
21948
    let panel = getPanel(view, createLineDialog);
21949
    if (!panel) {
21950
        let effects = [dialogEffect.of(true)];
21951
        if (view.state.field(dialogField, false) == null)
21952
            effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1$1]));
21953
        view.dispatch({ effects });
21954
        panel = getPanel(view, createLineDialog);
21955
    }
21956
    if (panel)
21957
        panel.dom.querySelector("input").select();
21958
    return true;
21959
};
21960
const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({
21961
    ".cm-panel.cm-gotoLine": {
21962
        padding: "2px 6px 4px",
1441 ariadna 21963
        position: "relative",
21964
        "& label": { fontSize: "80%" },
21965
        "& [name=close]": {
21966
            position: "absolute",
21967
            top: "0", bottom: "0",
21968
            right: "4px",
21969
            backgroundColor: "inherit",
21970
            border: "none",
21971
            font: "inherit",
21972
            padding: "0"
21973
        }
1 efrain 21974
    }
21975
});
21976
 
21977
const defaultHighlightOptions = {
21978
    highlightWordAroundCursor: false,
21979
    minSelectionLength: 1,
21980
    maxMatches: 100,
21981
    wholeWords: false
21982
};
21983
const highlightConfig = /*@__PURE__*/Facet.define({
21984
    combine(options) {
21985
        return combineConfig(options, defaultHighlightOptions, {
21986
            highlightWordAroundCursor: (a, b) => a || b,
21987
            minSelectionLength: Math.min,
21988
            maxMatches: Math.min
21989
        });
21990
    }
21991
});
21992
/**
21993
This extension highlights text that matches the selection. It uses
21994
the `"cm-selectionMatch"` class for the highlighting. When
21995
`highlightWordAroundCursor` is enabled, the word at the cursor
21996
itself will be highlighted with `"cm-selectionMatch-main"`.
21997
*/
21998
function highlightSelectionMatches(options) {
21999
    let ext = [defaultTheme, matchHighlighter];
22000
    return ext;
22001
}
22002
const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" });
22003
const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
22004
// Whether the characters directly outside the given positions are non-word characters
22005
function insideWordBoundaries(check, state, from, to) {
22006
    return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) &&
22007
        (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word);
22008
}
22009
// Whether the characters directly at the given positions are word characters
22010
function insideWord(check, state, from, to) {
22011
    return check(state.sliceDoc(from, from + 1)) == CharCategory.Word
22012
        && check(state.sliceDoc(to - 1, to)) == CharCategory.Word;
22013
}
22014
const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
22015
    constructor(view) {
22016
        this.decorations = this.getDeco(view);
22017
    }
22018
    update(update) {
22019
        if (update.selectionSet || update.docChanged || update.viewportChanged)
22020
            this.decorations = this.getDeco(update.view);
22021
    }
22022
    getDeco(view) {
22023
        let conf = view.state.facet(highlightConfig);
22024
        let { state } = view, sel = state.selection;
22025
        if (sel.ranges.length > 1)
22026
            return Decoration.none;
22027
        let range = sel.main, query, check = null;
22028
        if (range.empty) {
22029
            if (!conf.highlightWordAroundCursor)
22030
                return Decoration.none;
22031
            let word = state.wordAt(range.head);
22032
            if (!word)
22033
                return Decoration.none;
22034
            check = state.charCategorizer(range.head);
22035
            query = state.sliceDoc(word.from, word.to);
22036
        }
22037
        else {
22038
            let len = range.to - range.from;
22039
            if (len < conf.minSelectionLength || len > 200)
22040
                return Decoration.none;
22041
            if (conf.wholeWords) {
22042
                query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space?
22043
                check = state.charCategorizer(range.head);
22044
                if (!(insideWordBoundaries(check, state, range.from, range.to) &&
22045
                    insideWord(check, state, range.from, range.to)))
22046
                    return Decoration.none;
22047
            }
22048
            else {
22049
                query = state.sliceDoc(range.from, range.to);
22050
                if (!query)
22051
                    return Decoration.none;
22052
            }
22053
        }
22054
        let deco = [];
22055
        for (let part of view.visibleRanges) {
22056
            let cursor = new SearchCursor(state.doc, query, part.from, part.to);
22057
            while (!cursor.next().done) {
22058
                let { from, to } = cursor.value;
22059
                if (!check || insideWordBoundaries(check, state, from, to)) {
22060
                    if (range.empty && from <= range.from && to >= range.to)
22061
                        deco.push(mainMatchDeco.range(from, to));
22062
                    else if (from >= range.to || to <= range.from)
22063
                        deco.push(matchDeco.range(from, to));
22064
                    if (deco.length > conf.maxMatches)
22065
                        return Decoration.none;
22066
                }
22067
            }
22068
        }
22069
        return Decoration.set(deco);
22070
    }
22071
}, {
22072
    decorations: v => v.decorations
22073
});
22074
const defaultTheme = /*@__PURE__*/EditorView.baseTheme({
22075
    ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
22076
    ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
22077
});
22078
// Select the words around the cursors.
22079
const selectWord = ({ state, dispatch }) => {
22080
    let { selection } = state;
22081
    let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex);
22082
    if (newSel.eq(selection))
22083
        return false;
22084
    dispatch(state.update({ selection: newSel }));
22085
    return true;
22086
};
22087
// Find next occurrence of query relative to last cursor. Wrap around
22088
// the document if there are no more matches.
22089
function findNextOccurrence(state, query) {
22090
    let { main, ranges } = state.selection;
22091
    let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
22092
    for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) {
22093
        cursor.next();
22094
        if (cursor.done) {
22095
            if (cycled)
22096
                return null;
22097
            cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
22098
            cycled = true;
22099
        }
22100
        else {
22101
            if (cycled && ranges.some(r => r.from == cursor.value.from))
22102
                continue;
22103
            if (fullWord) {
22104
                let word = state.wordAt(cursor.value.from);
22105
                if (!word || word.from != cursor.value.from || word.to != cursor.value.to)
22106
                    continue;
22107
            }
22108
            return cursor.value;
22109
        }
22110
    }
22111
}
22112
/**
22113
Select next occurrence of the current selection. Expand selection
22114
to the surrounding word when the selection is empty.
22115
*/
22116
const selectNextOccurrence = ({ state, dispatch }) => {
22117
    let { ranges } = state.selection;
22118
    if (ranges.some(sel => sel.from === sel.to))
22119
        return selectWord({ state, dispatch });
22120
    let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
22121
    if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText))
22122
        return false;
22123
    let range = findNextOccurrence(state, searchedText);
22124
    if (!range)
22125
        return false;
22126
    dispatch(state.update({
22127
        selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false),
22128
        effects: EditorView.scrollIntoView(range.to)
22129
    }));
22130
    return true;
22131
};
22132
 
22133
const searchConfigFacet = /*@__PURE__*/Facet.define({
22134
    combine(configs) {
22135
        return combineConfig(configs, {
22136
            top: false,
22137
            caseSensitive: false,
22138
            literal: false,
22139
            regexp: false,
22140
            wholeWord: false,
22141
            createPanel: view => new SearchPanel(view),
22142
            scrollToMatch: range => EditorView.scrollIntoView(range)
22143
        });
22144
    }
22145
});
22146
/**
22147
A search query. Part of the editor's search state.
22148
*/
22149
class SearchQuery {
22150
    /**
22151
    Create a query object.
22152
    */
22153
    constructor(config) {
22154
        this.search = config.search;
22155
        this.caseSensitive = !!config.caseSensitive;
22156
        this.literal = !!config.literal;
22157
        this.regexp = !!config.regexp;
22158
        this.replace = config.replace || "";
22159
        this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
22160
        this.unquoted = this.unquote(this.search);
22161
        this.wholeWord = !!config.wholeWord;
22162
    }
22163
    /**
22164
    @internal
22165
    */
22166
    unquote(text) {
22167
        return this.literal ? text :
22168
            text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\");
22169
    }
22170
    /**
22171
    Compare this query to another query.
22172
    */
22173
    eq(other) {
22174
        return this.search == other.search && this.replace == other.replace &&
22175
            this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
22176
            this.wholeWord == other.wholeWord;
22177
    }
22178
    /**
22179
    @internal
22180
    */
22181
    create() {
22182
        return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
22183
    }
22184
    /**
22185
    Get a search cursor for this query, searching through the given
22186
    range in the given state.
22187
    */
22188
    getCursor(state, from = 0, to) {
22189
        let st = state.doc ? state : EditorState.create({ doc: state });
22190
        if (to == null)
22191
            to = st.doc.length;
22192
        return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
22193
    }
22194
}
22195
class QueryType {
22196
    constructor(spec) {
22197
        this.spec = spec;
22198
    }
22199
}
22200
function stringCursor(spec, state, from, to) {
22201
    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);
22202
}
22203
function stringWordTest(doc, categorizer) {
22204
    return (from, to, buf, bufPos) => {
22205
        if (bufPos > from || bufPos + buf.length < to) {
22206
            bufPos = Math.max(0, from - 2);
22207
            buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2));
22208
        }
22209
        return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word ||
22210
            categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) &&
22211
            (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word ||
22212
                categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
22213
    };
22214
}
22215
class StringQuery extends QueryType {
22216
    constructor(spec) {
22217
        super(spec);
22218
    }
22219
    nextMatch(state, curFrom, curTo) {
22220
        let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
1441 ariadna 22221
        if (cursor.done) {
22222
            let end = Math.min(state.doc.length, curFrom + this.spec.unquoted.length);
22223
            cursor = stringCursor(this.spec, state, 0, end).nextOverlapping();
22224
        }
22225
        return cursor.done || cursor.value.from == curFrom && cursor.value.to == curTo ? null : cursor.value;
1 efrain 22226
    }
22227
    // Searching in reverse is, rather than implementing an inverted search
22228
    // cursor, done by scanning chunk after chunk forward.
22229
    prevMatchInRange(state, from, to) {
22230
        for (let pos = to;;) {
22231
            let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length);
22232
            let cursor = stringCursor(this.spec, state, start, pos), range = null;
22233
            while (!cursor.nextOverlapping().done)
22234
                range = cursor.value;
22235
            if (range)
22236
                return range;
22237
            if (start == from)
22238
                return null;
22239
            pos -= 10000 /* FindPrev.ChunkSize */;
22240
        }
22241
    }
22242
    prevMatch(state, curFrom, curTo) {
1441 ariadna 22243
        let found = this.prevMatchInRange(state, 0, curFrom);
22244
        if (!found)
22245
            found = this.prevMatchInRange(state, Math.max(0, curTo - this.spec.unquoted.length), state.doc.length);
22246
        return found && (found.from != curFrom || found.to != curTo) ? found : null;
1 efrain 22247
    }
22248
    getReplacement(_result) { return this.spec.unquote(this.spec.replace); }
22249
    matchAll(state, limit) {
22250
        let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
22251
        while (!cursor.next().done) {
22252
            if (ranges.length >= limit)
22253
                return null;
22254
            ranges.push(cursor.value);
22255
        }
22256
        return ranges;
22257
    }
22258
    highlight(state, from, to, add) {
22259
        let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
22260
        while (!cursor.next().done)
22261
            add(cursor.value.from, cursor.value.to);
22262
    }
22263
}
22264
function regexpCursor(spec, state, from, to) {
22265
    return new RegExpCursor(state.doc, spec.search, {
22266
        ignoreCase: !spec.caseSensitive,
22267
        test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
22268
    }, from, to);
22269
}
22270
function charBefore(str, index) {
22271
    return str.slice(findClusterBreak(str, index, false), index);
22272
}
22273
function charAfter(str, index) {
22274
    return str.slice(index, findClusterBreak(str, index));
22275
}
22276
function regexpWordTest(categorizer) {
22277
    return (_from, _to, match) => !match[0].length ||
22278
        (categorizer(charBefore(match.input, match.index)) != CharCategory.Word ||
22279
            categorizer(charAfter(match.input, match.index)) != CharCategory.Word) &&
22280
            (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word ||
22281
                categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
22282
}
22283
class RegExpQuery extends QueryType {
22284
    nextMatch(state, curFrom, curTo) {
22285
        let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
22286
        if (cursor.done)
22287
            cursor = regexpCursor(this.spec, state, 0, curFrom).next();
22288
        return cursor.done ? null : cursor.value;
22289
    }
22290
    prevMatchInRange(state, from, to) {
22291
        for (let size = 1;; size++) {
22292
            let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */);
22293
            let cursor = regexpCursor(this.spec, state, start, to), range = null;
22294
            while (!cursor.next().done)
22295
                range = cursor.value;
22296
            if (range && (start == from || range.from > start + 10))
22297
                return range;
22298
            if (start == from)
22299
                return null;
22300
        }
22301
    }
22302
    prevMatch(state, curFrom, curTo) {
22303
        return this.prevMatchInRange(state, 0, curFrom) ||
22304
            this.prevMatchInRange(state, curTo, state.doc.length);
22305
    }
22306
    getReplacement(result) {
1441 ariadna 22307
        return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i) => {
22308
            if (i == "&")
22309
                return result.match[0];
22310
            if (i == "$")
22311
                return "$";
22312
            for (let l = i.length; l > 0; l--) {
22313
                let n = +i.slice(0, l);
22314
                if (n > 0 && n < result.match.length)
22315
                    return result.match[n] + i.slice(l);
22316
            }
22317
            return m;
22318
        });
1 efrain 22319
    }
22320
    matchAll(state, limit) {
22321
        let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
22322
        while (!cursor.next().done) {
22323
            if (ranges.length >= limit)
22324
                return null;
22325
            ranges.push(cursor.value);
22326
        }
22327
        return ranges;
22328
    }
22329
    highlight(state, from, to, add) {
22330
        let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length));
22331
        while (!cursor.next().done)
22332
            add(cursor.value.from, cursor.value.to);
22333
    }
22334
}
22335
/**
22336
A state effect that updates the current search query. Note that
22337
this only has an effect if the search state has been initialized
22338
(by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or
22339
by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least
22340
once).
22341
*/
22342
const setSearchQuery = /*@__PURE__*/StateEffect.define();
22343
const togglePanel$1 = /*@__PURE__*/StateEffect.define();
22344
const searchState = /*@__PURE__*/StateField.define({
22345
    create(state) {
22346
        return new SearchState(defaultQuery(state).create(), null);
22347
    },
22348
    update(value, tr) {
22349
        for (let effect of tr.effects) {
22350
            if (effect.is(setSearchQuery))
22351
                value = new SearchState(effect.value.create(), value.panel);
22352
            else if (effect.is(togglePanel$1))
22353
                value = new SearchState(value.query, effect.value ? createSearchPanel : null);
22354
        }
22355
        return value;
22356
    },
22357
    provide: f => showPanel.from(f, val => val.panel)
22358
});
22359
class SearchState {
22360
    constructor(query, panel) {
22361
        this.query = query;
22362
        this.panel = panel;
22363
    }
22364
}
22365
const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
22366
const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
22367
    constructor(view) {
22368
        this.view = view;
22369
        this.decorations = this.highlight(view.state.field(searchState));
22370
    }
22371
    update(update) {
22372
        let state = update.state.field(searchState);
22373
        if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged)
22374
            this.decorations = this.highlight(state);
22375
    }
22376
    highlight({ query, panel }) {
22377
        if (!panel || !query.spec.valid)
22378
            return Decoration.none;
22379
        let { view } = this;
22380
        let builder = new RangeSetBuilder();
22381
        for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
22382
            let { from, to } = ranges[i];
22383
            while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */)
22384
                to = ranges[++i].to;
22385
            query.highlight(view.state, from, to, (from, to) => {
22386
                let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to);
22387
                builder.add(from, to, selected ? selectedMatchMark : matchMark);
22388
            });
22389
        }
22390
        return builder.finish();
22391
    }
22392
}, {
22393
    decorations: v => v.decorations
22394
});
22395
function searchCommand(f) {
22396
    return view => {
22397
        let state = view.state.field(searchState, false);
22398
        return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
22399
    };
22400
}
22401
/**
22402
Open the search panel if it isn't already open, and move the
22403
selection to the first match after the current main selection.
22404
Will wrap around to the start of the document when it reaches the
22405
end.
22406
*/
22407
const findNext = /*@__PURE__*/searchCommand((view, { query }) => {
22408
    let { to } = view.state.selection.main;
22409
    let next = query.nextMatch(view.state, to, to);
22410
    if (!next)
22411
        return false;
22412
    let selection = EditorSelection.single(next.from, next.to);
22413
    let config = view.state.facet(searchConfigFacet);
22414
    view.dispatch({
22415
        selection,
22416
        effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)],
22417
        userEvent: "select.search"
22418
    });
22419
    selectSearchInput(view);
22420
    return true;
22421
});
22422
/**
22423
Move the selection to the previous instance of the search query,
22424
before the current main selection. Will wrap past the start
22425
of the document to start searching at the end again.
22426
*/
22427
const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => {
22428
    let { state } = view, { from } = state.selection.main;
22429
    let prev = query.prevMatch(state, from, from);
22430
    if (!prev)
22431
        return false;
22432
    let selection = EditorSelection.single(prev.from, prev.to);
22433
    let config = view.state.facet(searchConfigFacet);
22434
    view.dispatch({
22435
        selection,
22436
        effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)],
22437
        userEvent: "select.search"
22438
    });
22439
    selectSearchInput(view);
22440
    return true;
22441
});
22442
/**
22443
Select all instances of the search query.
22444
*/
22445
const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => {
22446
    let ranges = query.matchAll(view.state, 1000);
22447
    if (!ranges || !ranges.length)
22448
        return false;
22449
    view.dispatch({
22450
        selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))),
22451
        userEvent: "select.search.matches"
22452
    });
22453
    return true;
22454
});
22455
/**
22456
Select all instances of the currently selected text.
22457
*/
22458
const selectSelectionMatches = ({ state, dispatch }) => {
22459
    let sel = state.selection;
22460
    if (sel.ranges.length > 1 || sel.main.empty)
22461
        return false;
22462
    let { from, to } = sel.main;
22463
    let ranges = [], main = 0;
22464
    for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) {
22465
        if (ranges.length > 1000)
22466
            return false;
22467
        if (cur.value.from == from)
22468
            main = ranges.length;
22469
        ranges.push(EditorSelection.range(cur.value.from, cur.value.to));
22470
    }
22471
    dispatch(state.update({
22472
        selection: EditorSelection.create(ranges, main),
22473
        userEvent: "select.search.matches"
22474
    }));
22475
    return true;
22476
};
22477
/**
22478
Replace the current match of the search query.
22479
*/
22480
const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => {
22481
    let { state } = view, { from, to } = state.selection.main;
22482
    if (state.readOnly)
22483
        return false;
1441 ariadna 22484
    let match = query.nextMatch(state, from, from);
22485
    if (!match)
1 efrain 22486
        return false;
1441 ariadna 22487
    let next = match;
1 efrain 22488
    let changes = [], selection, replacement;
22489
    let effects = [];
22490
    if (next.from == from && next.to == to) {
22491
        replacement = state.toText(query.getReplacement(next));
22492
        changes.push({ from: next.from, to: next.to, insert: replacement });
22493
        next = query.nextMatch(state, next.from, next.to);
22494
        effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
22495
    }
22496
    if (next) {
1441 ariadna 22497
        let off = changes.length == 0 || changes[0].from >= match.to ? 0 : match.to - match.from - replacement.length;
1 efrain 22498
        selection = EditorSelection.single(next.from - off, next.to - off);
22499
        effects.push(announceMatch(view, next));
22500
        effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
22501
    }
22502
    view.dispatch({
22503
        changes, selection, effects,
22504
        userEvent: "input.replace"
22505
    });
22506
    return true;
22507
});
22508
/**
22509
Replace all instances of the search query with the given
22510
replacement.
22511
*/
22512
const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => {
22513
    if (view.state.readOnly)
22514
        return false;
22515
    let changes = query.matchAll(view.state, 1e9).map(match => {
22516
        let { from, to } = match;
22517
        return { from, to, insert: query.getReplacement(match) };
22518
    });
22519
    if (!changes.length)
22520
        return false;
22521
    let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
22522
    view.dispatch({
22523
        changes,
22524
        effects: EditorView.announce.of(announceText),
22525
        userEvent: "input.replace.all"
22526
    });
22527
    return true;
22528
});
22529
function createSearchPanel(view) {
22530
    return view.state.facet(searchConfigFacet).createPanel(view);
22531
}
22532
function defaultQuery(state, fallback) {
22533
    var _a, _b, _c, _d, _e;
22534
    let sel = state.selection.main;
22535
    let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
22536
    if (fallback && !selText)
22537
        return fallback;
22538
    let config = state.facet(searchConfigFacet);
22539
    return new SearchQuery({
22540
        search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"),
22541
        caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive,
22542
        literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal,
22543
        regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config.regexp,
22544
        wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config.wholeWord
22545
    });
22546
}
22547
function getSearchInput(view) {
22548
    let panel = getPanel(view, createSearchPanel);
22549
    return panel && panel.dom.querySelector("[main-field]");
22550
}
22551
function selectSearchInput(view) {
22552
    let input = getSearchInput(view);
22553
    if (input && input == view.root.activeElement)
22554
        input.select();
22555
}
22556
/**
22557
Make sure the search panel is open and focused.
22558
*/
22559
const openSearchPanel = view => {
22560
    let state = view.state.field(searchState, false);
22561
    if (state && state.panel) {
22562
        let searchInput = getSearchInput(view);
22563
        if (searchInput && searchInput != view.root.activeElement) {
22564
            let query = defaultQuery(view.state, state.query.spec);
22565
            if (query.valid)
22566
                view.dispatch({ effects: setSearchQuery.of(query) });
22567
            searchInput.focus();
22568
            searchInput.select();
22569
        }
22570
    }
22571
    else {
22572
        view.dispatch({ effects: [
22573
                togglePanel$1.of(true),
22574
                state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
22575
            ] });
22576
    }
22577
    return true;
22578
};
22579
/**
22580
Close the search panel.
22581
*/
22582
const closeSearchPanel = view => {
22583
    let state = view.state.field(searchState, false);
22584
    if (!state || !state.panel)
22585
        return false;
22586
    let panel = getPanel(view, createSearchPanel);
22587
    if (panel && panel.dom.contains(view.root.activeElement))
22588
        view.focus();
22589
    view.dispatch({ effects: togglePanel$1.of(false) });
22590
    return true;
22591
};
22592
/**
22593
Default search-related key bindings.
22594
 
22595
 - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel)
22596
 - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext)
22597
 - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious)
22598
 - Mod-Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine)
22599
 - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence)
22600
*/
22601
const searchKeymap = [
22602
    { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
22603
    { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22604
    { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22605
    { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
22606
    { key: "Mod-Shift-l", run: selectSelectionMatches },
22607
    { key: "Mod-Alt-g", run: gotoLine },
22608
    { key: "Mod-d", run: selectNextOccurrence, preventDefault: true },
22609
];
22610
class SearchPanel {
22611
    constructor(view) {
22612
        this.view = view;
22613
        let query = this.query = view.state.field(searchState).query.spec;
22614
        this.commit = this.commit.bind(this);
22615
        this.searchField = crelt("input", {
22616
            value: query.search,
22617
            placeholder: phrase(view, "Find"),
22618
            "aria-label": phrase(view, "Find"),
22619
            class: "cm-textfield",
22620
            name: "search",
22621
            form: "",
22622
            "main-field": "true",
22623
            onchange: this.commit,
22624
            onkeyup: this.commit
22625
        });
22626
        this.replaceField = crelt("input", {
22627
            value: query.replace,
22628
            placeholder: phrase(view, "Replace"),
22629
            "aria-label": phrase(view, "Replace"),
22630
            class: "cm-textfield",
22631
            name: "replace",
22632
            form: "",
22633
            onchange: this.commit,
22634
            onkeyup: this.commit
22635
        });
22636
        this.caseField = crelt("input", {
22637
            type: "checkbox",
22638
            name: "case",
22639
            form: "",
22640
            checked: query.caseSensitive,
22641
            onchange: this.commit
22642
        });
22643
        this.reField = crelt("input", {
22644
            type: "checkbox",
22645
            name: "re",
22646
            form: "",
22647
            checked: query.regexp,
22648
            onchange: this.commit
22649
        });
22650
        this.wordField = crelt("input", {
22651
            type: "checkbox",
22652
            name: "word",
22653
            form: "",
22654
            checked: query.wholeWord,
22655
            onchange: this.commit
22656
        });
22657
        function button(name, onclick, content) {
22658
            return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content);
22659
        }
22660
        this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
22661
            this.searchField,
22662
            button("next", () => findNext(view), [phrase(view, "next")]),
22663
            button("prev", () => findPrevious(view), [phrase(view, "previous")]),
22664
            button("select", () => selectMatches(view), [phrase(view, "all")]),
22665
            crelt("label", null, [this.caseField, phrase(view, "match case")]),
22666
            crelt("label", null, [this.reField, phrase(view, "regexp")]),
22667
            crelt("label", null, [this.wordField, phrase(view, "by word")]),
22668
            ...view.state.readOnly ? [] : [
22669
                crelt("br"),
22670
                this.replaceField,
22671
                button("replace", () => replaceNext(view), [phrase(view, "replace")]),
22672
                button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
22673
            ],
22674
            crelt("button", {
22675
                name: "close",
22676
                onclick: () => closeSearchPanel(view),
22677
                "aria-label": phrase(view, "close"),
22678
                type: "button"
22679
            }, ["×"])
22680
        ]);
22681
    }
22682
    commit() {
22683
        let query = new SearchQuery({
22684
            search: this.searchField.value,
22685
            caseSensitive: this.caseField.checked,
22686
            regexp: this.reField.checked,
22687
            wholeWord: this.wordField.checked,
22688
            replace: this.replaceField.value,
22689
        });
22690
        if (!query.eq(this.query)) {
22691
            this.query = query;
22692
            this.view.dispatch({ effects: setSearchQuery.of(query) });
22693
        }
22694
    }
22695
    keydown(e) {
22696
        if (runScopeHandlers(this.view, e, "search-panel")) {
22697
            e.preventDefault();
22698
        }
22699
        else if (e.keyCode == 13 && e.target == this.searchField) {
22700
            e.preventDefault();
22701
            (e.shiftKey ? findPrevious : findNext)(this.view);
22702
        }
22703
        else if (e.keyCode == 13 && e.target == this.replaceField) {
22704
            e.preventDefault();
22705
            replaceNext(this.view);
22706
        }
22707
    }
22708
    update(update) {
22709
        for (let tr of update.transactions)
22710
            for (let effect of tr.effects) {
22711
                if (effect.is(setSearchQuery) && !effect.value.eq(this.query))
22712
                    this.setQuery(effect.value);
22713
            }
22714
    }
22715
    setQuery(query) {
22716
        this.query = query;
22717
        this.searchField.value = query.search;
22718
        this.replaceField.value = query.replace;
22719
        this.caseField.checked = query.caseSensitive;
22720
        this.reField.checked = query.regexp;
22721
        this.wordField.checked = query.wholeWord;
22722
    }
22723
    mount() {
22724
        this.searchField.select();
22725
    }
22726
    get pos() { return 80; }
22727
    get top() { return this.view.state.facet(searchConfigFacet).top; }
22728
}
22729
function phrase(view, phrase) { return view.state.phrase(phrase); }
22730
const AnnounceMargin = 30;
22731
const Break = /[\s\.,:;?!]/;
22732
function announceMatch(view, { from, to }) {
22733
    let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
22734
    let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
22735
    let text = view.state.sliceDoc(start, end);
22736
    if (start != line.from) {
22737
        for (let i = 0; i < AnnounceMargin; i++)
22738
            if (!Break.test(text[i + 1]) && Break.test(text[i])) {
22739
                text = text.slice(i);
22740
                break;
22741
            }
22742
    }
22743
    if (end != lineEnd) {
22744
        for (let i = text.length - 1; i > text.length - AnnounceMargin; i--)
22745
            if (!Break.test(text[i - 1]) && Break.test(text[i])) {
22746
                text = text.slice(0, i);
22747
                break;
22748
            }
22749
    }
22750
    return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`);
22751
}
22752
const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({
22753
    ".cm-panel.cm-search": {
22754
        padding: "2px 6px 4px",
22755
        position: "relative",
22756
        "& [name=close]": {
22757
            position: "absolute",
22758
            top: "0",
22759
            right: "4px",
22760
            backgroundColor: "inherit",
22761
            border: "none",
22762
            font: "inherit",
22763
            padding: 0,
22764
            margin: 0
22765
        },
22766
        "& input, & button, & label": {
22767
            margin: ".2em .6em .2em 0"
22768
        },
22769
        "& input[type=checkbox]": {
22770
            marginRight: ".2em"
22771
        },
22772
        "& label": {
22773
            fontSize: "80%",
22774
            whiteSpace: "pre"
22775
        }
22776
    },
22777
    "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
22778
    "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
22779
    "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
22780
    "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
22781
});
22782
const searchExtensions = [
22783
    searchState,
22784
    /*@__PURE__*/Prec.low(searchHighlighter),
22785
    baseTheme$2
22786
];
22787
 
22788
/**
22789
An instance of this is passed to completion source functions.
22790
*/
22791
class CompletionContext {
22792
    /**
22793
    Create a new completion context. (Mostly useful for testing
22794
    completion sources—in the editor, the extension will create
22795
    these for you.)
22796
    */
22797
    constructor(
22798
    /**
22799
    The editor state that the completion happens in.
22800
    */
22801
    state,
22802
    /**
22803
    The position at which the completion is happening.
22804
    */
22805
    pos,
22806
    /**
22807
    Indicates whether completion was activated explicitly, or
22808
    implicitly by typing. The usual way to respond to this is to
22809
    only return completions when either there is part of a
22810
    completable entity before the cursor, or `explicit` is true.
22811
    */
1441 ariadna 22812
    explicit,
22813
    /**
22814
    The editor view. May be undefined if the context was created
22815
    in a situation where there is no such view available, such as
22816
    in synchronous updates via
22817
    [`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
22818
    or when called by test code.
22819
    */
22820
    view) {
1 efrain 22821
        this.state = state;
22822
        this.pos = pos;
22823
        this.explicit = explicit;
1441 ariadna 22824
        this.view = view;
1 efrain 22825
        /**
22826
        @internal
22827
        */
22828
        this.abortListeners = [];
1441 ariadna 22829
        /**
22830
        @internal
22831
        */
22832
        this.abortOnDocChange = false;
1 efrain 22833
    }
22834
    /**
22835
    Get the extent, content, and (if there is a token) type of the
22836
    token before `this.pos`.
22837
    */
22838
    tokenBefore(types) {
22839
        let token = syntaxTree(this.state).resolveInner(this.pos, -1);
22840
        while (token && types.indexOf(token.name) < 0)
22841
            token = token.parent;
22842
        return token ? { from: token.from, to: this.pos,
22843
            text: this.state.sliceDoc(token.from, this.pos),
22844
            type: token.type } : null;
22845
    }
22846
    /**
22847
    Get the match of the given expression directly before the
22848
    cursor.
22849
    */
22850
    matchBefore(expr) {
22851
        let line = this.state.doc.lineAt(this.pos);
22852
        let start = Math.max(line.from, this.pos - 250);
22853
        let str = line.text.slice(start - line.from, this.pos - line.from);
22854
        let found = str.search(ensureAnchor(expr, false));
22855
        return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
22856
    }
22857
    /**
22858
    Yields true when the query has been aborted. Can be useful in
22859
    asynchronous queries to avoid doing work that will be ignored.
22860
    */
22861
    get aborted() { return this.abortListeners == null; }
22862
    /**
22863
    Allows you to register abort handlers, which will be called when
22864
    the query is
22865
    [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
1441 ariadna 22866
 
22867
    By default, running queries will not be aborted for regular
22868
    typing or backspacing, on the assumption that they are likely to
22869
    return a result with a
22870
    [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
22871
    allows the result to be used after all. Passing `onDocChange:
22872
    true` will cause this query to be aborted for any document
22873
    change.
1 efrain 22874
    */
1441 ariadna 22875
    addEventListener(type, listener, options) {
22876
        if (type == "abort" && this.abortListeners) {
1 efrain 22877
            this.abortListeners.push(listener);
1441 ariadna 22878
            if (options && options.onDocChange)
22879
                this.abortOnDocChange = true;
22880
        }
1 efrain 22881
    }
22882
}
22883
function toSet(chars) {
22884
    let flat = Object.keys(chars).join("");
22885
    let words = /\w/.test(flat);
22886
    if (words)
22887
        flat = flat.replace(/\w/g, "");
22888
    return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
22889
}
22890
function prefixMatch(options) {
22891
    let first = Object.create(null), rest = Object.create(null);
22892
    for (let { label } of options) {
22893
        first[label[0]] = true;
22894
        for (let i = 1; i < label.length; i++)
22895
            rest[label[i]] = true;
22896
    }
22897
    let source = toSet(first) + toSet(rest) + "*$";
22898
    return [new RegExp("^" + source), new RegExp(source)];
22899
}
22900
/**
22901
Given a a fixed array of options, return an autocompleter that
22902
completes them.
22903
*/
22904
function completeFromList(list) {
22905
    let options = list.map(o => typeof o == "string" ? { label: o } : o);
22906
    let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
22907
    return (context) => {
22908
        let token = context.matchBefore(match);
22909
        return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null;
22910
    };
22911
}
22912
/**
22913
Wrap the given completion source so that it will not fire when the
22914
cursor is in a syntax node with one of the given names.
22915
*/
22916
function ifNotIn(nodes, source) {
22917
    return (context) => {
22918
        for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
22919
            if (nodes.indexOf(pos.name) > -1)
22920
                return null;
22921
            if (pos.type.isTop)
22922
                break;
22923
        }
22924
        return source(context);
22925
    };
22926
}
22927
class Option {
22928
    constructor(completion, source, match, score) {
22929
        this.completion = completion;
22930
        this.source = source;
22931
        this.match = match;
22932
        this.score = score;
22933
    }
22934
}
22935
function cur(state) { return state.selection.main.from; }
22936
// Make sure the given regexp has a $ at its end and, if `start` is
22937
// true, a ^ at its start.
22938
function ensureAnchor(expr, start) {
22939
    var _a;
22940
    let { source } = expr;
22941
    let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
22942
    if (!addStart && !addEnd)
22943
        return expr;
22944
    return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : ""));
22945
}
22946
/**
22947
This annotation is added to transactions that are produced by
22948
picking a completion.
22949
*/
22950
const pickedCompletion = /*@__PURE__*/Annotation.define();
22951
/**
22952
Helper function that returns a transaction spec which inserts a
22953
completion's text in the main selection range, and any other
22954
selection range that has the same text in front of it.
22955
*/
22956
function insertCompletionText(state, text, from, to) {
22957
    let { main } = state.selection, fromOff = from - main.from, toOff = to - main.from;
22958
    return Object.assign(Object.assign({}, state.changeByRange(range => {
22959
        if (range != main && from != to &&
22960
            state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to))
22961
            return { range };
1441 ariadna 22962
        let lines = state.toText(text);
1 efrain 22963
        return {
1441 ariadna 22964
            changes: { from: range.from + fromOff, to: to == main.from ? range.to : range.from + toOff, insert: lines },
22965
            range: EditorSelection.cursor(range.from + fromOff + lines.length)
1 efrain 22966
        };
22967
    })), { scrollIntoView: true, userEvent: "input.complete" });
22968
}
22969
const SourceCache = /*@__PURE__*/new WeakMap();
22970
function asSource(source) {
22971
    if (!Array.isArray(source))
22972
        return source;
22973
    let known = SourceCache.get(source);
22974
    if (!known)
22975
        SourceCache.set(source, known = completeFromList(source));
22976
    return known;
22977
}
22978
const startCompletionEffect = /*@__PURE__*/StateEffect.define();
22979
const closeCompletionEffect = /*@__PURE__*/StateEffect.define();
22980
 
22981
// A pattern matcher for fuzzy completion matching. Create an instance
22982
// once for a pattern, and then use that to match any number of
22983
// completions.
22984
class FuzzyMatcher {
22985
    constructor(pattern) {
22986
        this.pattern = pattern;
22987
        this.chars = [];
22988
        this.folded = [];
22989
        // Buffers reused by calls to `match` to track matched character
22990
        // positions.
22991
        this.any = [];
22992
        this.precise = [];
22993
        this.byWord = [];
22994
        this.score = 0;
22995
        this.matched = [];
22996
        for (let p = 0; p < pattern.length;) {
22997
            let char = codePointAt(pattern, p), size = codePointSize(char);
22998
            this.chars.push(char);
22999
            let part = pattern.slice(p, p + size), upper = part.toUpperCase();
23000
            this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
23001
            p += size;
23002
        }
23003
        this.astral = pattern.length != this.chars.length;
23004
    }
23005
    ret(score, matched) {
23006
        this.score = score;
23007
        this.matched = matched;
23008
        return this;
23009
    }
23010
    // Matches a given word (completion) against the pattern (input).
23011
    // Will return a boolean indicating whether there was a match and,
23012
    // on success, set `this.score` to the score, `this.matched` to an
23013
    // array of `from, to` pairs indicating the matched parts of `word`.
23014
    //
23015
    // The score is a number that is more negative the worse the match
23016
    // is. See `Penalty` above.
23017
    match(word) {
23018
        if (this.pattern.length == 0)
23019
            return this.ret(-100 /* Penalty.NotFull */, []);
23020
        if (word.length < this.pattern.length)
23021
            return null;
23022
        let { chars, folded, any, precise, byWord } = this;
23023
        // For single-character queries, only match when they occur right
23024
        // at the start
23025
        if (chars.length == 1) {
23026
            let first = codePointAt(word, 0), firstSize = codePointSize(first);
23027
            let score = firstSize == word.length ? 0 : -100 /* Penalty.NotFull */;
23028
            if (first == chars[0]) ;
23029
            else if (first == folded[0])
23030
                score += -200 /* Penalty.CaseFold */;
23031
            else
23032
                return null;
23033
            return this.ret(score, [0, firstSize]);
23034
        }
23035
        let direct = word.indexOf(this.pattern);
23036
        if (direct == 0)
23037
            return this.ret(word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */, [0, this.pattern.length]);
23038
        let len = chars.length, anyTo = 0;
23039
        if (direct < 0) {
23040
            for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
23041
                let next = codePointAt(word, i);
23042
                if (next == chars[anyTo] || next == folded[anyTo])
23043
                    any[anyTo++] = i;
23044
                i += codePointSize(next);
23045
            }
23046
            // No match, exit immediately
23047
            if (anyTo < len)
23048
                return null;
23049
        }
23050
        // This tracks the extent of the precise (non-folded, not
23051
        // necessarily adjacent) match
23052
        let preciseTo = 0;
23053
        // Tracks whether there is a match that hits only characters that
23054
        // appear to be starting words. `byWordFolded` is set to true when
23055
        // a case folded character is encountered in such a match
23056
        let byWordTo = 0, byWordFolded = false;
23057
        // If we've found a partial adjacent match, these track its state
23058
        let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
23059
        let hasLower = /[a-z]/.test(word), wordAdjacent = true;
23060
        // Go over the option's text, scanning for the various kinds of matches
23061
        for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* Tp.NonWord */; i < e && byWordTo < len;) {
23062
            let next = codePointAt(word, i);
23063
            if (direct < 0) {
23064
                if (preciseTo < len && next == chars[preciseTo])
23065
                    precise[preciseTo++] = i;
23066
                if (adjacentTo < len) {
23067
                    if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
23068
                        if (adjacentTo == 0)
23069
                            adjacentStart = i;
23070
                        adjacentEnd = i + 1;
23071
                        adjacentTo++;
23072
                    }
23073
                    else {
23074
                        adjacentTo = 0;
23075
                    }
23076
                }
23077
            }
23078
            let ch, type = next < 0xff
23079
                ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Tp.Lower */ : next >= 65 && next <= 90 ? 1 /* Tp.Upper */ : 0 /* Tp.NonWord */)
23080
                : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Tp.Upper */ : ch != ch.toUpperCase() ? 2 /* Tp.Lower */ : 0 /* Tp.NonWord */);
23081
            if (!i || type == 1 /* Tp.Upper */ && hasLower || prevType == 0 /* Tp.NonWord */ && type != 0 /* Tp.NonWord */) {
23082
                if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))
23083
                    byWord[byWordTo++] = i;
23084
                else if (byWord.length)
23085
                    wordAdjacent = false;
23086
            }
23087
            prevType = type;
23088
            i += codePointSize(next);
23089
        }
23090
        if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
23091
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0), byWord, word);
23092
        if (adjacentTo == len && adjacentStart == 0)
23093
            return this.ret(-200 /* Penalty.CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* Penalty.NotFull */), [0, adjacentEnd]);
23094
        if (direct > -1)
23095
            return this.ret(-700 /* Penalty.NotStart */ - word.length, [direct, direct + this.pattern.length]);
23096
        if (adjacentTo == len)
23097
            return this.ret(-200 /* Penalty.CaseFold */ + -700 /* Penalty.NotStart */ - word.length, [adjacentStart, adjacentEnd]);
23098
        if (byWordTo == len)
23099
            return this.result(-100 /* Penalty.ByWord */ + (byWordFolded ? -200 /* Penalty.CaseFold */ : 0) + -700 /* Penalty.NotStart */ +
23100
                (wordAdjacent ? 0 : -1100 /* Penalty.Gap */), byWord, word);
23101
        return chars.length == 2 ? null
23102
            : this.result((any[0] ? -700 /* Penalty.NotStart */ : 0) + -200 /* Penalty.CaseFold */ + -1100 /* Penalty.Gap */, any, word);
23103
    }
23104
    result(score, positions, word) {
23105
        let result = [], i = 0;
23106
        for (let pos of positions) {
23107
            let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
23108
            if (i && result[i - 1] == pos)
23109
                result[i - 1] = to;
23110
            else {
23111
                result[i++] = pos;
23112
                result[i++] = to;
23113
            }
23114
        }
23115
        return this.ret(score - word.length, result);
23116
    }
23117
}
23118
class StrictMatcher {
23119
    constructor(pattern) {
23120
        this.pattern = pattern;
23121
        this.matched = [];
23122
        this.score = 0;
23123
        this.folded = pattern.toLowerCase();
23124
    }
23125
    match(word) {
23126
        if (word.length < this.pattern.length)
23127
            return null;
23128
        let start = word.slice(0, this.pattern.length);
23129
        let match = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 /* Penalty.CaseFold */ : null;
23130
        if (match == null)
23131
            return null;
23132
        this.matched = [0, start.length];
23133
        this.score = match + (word.length == this.pattern.length ? 0 : -100 /* Penalty.NotFull */);
23134
        return this;
23135
    }
23136
}
23137
 
23138
const completionConfig = /*@__PURE__*/Facet.define({
23139
    combine(configs) {
23140
        return combineConfig(configs, {
23141
            activateOnTyping: true,
1441 ariadna 23142
            activateOnCompletion: () => false,
1 efrain 23143
            activateOnTypingDelay: 100,
23144
            selectOnOpen: true,
23145
            override: null,
23146
            closeOnBlur: true,
23147
            maxRenderedOptions: 100,
23148
            defaultKeymap: true,
23149
            tooltipClass: () => "",
23150
            optionClass: () => "",
23151
            aboveCursor: false,
23152
            icons: true,
23153
            addToOptions: [],
23154
            positionInfo: defaultPositionInfo,
23155
            filterStrict: false,
23156
            compareCompletions: (a, b) => a.label.localeCompare(b.label),
23157
            interactionDelay: 75,
23158
            updateSyncTime: 100
23159
        }, {
23160
            defaultKeymap: (a, b) => a && b,
23161
            closeOnBlur: (a, b) => a && b,
23162
            icons: (a, b) => a && b,
23163
            tooltipClass: (a, b) => c => joinClass(a(c), b(c)),
23164
            optionClass: (a, b) => c => joinClass(a(c), b(c)),
23165
            addToOptions: (a, b) => a.concat(b),
23166
            filterStrict: (a, b) => a || b,
23167
        });
23168
    }
23169
});
23170
function joinClass(a, b) {
23171
    return a ? b ? a + " " + b : a : b;
23172
}
23173
function defaultPositionInfo(view, list, option, info, space, tooltip) {
23174
    let rtl = view.textDirection == Direction.RTL, left = rtl, narrow = false;
23175
    let side = "top", offset, maxWidth;
23176
    let spaceLeft = list.left - space.left, spaceRight = space.right - list.right;
23177
    let infoWidth = info.right - info.left, infoHeight = info.bottom - info.top;
23178
    if (left && spaceLeft < Math.min(infoWidth, spaceRight))
23179
        left = false;
23180
    else if (!left && spaceRight < Math.min(infoWidth, spaceLeft))
23181
        left = true;
23182
    if (infoWidth <= (left ? spaceLeft : spaceRight)) {
23183
        offset = Math.max(space.top, Math.min(option.top, space.bottom - infoHeight)) - list.top;
23184
        maxWidth = Math.min(400 /* Info.Width */, left ? spaceLeft : spaceRight);
23185
    }
23186
    else {
23187
        narrow = true;
23188
        maxWidth = Math.min(400 /* Info.Width */, (rtl ? list.right : space.right - list.left) - 30 /* Info.Margin */);
23189
        let spaceBelow = space.bottom - list.bottom;
23190
        if (spaceBelow >= infoHeight || spaceBelow > list.top) { // Below the completion
23191
            offset = option.bottom - list.top;
23192
        }
23193
        else { // Above it
23194
            side = "bottom";
23195
            offset = list.bottom - option.top;
23196
        }
23197
    }
23198
    let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;
23199
    let scaleX = (list.right - list.left) / tooltip.offsetWidth;
23200
    return {
23201
        style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
23202
        class: "cm-completionInfo-" + (narrow ? (rtl ? "left-narrow" : "right-narrow") : left ? "left" : "right")
23203
    };
23204
}
23205
 
23206
function optionContent(config) {
23207
    let content = config.addToOptions.slice();
23208
    if (config.icons)
23209
        content.push({
23210
            render(completion) {
23211
                let icon = document.createElement("div");
23212
                icon.classList.add("cm-completionIcon");
23213
                if (completion.type)
23214
                    icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
23215
                icon.setAttribute("aria-hidden", "true");
23216
                return icon;
23217
            },
23218
            position: 20
23219
        });
23220
    content.push({
23221
        render(completion, _s, _v, match) {
23222
            let labelElt = document.createElement("span");
23223
            labelElt.className = "cm-completionLabel";
23224
            let label = completion.displayLabel || completion.label, off = 0;
23225
            for (let j = 0; j < match.length;) {
23226
                let from = match[j++], to = match[j++];
23227
                if (from > off)
23228
                    labelElt.appendChild(document.createTextNode(label.slice(off, from)));
23229
                let span = labelElt.appendChild(document.createElement("span"));
23230
                span.appendChild(document.createTextNode(label.slice(from, to)));
23231
                span.className = "cm-completionMatchedText";
23232
                off = to;
23233
            }
23234
            if (off < label.length)
23235
                labelElt.appendChild(document.createTextNode(label.slice(off)));
23236
            return labelElt;
23237
        },
23238
        position: 50
23239
    }, {
23240
        render(completion) {
23241
            if (!completion.detail)
23242
                return null;
23243
            let detailElt = document.createElement("span");
23244
            detailElt.className = "cm-completionDetail";
23245
            detailElt.textContent = completion.detail;
23246
            return detailElt;
23247
        },
23248
        position: 80
23249
    });
23250
    return content.sort((a, b) => a.position - b.position).map(a => a.render);
23251
}
23252
function rangeAroundSelected(total, selected, max) {
23253
    if (total <= max)
23254
        return { from: 0, to: total };
23255
    if (selected < 0)
23256
        selected = 0;
23257
    if (selected <= (total >> 1)) {
23258
        let off = Math.floor(selected / max);
23259
        return { from: off * max, to: (off + 1) * max };
23260
    }
23261
    let off = Math.floor((total - selected) / max);
23262
    return { from: total - (off + 1) * max, to: total - off * max };
23263
}
23264
class CompletionTooltip {
23265
    constructor(view, stateField, applyCompletion) {
23266
        this.view = view;
23267
        this.stateField = stateField;
23268
        this.applyCompletion = applyCompletion;
23269
        this.info = null;
23270
        this.infoDestroy = null;
23271
        this.placeInfoReq = {
23272
            read: () => this.measureInfo(),
23273
            write: (pos) => this.placeInfo(pos),
23274
            key: this
23275
        };
23276
        this.space = null;
23277
        this.currentClass = "";
23278
        let cState = view.state.field(stateField);
23279
        let { options, selected } = cState.open;
23280
        let config = view.state.facet(completionConfig);
23281
        this.optionContent = optionContent(config);
23282
        this.optionClass = config.optionClass;
23283
        this.tooltipClass = config.tooltipClass;
23284
        this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
23285
        this.dom = document.createElement("div");
23286
        this.dom.className = "cm-tooltip-autocomplete";
23287
        this.updateTooltipClass(view.state);
23288
        this.dom.addEventListener("mousedown", (e) => {
23289
            let { options } = view.state.field(stateField).open;
23290
            for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
23291
                if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
23292
                    this.applyCompletion(view, options[+match[1]]);
23293
                    e.preventDefault();
23294
                    return;
23295
                }
23296
            }
23297
        });
23298
        this.dom.addEventListener("focusout", (e) => {
23299
            let state = view.state.field(this.stateField, false);
23300
            if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur &&
23301
                e.relatedTarget != view.contentDOM)
23302
                view.dispatch({ effects: closeCompletionEffect.of(null) });
23303
        });
23304
        this.showOptions(options, cState.id);
23305
    }
23306
    mount() { this.updateSel(); }
23307
    showOptions(options, id) {
23308
        if (this.list)
23309
            this.list.remove();
23310
        this.list = this.dom.appendChild(this.createListBox(options, id, this.range));
23311
        this.list.addEventListener("scroll", () => {
23312
            if (this.info)
23313
                this.view.requestMeasure(this.placeInfoReq);
23314
        });
23315
    }
23316
    update(update) {
23317
        var _a;
23318
        let cState = update.state.field(this.stateField);
23319
        let prevState = update.startState.field(this.stateField);
23320
        this.updateTooltipClass(update.state);
23321
        if (cState != prevState) {
23322
            let { options, selected, disabled } = cState.open;
23323
            if (!prevState.open || prevState.open.options != options) {
23324
                this.range = rangeAroundSelected(options.length, selected, update.state.facet(completionConfig).maxRenderedOptions);
23325
                this.showOptions(options, cState.id);
23326
            }
23327
            this.updateSel();
23328
            if (disabled != ((_a = prevState.open) === null || _a === void 0 ? void 0 : _a.disabled))
23329
                this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
23330
        }
23331
    }
23332
    updateTooltipClass(state) {
23333
        let cls = this.tooltipClass(state);
23334
        if (cls != this.currentClass) {
23335
            for (let c of this.currentClass.split(" "))
23336
                if (c)
23337
                    this.dom.classList.remove(c);
23338
            for (let c of cls.split(" "))
23339
                if (c)
23340
                    this.dom.classList.add(c);
23341
            this.currentClass = cls;
23342
        }
23343
    }
23344
    positioned(space) {
23345
        this.space = space;
23346
        if (this.info)
23347
            this.view.requestMeasure(this.placeInfoReq);
23348
    }
23349
    updateSel() {
23350
        let cState = this.view.state.field(this.stateField), open = cState.open;
23351
        if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
23352
            this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
23353
            this.showOptions(open.options, cState.id);
23354
        }
23355
        if (this.updateSelectedOption(open.selected)) {
23356
            this.destroyInfo();
23357
            let { completion } = open.options[open.selected];
23358
            let { info } = completion;
23359
            if (!info)
23360
                return;
23361
            let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
23362
            if (!infoResult)
23363
                return;
23364
            if ("then" in infoResult) {
23365
                infoResult.then(obj => {
23366
                    if (obj && this.view.state.field(this.stateField, false) == cState)
23367
                        this.addInfoPane(obj, completion);
23368
                }).catch(e => logException(this.view.state, e, "completion info"));
23369
            }
23370
            else {
23371
                this.addInfoPane(infoResult, completion);
23372
            }
23373
        }
23374
    }
23375
    addInfoPane(content, completion) {
23376
        this.destroyInfo();
23377
        let wrap = this.info = document.createElement("div");
23378
        wrap.className = "cm-tooltip cm-completionInfo";
23379
        if (content.nodeType != null) {
23380
            wrap.appendChild(content);
23381
            this.infoDestroy = null;
23382
        }
23383
        else {
23384
            let { dom, destroy } = content;
23385
            wrap.appendChild(dom);
23386
            this.infoDestroy = destroy || null;
23387
        }
23388
        this.dom.appendChild(wrap);
23389
        this.view.requestMeasure(this.placeInfoReq);
23390
    }
23391
    updateSelectedOption(selected) {
23392
        let set = null;
23393
        for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
23394
            if (opt.nodeName != "LI" || !opt.id) {
23395
                i--; // A section header
23396
            }
23397
            else if (i == selected) {
23398
                if (!opt.hasAttribute("aria-selected")) {
23399
                    opt.setAttribute("aria-selected", "true");
23400
                    set = opt;
23401
                }
23402
            }
23403
            else {
23404
                if (opt.hasAttribute("aria-selected"))
23405
                    opt.removeAttribute("aria-selected");
23406
            }
23407
        }
23408
        if (set)
23409
            scrollIntoView(this.list, set);
23410
        return set;
23411
    }
23412
    measureInfo() {
23413
        let sel = this.dom.querySelector("[aria-selected]");
23414
        if (!sel || !this.info)
23415
            return null;
23416
        let listRect = this.dom.getBoundingClientRect();
23417
        let infoRect = this.info.getBoundingClientRect();
23418
        let selRect = sel.getBoundingClientRect();
23419
        let space = this.space;
23420
        if (!space) {
1441 ariadna 23421
            let docElt = this.dom.ownerDocument.documentElement;
23422
            space = { left: 0, top: 0, right: docElt.clientWidth, bottom: docElt.clientHeight };
1 efrain 23423
        }
23424
        if (selRect.top > Math.min(space.bottom, listRect.bottom) - 10 ||
23425
            selRect.bottom < Math.max(space.top, listRect.top) + 10)
23426
            return null;
23427
        return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space, this.dom);
23428
    }
23429
    placeInfo(pos) {
23430
        if (this.info) {
23431
            if (pos) {
23432
                if (pos.style)
23433
                    this.info.style.cssText = pos.style;
23434
                this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
23435
            }
23436
            else {
23437
                this.info.style.cssText = "top: -1e6px";
23438
            }
23439
        }
23440
    }
23441
    createListBox(options, id, range) {
23442
        const ul = document.createElement("ul");
23443
        ul.id = id;
23444
        ul.setAttribute("role", "listbox");
23445
        ul.setAttribute("aria-expanded", "true");
23446
        ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
1441 ariadna 23447
        ul.addEventListener("mousedown", e => {
23448
            // Prevent focus change when clicking the scrollbar
23449
            if (e.target == ul)
23450
                e.preventDefault();
23451
        });
1 efrain 23452
        let curSection = null;
23453
        for (let i = range.from; i < range.to; i++) {
23454
            let { completion, match } = options[i], { section } = completion;
23455
            if (section) {
23456
                let name = typeof section == "string" ? section : section.name;
23457
                if (name != curSection && (i > range.from || range.from == 0)) {
23458
                    curSection = name;
23459
                    if (typeof section != "string" && section.header) {
23460
                        ul.appendChild(section.header(section));
23461
                    }
23462
                    else {
23463
                        let header = ul.appendChild(document.createElement("completion-section"));
23464
                        header.textContent = name;
23465
                    }
23466
                }
23467
            }
23468
            const li = ul.appendChild(document.createElement("li"));
23469
            li.id = id + "-" + i;
23470
            li.setAttribute("role", "option");
23471
            let cls = this.optionClass(completion);
23472
            if (cls)
23473
                li.className = cls;
23474
            for (let source of this.optionContent) {
23475
                let node = source(completion, this.view.state, this.view, match);
23476
                if (node)
23477
                    li.appendChild(node);
23478
            }
23479
        }
23480
        if (range.from)
23481
            ul.classList.add("cm-completionListIncompleteTop");
23482
        if (range.to < options.length)
23483
            ul.classList.add("cm-completionListIncompleteBottom");
23484
        return ul;
23485
    }
23486
    destroyInfo() {
23487
        if (this.info) {
23488
            if (this.infoDestroy)
23489
                this.infoDestroy();
23490
            this.info.remove();
23491
            this.info = null;
23492
        }
23493
    }
23494
    destroy() {
23495
        this.destroyInfo();
23496
    }
23497
}
23498
function completionTooltip(stateField, applyCompletion) {
23499
    return (view) => new CompletionTooltip(view, stateField, applyCompletion);
23500
}
23501
function scrollIntoView(container, element) {
23502
    let parent = container.getBoundingClientRect();
23503
    let self = element.getBoundingClientRect();
23504
    let scaleY = parent.height / container.offsetHeight;
23505
    if (self.top < parent.top)
23506
        container.scrollTop -= (parent.top - self.top) / scaleY;
23507
    else if (self.bottom > parent.bottom)
23508
        container.scrollTop += (self.bottom - parent.bottom) / scaleY;
23509
}
23510
 
23511
// Used to pick a preferred option when two options with the same
23512
// label occur in the result.
23513
function score(option) {
23514
    return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +
23515
        (option.type ? 1 : 0);
23516
}
23517
function sortOptions(active, state) {
23518
    let options = [];
23519
    let sections = null;
23520
    let addOption = (option) => {
23521
        options.push(option);
23522
        let { section } = option.completion;
23523
        if (section) {
23524
            if (!sections)
23525
                sections = [];
23526
            let name = typeof section == "string" ? section : section.name;
23527
            if (!sections.some(s => s.name == name))
23528
                sections.push(typeof section == "string" ? { name } : section);
23529
        }
23530
    };
23531
    let conf = state.facet(completionConfig);
23532
    for (let a of active)
23533
        if (a.hasResult()) {
23534
            let getMatch = a.result.getMatch;
23535
            if (a.result.filter === false) {
23536
                for (let option of a.result.options) {
23537
                    addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));
23538
                }
23539
            }
23540
            else {
23541
                let pattern = state.sliceDoc(a.from, a.to), match;
23542
                let matcher = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
23543
                for (let option of a.result.options)
23544
                    if (match = matcher.match(option.label)) {
23545
                        let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
23546
                        addOption(new Option(option, a.source, matched, match.score + (option.boost || 0)));
23547
                    }
23548
            }
23549
        }
23550
    if (sections) {
23551
        let sectionOrder = Object.create(null), pos = 0;
23552
        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); };
23553
        for (let s of sections.sort(cmp)) {
23554
            pos -= 1e5;
23555
            sectionOrder[s.name] = pos;
23556
        }
23557
        for (let option of options) {
23558
            let { section } = option.completion;
23559
            if (section)
23560
                option.score += sectionOrder[typeof section == "string" ? section : section.name];
23561
        }
23562
    }
23563
    let result = [], prev = null;
23564
    let compare = conf.compareCompletions;
23565
    for (let opt of options.sort((a, b) => (b.score - a.score) || compare(a.completion, b.completion))) {
23566
        let cur = opt.completion;
23567
        if (!prev || prev.label != cur.label || prev.detail != cur.detail ||
23568
            (prev.type != null && cur.type != null && prev.type != cur.type) ||
23569
            prev.apply != cur.apply || prev.boost != cur.boost)
23570
            result.push(opt);
23571
        else if (score(opt.completion) > score(prev))
23572
            result[result.length - 1] = opt;
23573
        prev = opt.completion;
23574
    }
23575
    return result;
23576
}
23577
class CompletionDialog {
23578
    constructor(options, attrs, tooltip, timestamp, selected, disabled) {
23579
        this.options = options;
23580
        this.attrs = attrs;
23581
        this.tooltip = tooltip;
23582
        this.timestamp = timestamp;
23583
        this.selected = selected;
23584
        this.disabled = disabled;
23585
    }
23586
    setSelected(selected, id) {
23587
        return selected == this.selected || selected >= this.options.length ? this
23588
            : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected, this.disabled);
23589
    }
1441 ariadna 23590
    static build(active, state, id, prev, conf, didSetActive) {
23591
        if (prev && !didSetActive && active.some(s => s.isPending))
23592
            return prev.setDisabled();
1 efrain 23593
        let options = sortOptions(active, state);
1441 ariadna 23594
        if (!options.length)
23595
            return prev && active.some(a => a.isPending) ? prev.setDisabled() : null;
1 efrain 23596
        let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
23597
        if (prev && prev.selected != selected && prev.selected != -1) {
23598
            let selectedValue = prev.options[prev.selected].completion;
23599
            for (let i = 0; i < options.length; i++)
23600
                if (options[i].completion == selectedValue) {
23601
                    selected = i;
23602
                    break;
23603
                }
23604
        }
23605
        return new CompletionDialog(options, makeAttrs(id, selected), {
23606
            pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
23607
            create: createTooltip,
23608
            above: conf.aboveCursor,
23609
        }, prev ? prev.timestamp : Date.now(), selected, false);
23610
    }
23611
    map(changes) {
23612
        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);
23613
    }
1441 ariadna 23614
    setDisabled() {
23615
        return new CompletionDialog(this.options, this.attrs, this.tooltip, this.timestamp, this.selected, true);
23616
    }
1 efrain 23617
}
23618
class CompletionState {
23619
    constructor(active, id, open) {
23620
        this.active = active;
23621
        this.id = id;
23622
        this.open = open;
23623
    }
23624
    static start() {
23625
        return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
23626
    }
23627
    update(tr) {
23628
        let { state } = tr, conf = state.facet(completionConfig);
23629
        let sources = conf.override ||
23630
            state.languageDataAt("autocomplete", cur(state)).map(asSource);
23631
        let active = sources.map(source => {
23632
            let value = this.active.find(s => s.source == source) ||
23633
                new ActiveSource(source, this.active.some(a => a.state != 0 /* State.Inactive */) ? 1 /* State.Pending */ : 0 /* State.Inactive */);
23634
            return value.update(tr, conf);
23635
        });
23636
        if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
23637
            active = this.active;
1441 ariadna 23638
        let open = this.open, didSet = tr.effects.some(e => e.is(setActiveEffect));
1 efrain 23639
        if (open && tr.docChanged)
23640
            open = open.map(tr.changes);
23641
        if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||
1441 ariadna 23642
            !sameResults(active, this.active) || didSet)
23643
            open = CompletionDialog.build(active, state, this.id, open, conf, didSet);
23644
        else if (open && open.disabled && !active.some(a => a.isPending))
1 efrain 23645
            open = null;
1441 ariadna 23646
        if (!open && active.every(a => !a.isPending) && active.some(a => a.hasResult()))
1 efrain 23647
            active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* State.Inactive */) : a);
23648
        for (let effect of tr.effects)
23649
            if (effect.is(setSelectedEffect))
23650
                open = open && open.setSelected(effect.value, this.id);
23651
        return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
23652
    }
23653
    get tooltip() { return this.open ? this.open.tooltip : null; }
1441 ariadna 23654
    get attrs() { return this.open ? this.open.attrs : this.active.length ? baseAttrs : noAttrs; }
1 efrain 23655
}
23656
function sameResults(a, b) {
23657
    if (a == b)
23658
        return true;
23659
    for (let iA = 0, iB = 0;;) {
1441 ariadna 23660
        while (iA < a.length && !a[iA].hasResult())
1 efrain 23661
            iA++;
1441 ariadna 23662
        while (iB < b.length && !b[iB].hasResult())
1 efrain 23663
            iB++;
23664
        let endA = iA == a.length, endB = iB == b.length;
23665
        if (endA || endB)
23666
            return endA == endB;
23667
        if (a[iA++].result != b[iB++].result)
23668
            return false;
23669
    }
23670
}
23671
const baseAttrs = {
23672
    "aria-autocomplete": "list"
23673
};
1441 ariadna 23674
const noAttrs = {};
1 efrain 23675
function makeAttrs(id, selected) {
23676
    let result = {
23677
        "aria-autocomplete": "list",
23678
        "aria-haspopup": "listbox",
23679
        "aria-controls": id
23680
    };
23681
    if (selected > -1)
23682
        result["aria-activedescendant"] = id + "-" + selected;
23683
    return result;
23684
}
23685
const none = [];
1441 ariadna 23686
function getUpdateType(tr, conf) {
23687
    if (tr.isUserEvent("input.complete")) {
23688
        let completion = tr.annotation(pickedCompletion);
23689
        if (completion && conf.activateOnCompletion(completion))
23690
            return 4 /* UpdateType.Activate */ | 8 /* UpdateType.Reset */;
23691
    }
23692
    let typing = tr.isUserEvent("input.type");
23693
    return typing && conf.activateOnTyping ? 4 /* UpdateType.Activate */ | 1 /* UpdateType.Typing */
23694
        : typing ? 1 /* UpdateType.Typing */
23695
            : tr.isUserEvent("delete.backward") ? 2 /* UpdateType.Backspacing */
23696
                : tr.selection ? 8 /* UpdateType.Reset */
23697
                    : tr.docChanged ? 16 /* UpdateType.ResetIfTouching */ : 0 /* UpdateType.None */;
1 efrain 23698
}
23699
class ActiveSource {
1441 ariadna 23700
    constructor(source, state, explicit = false) {
1 efrain 23701
        this.source = source;
23702
        this.state = state;
1441 ariadna 23703
        this.explicit = explicit;
1 efrain 23704
    }
23705
    hasResult() { return false; }
1441 ariadna 23706
    get isPending() { return this.state == 1 /* State.Pending */; }
1 efrain 23707
    update(tr, conf) {
1441 ariadna 23708
        let type = getUpdateType(tr, conf), value = this;
23709
        if ((type & 8 /* UpdateType.Reset */) || (type & 16 /* UpdateType.ResetIfTouching */) && this.touches(tr))
1 efrain 23710
            value = new ActiveSource(value.source, 0 /* State.Inactive */);
1441 ariadna 23711
        if ((type & 4 /* UpdateType.Activate */) && value.state == 0 /* State.Inactive */)
23712
            value = new ActiveSource(this.source, 1 /* State.Pending */);
23713
        value = value.updateFor(tr, type);
1 efrain 23714
        for (let effect of tr.effects) {
23715
            if (effect.is(startCompletionEffect))
1441 ariadna 23716
                value = new ActiveSource(value.source, 1 /* State.Pending */, effect.value);
1 efrain 23717
            else if (effect.is(closeCompletionEffect))
23718
                value = new ActiveSource(value.source, 0 /* State.Inactive */);
23719
            else if (effect.is(setActiveEffect))
23720
                for (let active of effect.value)
23721
                    if (active.source == value.source)
23722
                        value = active;
23723
        }
23724
        return value;
23725
    }
1441 ariadna 23726
    updateFor(tr, type) { return this.map(tr.changes); }
23727
    map(changes) { return this; }
23728
    touches(tr) {
23729
        return tr.changes.touchesRange(cur(tr.state));
1 efrain 23730
    }
23731
}
23732
class ActiveResult extends ActiveSource {
1441 ariadna 23733
    constructor(source, explicit, limit, result, from, to) {
23734
        super(source, 3 /* State.Result */, explicit);
23735
        this.limit = limit;
1 efrain 23736
        this.result = result;
23737
        this.from = from;
23738
        this.to = to;
23739
    }
23740
    hasResult() { return true; }
1441 ariadna 23741
    updateFor(tr, type) {
1 efrain 23742
        var _a;
1441 ariadna 23743
        if (!(type & 3 /* UpdateType.SimpleInteraction */))
23744
            return this.map(tr.changes);
1 efrain 23745
        let result = this.result;
23746
        if (result.map && !tr.changes.empty)
23747
            result = result.map(result, tr.changes);
23748
        let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
23749
        let pos = cur(tr.state);
1441 ariadna 23750
        if (pos > to || !result ||
23751
            (type & 2 /* UpdateType.Backspacing */) && (cur(tr.startState) == this.from || pos < this.limit))
23752
            return new ActiveSource(this.source, type & 4 /* UpdateType.Activate */ ? 1 /* State.Pending */ : 0 /* State.Inactive */);
23753
        let limit = tr.changes.mapPos(this.limit);
1 efrain 23754
        if (checkValid(result.validFor, tr.state, from, to))
1441 ariadna 23755
            return new ActiveResult(this.source, this.explicit, limit, result, from, to);
1 efrain 23756
        if (result.update &&
1441 ariadna 23757
            (result = result.update(result, from, to, new CompletionContext(tr.state, pos, false))))
23758
            return new ActiveResult(this.source, this.explicit, limit, result, result.from, (_a = result.to) !== null && _a !== void 0 ? _a : cur(tr.state));
23759
        return new ActiveSource(this.source, 1 /* State.Pending */, this.explicit);
1 efrain 23760
    }
23761
    map(mapping) {
23762
        if (mapping.empty)
23763
            return this;
23764
        let result = this.result.map ? this.result.map(this.result, mapping) : this.result;
23765
        if (!result)
23766
            return new ActiveSource(this.source, 0 /* State.Inactive */);
1441 ariadna 23767
        return new ActiveResult(this.source, this.explicit, mapping.mapPos(this.limit), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
1 efrain 23768
    }
1441 ariadna 23769
    touches(tr) {
23770
        return tr.changes.touchesRange(this.from, this.to);
23771
    }
1 efrain 23772
}
23773
function checkValid(validFor, state, from, to) {
23774
    if (!validFor)
23775
        return false;
23776
    let text = state.sliceDoc(from, to);
23777
    return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
23778
}
23779
const setActiveEffect = /*@__PURE__*/StateEffect.define({
23780
    map(sources, mapping) { return sources.map(s => s.map(mapping)); }
23781
});
23782
const setSelectedEffect = /*@__PURE__*/StateEffect.define();
23783
const completionState = /*@__PURE__*/StateField.define({
23784
    create() { return CompletionState.start(); },
23785
    update(value, tr) { return value.update(tr); },
23786
    provide: f => [
23787
        showTooltip.from(f, val => val.tooltip),
23788
        EditorView.contentAttributes.from(f, state => state.attrs)
23789
    ]
23790
});
23791
function applyCompletion(view, option) {
23792
    const apply = option.completion.apply || option.completion.label;
23793
    let result = view.state.field(completionState).active.find(a => a.source == option.source);
23794
    if (!(result instanceof ActiveResult))
23795
        return false;
23796
    if (typeof apply == "string")
23797
        view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), { annotations: pickedCompletion.of(option.completion) }));
23798
    else
23799
        apply(view, option.completion, result.from, result.to);
23800
    return true;
23801
}
23802
const createTooltip = /*@__PURE__*/completionTooltip(completionState, applyCompletion);
23803
 
23804
/**
23805
Returns a command that moves the completion selection forward or
23806
backward by the given amount.
23807
*/
23808
function moveCompletionSelection(forward, by = "option") {
23809
    return (view) => {
23810
        let cState = view.state.field(completionState, false);
23811
        if (!cState || !cState.open || cState.open.disabled ||
23812
            Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
23813
            return false;
23814
        let step = 1, tooltip;
23815
        if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
23816
            step = Math.max(2, Math.floor(tooltip.dom.offsetHeight /
23817
                tooltip.dom.querySelector("li").offsetHeight) - 1);
23818
        let { length } = cState.open.options;
23819
        let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
23820
        if (selected < 0)
23821
            selected = by == "page" ? 0 : length - 1;
23822
        else if (selected >= length)
23823
            selected = by == "page" ? length - 1 : 0;
23824
        view.dispatch({ effects: setSelectedEffect.of(selected) });
23825
        return true;
23826
    };
23827
}
23828
/**
23829
Accept the current completion.
23830
*/
23831
const acceptCompletion = (view) => {
23832
    let cState = view.state.field(completionState, false);
23833
    if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled ||
23834
        Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay)
23835
        return false;
23836
    return applyCompletion(view, cState.open.options[cState.open.selected]);
23837
};
23838
/**
23839
Explicitly start autocompletion.
23840
*/
23841
const startCompletion = (view) => {
23842
    let cState = view.state.field(completionState, false);
23843
    if (!cState)
23844
        return false;
23845
    view.dispatch({ effects: startCompletionEffect.of(true) });
23846
    return true;
23847
};
23848
/**
23849
Close the currently active completion.
23850
*/
23851
const closeCompletion = (view) => {
23852
    let cState = view.state.field(completionState, false);
23853
    if (!cState || !cState.active.some(a => a.state != 0 /* State.Inactive */))
23854
        return false;
23855
    view.dispatch({ effects: closeCompletionEffect.of(null) });
23856
    return true;
23857
};
23858
class RunningQuery {
23859
    constructor(active, context) {
23860
        this.active = active;
23861
        this.context = context;
23862
        this.time = Date.now();
23863
        this.updates = [];
23864
        // Note that 'undefined' means 'not done yet', whereas 'null' means
23865
        // 'query returned null'.
23866
        this.done = undefined;
23867
    }
23868
}
23869
const MaxUpdateCount = 50, MinAbortTime = 1000;
23870
const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
23871
    constructor(view) {
23872
        this.view = view;
23873
        this.debounceUpdate = -1;
23874
        this.running = [];
23875
        this.debounceAccept = -1;
23876
        this.pendingStart = false;
23877
        this.composing = 0 /* CompositionState.None */;
23878
        for (let active of view.state.field(completionState).active)
1441 ariadna 23879
            if (active.isPending)
1 efrain 23880
                this.startQuery(active);
23881
    }
23882
    update(update) {
23883
        let cState = update.state.field(completionState);
1441 ariadna 23884
        let conf = update.state.facet(completionConfig);
1 efrain 23885
        if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
23886
            return;
23887
        let doesReset = update.transactions.some(tr => {
1441 ariadna 23888
            let type = getUpdateType(tr, conf);
23889
            return (type & 8 /* UpdateType.Reset */) || (tr.selection || tr.docChanged) && !(type & 3 /* UpdateType.SimpleInteraction */);
1 efrain 23890
        });
23891
        for (let i = 0; i < this.running.length; i++) {
23892
            let query = this.running[i];
23893
            if (doesReset ||
1441 ariadna 23894
                query.context.abortOnDocChange && update.docChanged ||
1 efrain 23895
                query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
23896
                for (let handler of query.context.abortListeners) {
23897
                    try {
23898
                        handler();
23899
                    }
23900
                    catch (e) {
23901
                        logException(this.view.state, e);
23902
                    }
23903
                }
23904
                query.context.abortListeners = null;
23905
                this.running.splice(i--, 1);
23906
            }
23907
            else {
23908
                query.updates.push(...update.transactions);
23909
            }
23910
        }
23911
        if (this.debounceUpdate > -1)
23912
            clearTimeout(this.debounceUpdate);
23913
        if (update.transactions.some(tr => tr.effects.some(e => e.is(startCompletionEffect))))
23914
            this.pendingStart = true;
1441 ariadna 23915
        let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
23916
        this.debounceUpdate = cState.active.some(a => a.isPending && !this.running.some(q => q.active.source == a.source))
1 efrain 23917
            ? setTimeout(() => this.startUpdate(), delay) : -1;
23918
        if (this.composing != 0 /* CompositionState.None */)
23919
            for (let tr of update.transactions) {
1441 ariadna 23920
                if (tr.isUserEvent("input.type"))
1 efrain 23921
                    this.composing = 2 /* CompositionState.Changed */;
23922
                else if (this.composing == 2 /* CompositionState.Changed */ && tr.selection)
23923
                    this.composing = 3 /* CompositionState.ChangedAndMoved */;
23924
            }
23925
    }
23926
    startUpdate() {
23927
        this.debounceUpdate = -1;
23928
        this.pendingStart = false;
23929
        let { state } = this.view, cState = state.field(completionState);
23930
        for (let active of cState.active) {
1441 ariadna 23931
            if (active.isPending && !this.running.some(r => r.active.source == active.source))
1 efrain 23932
                this.startQuery(active);
23933
        }
1441 ariadna 23934
        if (this.running.length && cState.open && cState.open.disabled)
23935
            this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
1 efrain 23936
    }
23937
    startQuery(active) {
23938
        let { state } = this.view, pos = cur(state);
1441 ariadna 23939
        let context = new CompletionContext(state, pos, active.explicit, this.view);
1 efrain 23940
        let pending = new RunningQuery(active, context);
23941
        this.running.push(pending);
23942
        Promise.resolve(active.source(context)).then(result => {
23943
            if (!pending.context.aborted) {
23944
                pending.done = result || null;
23945
                this.scheduleAccept();
23946
            }
23947
        }, err => {
23948
            this.view.dispatch({ effects: closeCompletionEffect.of(null) });
23949
            logException(this.view.state, err);
23950
        });
23951
    }
23952
    scheduleAccept() {
23953
        if (this.running.every(q => q.done !== undefined))
23954
            this.accept();
23955
        else if (this.debounceAccept < 0)
23956
            this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
23957
    }
23958
    // For each finished query in this.running, try to create a result
23959
    // or, if appropriate, restart the query.
23960
    accept() {
23961
        var _a;
23962
        if (this.debounceAccept > -1)
23963
            clearTimeout(this.debounceAccept);
23964
        this.debounceAccept = -1;
23965
        let updated = [];
1441 ariadna 23966
        let conf = this.view.state.facet(completionConfig), cState = this.view.state.field(completionState);
1 efrain 23967
        for (let i = 0; i < this.running.length; i++) {
23968
            let query = this.running[i];
23969
            if (query.done === undefined)
23970
                continue;
23971
            this.running.splice(i--, 1);
23972
            if (query.done) {
1441 ariadna 23973
                let pos = cur(query.updates.length ? query.updates[0].startState : this.view.state);
23974
                let limit = Math.min(pos, query.done.from + (query.active.explicit ? 0 : 1));
23975
                let active = new ActiveResult(query.active.source, query.active.explicit, limit, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : pos);
1 efrain 23976
                // Replay the transactions that happened since the start of
23977
                // the request and see if that preserves the result
23978
                for (let tr of query.updates)
23979
                    active = active.update(tr, conf);
23980
                if (active.hasResult()) {
23981
                    updated.push(active);
23982
                    continue;
23983
                }
23984
            }
1441 ariadna 23985
            let current = cState.active.find(a => a.source == query.active.source);
23986
            if (current && current.isPending) {
1 efrain 23987
                if (query.done == null) {
23988
                    // Explicitly failed. Should clear the pending status if it
23989
                    // hasn't been re-set in the meantime.
23990
                    let active = new ActiveSource(query.active.source, 0 /* State.Inactive */);
23991
                    for (let tr of query.updates)
23992
                        active = active.update(tr, conf);
1441 ariadna 23993
                    if (!active.isPending)
1 efrain 23994
                        updated.push(active);
23995
                }
23996
                else {
23997
                    // Cleared by subsequent transactions. Restart.
23998
                    this.startQuery(current);
23999
                }
24000
            }
24001
        }
1441 ariadna 24002
        if (updated.length || cState.open && cState.open.disabled)
1 efrain 24003
            this.view.dispatch({ effects: setActiveEffect.of(updated) });
24004
    }
24005
}, {
24006
    eventHandlers: {
24007
        blur(event) {
24008
            let state = this.view.state.field(completionState, false);
24009
            if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
24010
                let dialog = state.open && getTooltip(this.view, state.open.tooltip);
24011
                if (!dialog || !dialog.dom.contains(event.relatedTarget))
24012
                    setTimeout(() => this.view.dispatch({ effects: closeCompletionEffect.of(null) }), 10);
24013
            }
24014
        },
24015
        compositionstart() {
24016
            this.composing = 1 /* CompositionState.Started */;
24017
        },
24018
        compositionend() {
24019
            if (this.composing == 3 /* CompositionState.ChangedAndMoved */) {
24020
                // Safari fires compositionend events synchronously, possibly
24021
                // from inside an update, so dispatch asynchronously to avoid reentrancy
24022
                setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
24023
            }
24024
            this.composing = 0 /* CompositionState.None */;
24025
        }
24026
    }
24027
});
24028
const windows = typeof navigator == "object" && /*@__PURE__*//Win/.test(navigator.platform);
24029
const commitCharacters = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.domEventHandlers({
24030
    keydown(event, view) {
24031
        let field = view.state.field(completionState, false);
24032
        if (!field || !field.open || field.open.disabled || field.open.selected < 0 ||
24033
            event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey)
24034
            return false;
24035
        let option = field.open.options[field.open.selected];
24036
        let result = field.active.find(a => a.source == option.source);
24037
        let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
24038
        if (commitChars && commitChars.indexOf(event.key) > -1)
24039
            applyCompletion(view, option);
24040
        return false;
24041
    }
24042
}));
24043
 
24044
const baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({
24045
    ".cm-tooltip.cm-tooltip-autocomplete": {
24046
        "& > ul": {
24047
            fontFamily: "monospace",
24048
            whiteSpace: "nowrap",
24049
            overflow: "hidden auto",
24050
            maxWidth_fallback: "700px",
24051
            maxWidth: "min(700px, 95vw)",
24052
            minWidth: "250px",
24053
            maxHeight: "10em",
24054
            height: "100%",
24055
            listStyle: "none",
24056
            margin: 0,
24057
            padding: 0,
24058
            "& > li, & > completion-section": {
24059
                padding: "1px 3px",
24060
                lineHeight: 1.2
24061
            },
24062
            "& > li": {
24063
                overflowX: "hidden",
24064
                textOverflow: "ellipsis",
24065
                cursor: "pointer"
24066
            },
24067
            "& > completion-section": {
24068
                display: "list-item",
24069
                borderBottom: "1px solid silver",
24070
                paddingLeft: "0.5em",
24071
                opacity: 0.7
24072
            }
24073
        }
24074
    },
24075
    "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
24076
        background: "#17c",
24077
        color: "white",
24078
    },
24079
    "&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
24080
        background: "#777",
24081
    },
24082
    "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
24083
        background: "#347",
24084
        color: "white",
24085
    },
24086
    "&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
24087
        background: "#444",
24088
    },
24089
    ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
24090
        content: '"···"',
24091
        opacity: 0.5,
24092
        display: "block",
24093
        textAlign: "center"
24094
    },
24095
    ".cm-tooltip.cm-completionInfo": {
24096
        position: "absolute",
24097
        padding: "3px 9px",
24098
        width: "max-content",
24099
        maxWidth: `${400 /* Info.Width */}px`,
1441 ariadna 24100
        boxSizing: "border-box",
24101
        whiteSpace: "pre-line"
1 efrain 24102
    },
24103
    ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
24104
    ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
24105
    ".cm-completionInfo.cm-completionInfo-left-narrow": { right: `${30 /* Info.Margin */}px` },
24106
    ".cm-completionInfo.cm-completionInfo-right-narrow": { left: `${30 /* Info.Margin */}px` },
24107
    "&light .cm-snippetField": { backgroundColor: "#00000022" },
24108
    "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
24109
    ".cm-snippetFieldPosition": {
24110
        verticalAlign: "text-top",
24111
        width: 0,
24112
        height: "1.15em",
24113
        display: "inline-block",
24114
        margin: "0 -0.7px -.7em",
24115
        borderLeft: "1.4px dotted #888"
24116
    },
24117
    ".cm-completionMatchedText": {
24118
        textDecoration: "underline"
24119
    },
24120
    ".cm-completionDetail": {
24121
        marginLeft: "0.5em",
24122
        fontStyle: "italic"
24123
    },
24124
    ".cm-completionIcon": {
24125
        fontSize: "90%",
24126
        width: ".8em",
24127
        display: "inline-block",
24128
        textAlign: "center",
24129
        paddingRight: ".6em",
24130
        opacity: "0.6",
24131
        boxSizing: "content-box"
24132
    },
24133
    ".cm-completionIcon-function, .cm-completionIcon-method": {
24134
        "&:after": { content: "'Æ’'" }
24135
    },
24136
    ".cm-completionIcon-class": {
24137
        "&:after": { content: "'○'" }
24138
    },
24139
    ".cm-completionIcon-interface": {
24140
        "&:after": { content: "'◌'" }
24141
    },
24142
    ".cm-completionIcon-variable": {
24143
        "&:after": { content: "'𝑥'" }
24144
    },
24145
    ".cm-completionIcon-constant": {
24146
        "&:after": { content: "'𝐶'" }
24147
    },
24148
    ".cm-completionIcon-type": {
24149
        "&:after": { content: "'𝑡'" }
24150
    },
24151
    ".cm-completionIcon-enum": {
24152
        "&:after": { content: "'∪'" }
24153
    },
24154
    ".cm-completionIcon-property": {
24155
        "&:after": { content: "'â–¡'" }
24156
    },
24157
    ".cm-completionIcon-keyword": {
24158
        "&:after": { content: "'🔑\uFE0E'" } // Disable emoji rendering
24159
    },
24160
    ".cm-completionIcon-namespace": {
24161
        "&:after": { content: "'â–¢'" }
24162
    },
24163
    ".cm-completionIcon-text": {
24164
        "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
24165
    }
24166
});
24167
 
24168
class FieldPos {
24169
    constructor(field, line, from, to) {
24170
        this.field = field;
24171
        this.line = line;
24172
        this.from = from;
24173
        this.to = to;
24174
    }
24175
}
24176
class FieldRange {
24177
    constructor(field, from, to) {
24178
        this.field = field;
24179
        this.from = from;
24180
        this.to = to;
24181
    }
24182
    map(changes) {
24183
        let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
24184
        let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
24185
        return from == null || to == null ? null : new FieldRange(this.field, from, to);
24186
    }
24187
}
24188
class Snippet {
24189
    constructor(lines, fieldPositions) {
24190
        this.lines = lines;
24191
        this.fieldPositions = fieldPositions;
24192
    }
24193
    instantiate(state, pos) {
24194
        let text = [], lineStart = [pos];
24195
        let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
24196
        for (let line of this.lines) {
24197
            if (text.length) {
24198
                let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
24199
                for (let i = 0; i < tabs; i++)
24200
                    indent += state.facet(indentUnit);
24201
                lineStart.push(pos + indent.length - tabs);
24202
                line = indent + line.slice(tabs);
24203
            }
24204
            text.push(line);
24205
            pos += line.length + 1;
24206
        }
24207
        let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
24208
        return { text, ranges };
24209
    }
24210
    static parse(template) {
24211
        let fields = [];
24212
        let lines = [], positions = [], m;
24213
        for (let line of template.split(/\r\n?|\n/)) {
1441 ariadna 24214
            while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(line)) {
24215
                let seq = m[1] ? +m[1] : null, rawName = m[2] || m[3] || "", found = -1;
24216
                let name = rawName.replace(/\\[{}]/g, m => m[1]);
1 efrain 24217
                for (let i = 0; i < fields.length; i++) {
24218
                    if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false)
24219
                        found = i;
24220
                }
24221
                if (found < 0) {
24222
                    let i = 0;
24223
                    while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))
24224
                        i++;
24225
                    fields.splice(i, 0, { seq, name });
24226
                    found = i;
24227
                    for (let pos of positions)
24228
                        if (pos.field >= found)
24229
                            pos.field++;
24230
                }
24231
                positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
1441 ariadna 24232
                line = line.slice(0, m.index) + rawName + line.slice(m.index + m[0].length);
1 efrain 24233
            }
1441 ariadna 24234
            line = line.replace(/\\([{}])/g, (_, brace, index) => {
1 efrain 24235
                for (let pos of positions)
1441 ariadna 24236
                    if (pos.line == lines.length && pos.from > index) {
1 efrain 24237
                        pos.from--;
24238
                        pos.to--;
24239
                    }
1441 ariadna 24240
                return brace;
24241
            });
1 efrain 24242
            lines.push(line);
24243
        }
24244
        return new Snippet(lines, positions);
24245
    }
24246
}
24247
let fieldMarker = /*@__PURE__*/Decoration.widget({ widget: /*@__PURE__*/new class extends WidgetType {
24248
        toDOM() {
24249
            let span = document.createElement("span");
24250
            span.className = "cm-snippetFieldPosition";
24251
            return span;
24252
        }
24253
        ignoreEvent() { return false; }
24254
    } });
24255
let fieldRange = /*@__PURE__*/Decoration.mark({ class: "cm-snippetField" });
24256
class ActiveSnippet {
24257
    constructor(ranges, active) {
24258
        this.ranges = ranges;
24259
        this.active = active;
24260
        this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
24261
    }
24262
    map(changes) {
24263
        let ranges = [];
24264
        for (let r of this.ranges) {
24265
            let mapped = r.map(changes);
24266
            if (!mapped)
24267
                return null;
24268
            ranges.push(mapped);
24269
        }
24270
        return new ActiveSnippet(ranges, this.active);
24271
    }
24272
    selectionInsideField(sel) {
24273
        return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
24274
    }
24275
}
24276
const setActive = /*@__PURE__*/StateEffect.define({
24277
    map(value, changes) { return value && value.map(changes); }
24278
});
24279
const moveToField = /*@__PURE__*/StateEffect.define();
24280
const snippetState = /*@__PURE__*/StateField.define({
24281
    create() { return null; },
24282
    update(value, tr) {
24283
        for (let effect of tr.effects) {
24284
            if (effect.is(setActive))
24285
                return effect.value;
24286
            if (effect.is(moveToField) && value)
24287
                return new ActiveSnippet(value.ranges, effect.value);
24288
        }
24289
        if (value && tr.docChanged)
24290
            value = value.map(tr.changes);
24291
        if (value && tr.selection && !value.selectionInsideField(tr.selection))
24292
            value = null;
24293
        return value;
24294
    },
24295
    provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)
24296
});
24297
function fieldSelection(ranges, field) {
24298
    return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
24299
}
24300
/**
24301
Convert a snippet template to a function that can
24302
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
24303
using syntax like this:
24304
 
24305
    "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
24306
 
24307
Each `${}` placeholder (you may also use `#{}`) indicates a field
24308
that the user can fill in. Its name, if any, will be the default
24309
content for the field.
24310
 
24311
When the snippet is activated by calling the returned function,
24312
the code is inserted at the given position. Newlines in the
24313
template are indented by the indentation of the start line, plus
24314
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
24315
the newline.
24316
 
24317
On activation, (all instances of) the first field are selected.
24318
The user can move between fields with Tab and Shift-Tab as long as
24319
the fields are active. Moving to the last field or moving the
24320
cursor out of the current field deactivates the fields.
24321
 
24322
The order of fields defaults to textual order, but you can add
24323
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
24324
a custom order.
24325
 
24326
To include a literal `{` or `}` in your template, put a backslash
24327
in front of it. This will be removed and the brace will not be
24328
interpreted as indicating a placeholder.
24329
*/
24330
function snippet(template) {
24331
    let snippet = Snippet.parse(template);
24332
    return (editor, completion, from, to) => {
24333
        let { text, ranges } = snippet.instantiate(editor.state, from);
1441 ariadna 24334
        let { main } = editor.state.selection;
1 efrain 24335
        let spec = {
1441 ariadna 24336
            changes: { from, to: to == main.from ? main.to : to, insert: Text.of(text) },
1 efrain 24337
            scrollIntoView: true,
24338
            annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : undefined
24339
        };
24340
        if (ranges.length)
24341
            spec.selection = fieldSelection(ranges, 0);
24342
        if (ranges.some(r => r.field > 0)) {
24343
            let active = new ActiveSnippet(ranges, 0);
24344
            let effects = spec.effects = [setActive.of(active)];
24345
            if (editor.state.field(snippetState, false) === undefined)
24346
                effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme$1]));
24347
        }
24348
        editor.dispatch(editor.state.update(spec));
24349
    };
24350
}
24351
function moveField(dir) {
24352
    return ({ state, dispatch }) => {
24353
        let active = state.field(snippetState, false);
24354
        if (!active || dir < 0 && active.active == 0)
24355
            return false;
24356
        let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
24357
        dispatch(state.update({
24358
            selection: fieldSelection(active.ranges, next),
24359
            effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next)),
24360
            scrollIntoView: true
24361
        }));
24362
        return true;
24363
    };
24364
}
24365
/**
24366
A command that clears the active snippet, if any.
24367
*/
24368
const clearSnippet = ({ state, dispatch }) => {
24369
    let active = state.field(snippetState, false);
24370
    if (!active)
24371
        return false;
24372
    dispatch(state.update({ effects: setActive.of(null) }));
24373
    return true;
24374
};
24375
/**
24376
Move to the next snippet field, if available.
24377
*/
24378
const nextSnippetField = /*@__PURE__*/moveField(1);
24379
/**
24380
Move to the previous snippet field, if available.
24381
*/
24382
const prevSnippetField = /*@__PURE__*/moveField(-1);
24383
const defaultSnippetKeymap = [
24384
    { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
24385
    { key: "Escape", run: clearSnippet }
24386
];
24387
/**
24388
A facet that can be used to configure the key bindings used by
24389
snippets. The default binds Tab to
24390
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
24391
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
24392
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
24393
*/
24394
const snippetKeymap = /*@__PURE__*/Facet.define({
24395
    combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }
24396
});
24397
const addSnippetKeymap = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
24398
/**
24399
Create a completion from a snippet. Returns an object with the
24400
properties from `completion`, plus an `apply` function that
24401
applies the snippet.
24402
*/
24403
function snippetCompletion(template, completion) {
24404
    return Object.assign(Object.assign({}, completion), { apply: snippet(template) });
24405
}
24406
const snippetPointerHandler = /*@__PURE__*/EditorView.domEventHandlers({
24407
    mousedown(event, view) {
24408
        let active = view.state.field(snippetState, false), pos;
24409
        if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)
24410
            return false;
24411
        let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
24412
        if (!match || match.field == active.active)
24413
            return false;
24414
        view.dispatch({
24415
            selection: fieldSelection(active.ranges, match.field),
24416
            effects: setActive.of(active.ranges.some(r => r.field > match.field)
24417
                ? new ActiveSnippet(active.ranges, match.field) : null),
24418
            scrollIntoView: true
24419
        });
24420
        return true;
24421
    }
24422
});
24423
 
24424
const defaults = {
24425
    brackets: ["(", "[", "{", "'", '"'],
24426
    before: ")]}:;>",
24427
    stringPrefixes: []
24428
};
24429
const closeBracketEffect = /*@__PURE__*/StateEffect.define({
24430
    map(value, mapping) {
24431
        let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
24432
        return mapped == null ? undefined : mapped;
24433
    }
24434
});
24435
const closedBracket = /*@__PURE__*/new class extends RangeValue {
24436
};
24437
closedBracket.startSide = 1;
24438
closedBracket.endSide = -1;
24439
const bracketState = /*@__PURE__*/StateField.define({
24440
    create() { return RangeSet.empty; },
24441
    update(value, tr) {
24442
        value = value.map(tr.changes);
24443
        if (tr.selection) {
24444
            let line = tr.state.doc.lineAt(tr.selection.main.head);
24445
            value = value.update({ filter: from => from >= line.from && from <= line.to });
24446
        }
24447
        for (let effect of tr.effects)
24448
            if (effect.is(closeBracketEffect))
24449
                value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
24450
        return value;
24451
    }
24452
});
24453
/**
24454
Extension to enable bracket-closing behavior. When a closeable
24455
bracket is typed, its closing bracket is immediately inserted
24456
after the cursor. When closing a bracket directly in front of a
24457
closing bracket inserted by the extension, the cursor moves over
24458
that bracket.
24459
*/
24460
function closeBrackets() {
24461
    return [inputHandler, bracketState];
24462
}
1441 ariadna 24463
const definedClosing = "()[]{}<>«»»«[]{}";
1 efrain 24464
function closing(ch) {
24465
    for (let i = 0; i < definedClosing.length; i += 2)
24466
        if (definedClosing.charCodeAt(i) == ch)
24467
            return definedClosing.charAt(i + 1);
24468
    return fromCodePoint(ch < 128 ? ch : ch + 1);
24469
}
24470
function config(state, pos) {
24471
    return state.languageDataAt("closeBrackets", pos)[0] || defaults;
24472
}
24473
const android$1 = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
24474
const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => {
24475
    if ((android$1 ? view.composing : view.compositionStarted) || view.state.readOnly)
24476
        return false;
24477
    let sel = view.state.selection.main;
24478
    if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||
24479
        from != sel.from || to != sel.to)
24480
        return false;
24481
    let tr = insertBracket(view.state, insert);
24482
    if (!tr)
24483
        return false;
24484
    view.dispatch(tr);
24485
    return true;
24486
});
24487
/**
24488
Command that implements deleting a pair of matching brackets when
24489
the cursor is between them.
24490
*/
24491
const deleteBracketPair = ({ state, dispatch }) => {
24492
    if (state.readOnly)
24493
        return false;
24494
    let conf = config(state, state.selection.main.head);
24495
    let tokens = conf.brackets || defaults.brackets;
24496
    let dont = null, changes = state.changeByRange(range => {
24497
        if (range.empty) {
24498
            let before = prevChar(state.doc, range.head);
24499
            for (let token of tokens) {
24500
                if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0)))
24501
                    return { changes: { from: range.head - token.length, to: range.head + token.length },
24502
                        range: EditorSelection.cursor(range.head - token.length) };
24503
            }
24504
        }
24505
        return { range: dont = range };
24506
    });
24507
    if (!dont)
24508
        dispatch(state.update(changes, { scrollIntoView: true, userEvent: "delete.backward" }));
24509
    return !dont;
24510
};
24511
/**
24512
Close-brackets related key bindings. Binds Backspace to
24513
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
24514
*/
24515
const closeBracketsKeymap = [
24516
    { key: "Backspace", run: deleteBracketPair }
24517
];
24518
/**
24519
Implements the extension's behavior on text insertion. If the
24520
given string counts as a bracket in the language around the
24521
selection, and replacing the selection with it requires custom
24522
behavior (inserting a closing version or skipping past a
24523
previously-closed bracket), this function returns a transaction
24524
representing that custom behavior. (You only need this if you want
24525
to programmatically insert brackets—the
24526
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
24527
take care of running this for user input.)
24528
*/
24529
function insertBracket(state, bracket) {
24530
    let conf = config(state, state.selection.main.head);
24531
    let tokens = conf.brackets || defaults.brackets;
24532
    for (let tok of tokens) {
24533
        let closed = closing(codePointAt(tok, 0));
24534
        if (bracket == tok)
24535
            return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf)
24536
                : handleOpen(state, tok, closed, conf.before || defaults.before);
24537
        if (bracket == closed && closedBracketAt(state, state.selection.main.from))
24538
            return handleClose(state, tok, closed);
24539
    }
24540
    return null;
24541
}
24542
function closedBracketAt(state, pos) {
24543
    let found = false;
24544
    state.field(bracketState).between(0, state.doc.length, from => {
24545
        if (from == pos)
24546
            found = true;
24547
    });
24548
    return found;
24549
}
24550
function nextChar(doc, pos) {
24551
    let next = doc.sliceString(pos, pos + 2);
24552
    return next.slice(0, codePointSize(codePointAt(next, 0)));
24553
}
24554
function prevChar(doc, pos) {
24555
    let prev = doc.sliceString(pos - 2, pos);
24556
    return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
24557
}
24558
function handleOpen(state, open, close, closeBefore) {
24559
    let dont = null, changes = state.changeByRange(range => {
24560
        if (!range.empty)
24561
            return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
24562
                effects: closeBracketEffect.of(range.to + open.length),
24563
                range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
24564
        let next = nextChar(state.doc, range.head);
24565
        if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
24566
            return { changes: { insert: open + close, from: range.head },
24567
                effects: closeBracketEffect.of(range.head + open.length),
24568
                range: EditorSelection.cursor(range.head + open.length) };
24569
        return { range: dont = range };
24570
    });
24571
    return dont ? null : state.update(changes, {
24572
        scrollIntoView: true,
24573
        userEvent: "input.type"
24574
    });
24575
}
24576
function handleClose(state, _open, close) {
24577
    let dont = null, changes = state.changeByRange(range => {
24578
        if (range.empty && nextChar(state.doc, range.head) == close)
24579
            return { changes: { from: range.head, to: range.head + close.length, insert: close },
24580
                range: EditorSelection.cursor(range.head + close.length) };
24581
        return dont = { range };
24582
    });
24583
    return dont ? null : state.update(changes, {
24584
        scrollIntoView: true,
24585
        userEvent: "input.type"
24586
    });
24587
}
24588
// Handles cases where the open and close token are the same, and
24589
// possibly triple quotes (as in `"""abc"""`-style quoting).
24590
function handleSame(state, token, allowTriple, config) {
24591
    let stringPrefixes = config.stringPrefixes || defaults.stringPrefixes;
24592
    let dont = null, changes = state.changeByRange(range => {
24593
        if (!range.empty)
24594
            return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
24595
                effects: closeBracketEffect.of(range.to + token.length),
24596
                range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
24597
        let pos = range.head, next = nextChar(state.doc, pos), start;
24598
        if (next == token) {
24599
            if (nodeStart(state, pos)) {
24600
                return { changes: { insert: token + token, from: pos },
24601
                    effects: closeBracketEffect.of(pos + token.length),
24602
                    range: EditorSelection.cursor(pos + token.length) };
24603
            }
24604
            else if (closedBracketAt(state, pos)) {
24605
                let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
24606
                let content = isTriple ? token + token + token : token;
24607
                return { changes: { from: pos, to: pos + content.length, insert: content },
24608
                    range: EditorSelection.cursor(pos + content.length) };
24609
            }
24610
        }
24611
        else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
24612
            (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 &&
24613
            nodeStart(state, start)) {
24614
            return { changes: { insert: token + token + token + token, from: pos },
24615
                effects: closeBracketEffect.of(pos + token.length),
24616
                range: EditorSelection.cursor(pos + token.length) };
24617
        }
24618
        else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
24619
            if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes))
24620
                return { changes: { insert: token + token, from: pos },
24621
                    effects: closeBracketEffect.of(pos + token.length),
24622
                    range: EditorSelection.cursor(pos + token.length) };
24623
        }
24624
        return { range: dont = range };
24625
    });
24626
    return dont ? null : state.update(changes, {
24627
        scrollIntoView: true,
24628
        userEvent: "input.type"
24629
    });
24630
}
24631
function nodeStart(state, pos) {
24632
    let tree = syntaxTree(state).resolveInner(pos + 1);
24633
    return tree.parent && tree.from == pos;
24634
}
24635
function probablyInString(state, pos, quoteToken, prefixes) {
24636
    let node = syntaxTree(state).resolveInner(pos, -1);
24637
    let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);
24638
    for (let i = 0; i < 5; i++) {
24639
        let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
24640
        let quotePos = start.indexOf(quoteToken);
24641
        if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
24642
            let first = node.firstChild;
24643
            while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
24644
                if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
24645
                    return false;
24646
                first = first.firstChild;
24647
            }
24648
            return true;
24649
        }
24650
        let parent = node.to == pos && node.parent;
24651
        if (!parent)
24652
            break;
24653
        node = parent;
24654
    }
24655
    return false;
24656
}
24657
function canStartStringAt(state, pos, prefixes) {
24658
    let charCat = state.charCategorizer(pos);
24659
    if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word)
24660
        return pos;
24661
    for (let prefix of prefixes) {
24662
        let start = pos - prefix.length;
24663
        if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word)
24664
            return start;
24665
    }
24666
    return -1;
24667
}
24668
 
24669
/**
24670
Returns an extension that enables autocompletion.
24671
*/
24672
function autocompletion(config = {}) {
24673
    return [
24674
        commitCharacters,
24675
        completionState,
24676
        completionConfig.of(config),
24677
        completionPlugin,
24678
        completionKeymapExt,
24679
        baseTheme$1
24680
    ];
24681
}
24682
/**
24683
Basic keybindings for autocompletion.
24684
 
1441 ariadna 24685
 - Ctrl-Space (and Alt-\` on macOS): [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
1 efrain 24686
 - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
24687
 - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
24688
 - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
24689
 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
24690
 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
24691
 - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
24692
*/
24693
const completionKeymap = [
24694
    { key: "Ctrl-Space", run: startCompletion },
1441 ariadna 24695
    { mac: "Alt-`", run: startCompletion },
1 efrain 24696
    { key: "Escape", run: closeCompletion },
24697
    { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) },
24698
    { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) },
24699
    { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") },
24700
    { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") },
24701
    { key: "Enter", run: acceptCompletion }
24702
];
24703
const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
24704
 
24705
class SelectedDiagnostic {
24706
    constructor(from, to, diagnostic) {
24707
        this.from = from;
24708
        this.to = to;
24709
        this.diagnostic = diagnostic;
24710
    }
24711
}
24712
class LintState {
24713
    constructor(diagnostics, panel, selected) {
24714
        this.diagnostics = diagnostics;
24715
        this.panel = panel;
24716
        this.selected = selected;
24717
    }
24718
    static init(diagnostics, panel, state) {
24719
        // Filter the list of diagnostics for which to create markers
24720
        let markedDiagnostics = diagnostics;
24721
        let diagnosticFilter = state.facet(lintConfig).markerFilter;
24722
        if (diagnosticFilter)
24723
            markedDiagnostics = diagnosticFilter(markedDiagnostics, state);
1441 ariadna 24724
        let sorted = diagnostics.slice().sort((a, b) => a.from - b.from || a.to - b.to);
24725
        let deco = new RangeSetBuilder(), active = [], pos = 0;
24726
        for (let i = 0;;) {
24727
            let next = i == sorted.length ? null : sorted[i];
24728
            if (!next && !active.length)
24729
                break;
24730
            let from, to;
24731
            if (active.length) {
24732
                from = pos;
24733
                to = active.reduce((p, d) => Math.min(p, d.to), next && next.from > from ? next.from : 1e8);
24734
            }
24735
            else {
24736
                from = next.from;
24737
                to = next.to;
24738
                active.push(next);
24739
                i++;
24740
            }
24741
            while (i < sorted.length) {
24742
                let next = sorted[i];
24743
                if (next.from == from && (next.to > next.from || next.to == from)) {
24744
                    active.push(next);
24745
                    i++;
24746
                    to = Math.min(next.to, to);
24747
                }
24748
                else {
24749
                    to = Math.min(next.from, to);
24750
                    break;
24751
                }
24752
            }
24753
            let sev = maxSeverity(active);
24754
            if (active.some(d => d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from))) {
24755
                deco.add(from, from, Decoration.widget({
24756
                    widget: new DiagnosticWidget(sev),
24757
                    diagnostics: active.slice()
24758
                }));
24759
            }
24760
            else {
24761
                let markClass = active.reduce((c, d) => d.markClass ? c + " " + d.markClass : c, "");
24762
                deco.add(from, to, Decoration.mark({
24763
                    class: "cm-lintRange cm-lintRange-" + sev + markClass,
24764
                    diagnostics: active.slice(),
24765
                    inclusiveEnd: active.some(a => a.to > to)
24766
                }));
24767
            }
24768
            pos = to;
24769
            for (let i = 0; i < active.length; i++)
24770
                if (active[i].to <= pos)
24771
                    active.splice(i--, 1);
24772
        }
24773
        let set = deco.finish();
24774
        return new LintState(set, panel, findDiagnostic(set));
1 efrain 24775
    }
24776
}
24777
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
24778
    let found = null;
24779
    diagnostics.between(after, 1e9, (from, to, { spec }) => {
1441 ariadna 24780
        if (diagnostic && spec.diagnostics.indexOf(diagnostic) < 0)
1 efrain 24781
            return;
1441 ariadna 24782
        if (!found)
24783
            found = new SelectedDiagnostic(from, to, diagnostic || spec.diagnostics[0]);
24784
        else if (spec.diagnostics.indexOf(found.diagnostic) < 0)
24785
            return false;
24786
        else
24787
            found = new SelectedDiagnostic(found.from, to, found.diagnostic);
1 efrain 24788
    });
24789
    return found;
24790
}
24791
function hideTooltip(tr, tooltip) {
1441 ariadna 24792
    let from = tooltip.pos, to = tooltip.end || from;
24793
    let result = tr.state.facet(lintConfig).hideOn(tr, from, to);
24794
    if (result != null)
24795
        return result;
1 efrain 24796
    let line = tr.startState.doc.lineAt(tooltip.pos);
1441 ariadna 24797
    return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, Math.max(line.to, to)));
1 efrain 24798
}
24799
function maybeEnableLint(state, effects) {
24800
    return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of(lintExtensions));
24801
}
24802
/**
24803
The state effect that updates the set of active diagnostics. Can
24804
be useful when writing an extension that needs to track these.
24805
*/
24806
const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define();
24807
const togglePanel = /*@__PURE__*/StateEffect.define();
24808
const movePanelSelection = /*@__PURE__*/StateEffect.define();
24809
const lintState = /*@__PURE__*/StateField.define({
24810
    create() {
24811
        return new LintState(Decoration.none, null, null);
24812
    },
24813
    update(value, tr) {
1441 ariadna 24814
        if (tr.docChanged && value.diagnostics.size) {
24815
            let mapped = value.diagnostics.map(tr.changes), selected = null, panel = value.panel;
1 efrain 24816
            if (value.selected) {
24817
                let selPos = tr.changes.mapPos(value.selected.from, 1);
24818
                selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
24819
            }
1441 ariadna 24820
            if (!mapped.size && panel && tr.state.facet(lintConfig).autoPanel)
24821
                panel = null;
24822
            value = new LintState(mapped, panel, selected);
1 efrain 24823
        }
24824
        for (let effect of tr.effects) {
24825
            if (effect.is(setDiagnosticsEffect)) {
1441 ariadna 24826
                let panel = !tr.state.facet(lintConfig).autoPanel ? value.panel : effect.value.length ? LintPanel.open : null;
24827
                value = LintState.init(effect.value, panel, tr.state);
1 efrain 24828
            }
24829
            else if (effect.is(togglePanel)) {
24830
                value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
24831
            }
24832
            else if (effect.is(movePanelSelection)) {
24833
                value = new LintState(value.diagnostics, value.panel, effect.value);
24834
            }
24835
        }
24836
        return value;
24837
    },
24838
    provide: f => [showPanel.from(f, val => val.panel),
24839
        EditorView.decorations.from(f, s => s.diagnostics)]
24840
});
1441 ariadna 24841
const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
1 efrain 24842
function lintTooltip(view, pos, side) {
24843
    let { diagnostics } = view.state.field(lintState);
1441 ariadna 24844
    let found, start = -1, end = -1;
1 efrain 24845
    diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
24846
        if (pos >= from && pos <= to &&
24847
            (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) {
1441 ariadna 24848
            found = spec.diagnostics;
24849
            start = from;
24850
            end = to;
24851
            return false;
1 efrain 24852
        }
24853
    });
24854
    let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
1441 ariadna 24855
    if (found && diagnosticFilter)
1 efrain 24856
        found = diagnosticFilter(found, view.state);
1441 ariadna 24857
    if (!found)
1 efrain 24858
        return null;
24859
    return {
1441 ariadna 24860
        pos: start,
24861
        end: end,
24862
        above: view.state.doc.lineAt(start).to < end,
1 efrain 24863
        create() {
24864
            return { dom: diagnosticsTooltip(view, found) };
24865
        }
24866
    };
24867
}
24868
function diagnosticsTooltip(view, diagnostics) {
24869
    return crelt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false)));
24870
}
24871
/**
24872
Command to open and focus the lint panel.
24873
*/
24874
const openLintPanel = (view) => {
24875
    let field = view.state.field(lintState, false);
24876
    if (!field || !field.panel)
24877
        view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
24878
    let panel = getPanel(view, LintPanel.open);
24879
    if (panel)
24880
        panel.dom.querySelector(".cm-panel-lint ul").focus();
24881
    return true;
24882
};
24883
/**
24884
Command to close the lint panel, when open.
24885
*/
24886
const closeLintPanel = (view) => {
24887
    let field = view.state.field(lintState, false);
24888
    if (!field || !field.panel)
24889
        return false;
24890
    view.dispatch({ effects: togglePanel.of(false) });
24891
    return true;
24892
};
24893
/**
24894
Move the selection to the next diagnostic.
24895
*/
24896
const nextDiagnostic = (view) => {
24897
    let field = view.state.field(lintState, false);
24898
    if (!field)
24899
        return false;
24900
    let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
24901
    if (!next.value) {
24902
        next = field.diagnostics.iter(0);
24903
        if (!next.value || next.from == sel.from && next.to == sel.to)
24904
            return false;
24905
    }
24906
    view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
24907
    return true;
24908
};
24909
/**
24910
A set of default key bindings for the lint functionality.
24911
 
24912
- Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel)
24913
- F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic)
24914
*/
24915
const lintKeymap = [
24916
    { key: "Mod-Shift-m", run: openLintPanel, preventDefault: true },
24917
    { key: "F8", run: nextDiagnostic }
24918
];
24919
const lintConfig = /*@__PURE__*/Facet.define({
24920
    combine(input) {
24921
        return Object.assign({ sources: input.map(i => i.source).filter(x => x != null) }, combineConfig(input.map(i => i.config), {
24922
            delay: 750,
24923
            markerFilter: null,
24924
            tooltipFilter: null,
1441 ariadna 24925
            needsRefresh: null,
24926
            hideOn: () => null,
1 efrain 24927
        }, {
24928
            needsRefresh: (a, b) => !a ? b : !b ? a : u => a(u) || b(u)
24929
        }));
24930
    }
24931
});
24932
function assignKeys(actions) {
24933
    let assigned = [];
24934
    if (actions)
24935
        actions: for (let { name } of actions) {
24936
            for (let i = 0; i < name.length; i++) {
24937
                let ch = name[i];
24938
                if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
24939
                    assigned.push(ch);
24940
                    continue actions;
24941
                }
24942
            }
24943
            assigned.push("");
24944
        }
24945
    return assigned;
24946
}
24947
function renderDiagnostic(view, diagnostic, inPanel) {
24948
    var _a;
24949
    let keys = inPanel ? assignKeys(diagnostic.actions) : [];
1441 ariadna 24950
    return crelt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, crelt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage(view) : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => {
1 efrain 24951
        let fired = false, click = (e) => {
24952
            e.preventDefault();
24953
            if (fired)
24954
                return;
24955
            fired = true;
24956
            let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
24957
            if (found)
24958
                action.apply(view, found.from, found.to);
24959
        };
24960
        let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
24961
        let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex),
24962
            crelt("u", name.slice(keyIndex, keyIndex + 1)),
24963
            name.slice(keyIndex + 1)];
24964
        return crelt("button", {
24965
            type: "button",
24966
            class: "cm-diagnosticAction",
24967
            onclick: click,
24968
            onmousedown: click,
24969
            "aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.`
24970
        }, nameElt);
24971
    }), diagnostic.source && crelt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
24972
}
24973
class DiagnosticWidget extends WidgetType {
1441 ariadna 24974
    constructor(sev) {
1 efrain 24975
        super();
1441 ariadna 24976
        this.sev = sev;
1 efrain 24977
    }
1441 ariadna 24978
    eq(other) { return other.sev == this.sev; }
1 efrain 24979
    toDOM() {
1441 ariadna 24980
        return crelt("span", { class: "cm-lintPoint cm-lintPoint-" + this.sev });
1 efrain 24981
    }
24982
}
24983
class PanelItem {
24984
    constructor(view, diagnostic) {
24985
        this.diagnostic = diagnostic;
24986
        this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16);
24987
        this.dom = renderDiagnostic(view, diagnostic, true);
24988
        this.dom.id = this.id;
24989
        this.dom.setAttribute("role", "option");
24990
    }
24991
}
24992
class LintPanel {
24993
    constructor(view) {
24994
        this.view = view;
24995
        this.items = [];
24996
        let onkeydown = (event) => {
24997
            if (event.keyCode == 27) { // Escape
24998
                closeLintPanel(this.view);
24999
                this.view.focus();
25000
            }
25001
            else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp
25002
                this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
25003
            }
25004
            else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown
25005
                this.moveSelection((this.selectedIndex + 1) % this.items.length);
25006
            }
25007
            else if (event.keyCode == 36) { // Home
25008
                this.moveSelection(0);
25009
            }
25010
            else if (event.keyCode == 35) { // End
25011
                this.moveSelection(this.items.length - 1);
25012
            }
25013
            else if (event.keyCode == 13) { // Enter
25014
                this.view.focus();
25015
            }
25016
            else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z
25017
                let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
25018
                for (let i = 0; i < keys.length; i++)
25019
                    if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
25020
                        let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
25021
                        if (found)
25022
                            diagnostic.actions[i].apply(view, found.from, found.to);
25023
                    }
25024
            }
25025
            else {
25026
                return;
25027
            }
25028
            event.preventDefault();
25029
        };
25030
        let onclick = (event) => {
25031
            for (let i = 0; i < this.items.length; i++) {
25032
                if (this.items[i].dom.contains(event.target))
25033
                    this.moveSelection(i);
25034
            }
25035
        };
25036
        this.list = crelt("ul", {
25037
            tabIndex: 0,
25038
            role: "listbox",
25039
            "aria-label": this.view.state.phrase("Diagnostics"),
25040
            onkeydown,
25041
            onclick
25042
        });
25043
        this.dom = crelt("div", { class: "cm-panel-lint" }, this.list, crelt("button", {
25044
            type: "button",
25045
            name: "close",
25046
            "aria-label": this.view.state.phrase("close"),
25047
            onclick: () => closeLintPanel(this.view)
25048
        }, "×"));
25049
        this.update();
25050
    }
25051
    get selectedIndex() {
25052
        let selected = this.view.state.field(lintState).selected;
25053
        if (!selected)
25054
            return -1;
25055
        for (let i = 0; i < this.items.length; i++)
25056
            if (this.items[i].diagnostic == selected.diagnostic)
25057
                return i;
25058
        return -1;
25059
    }
25060
    update() {
25061
        let { diagnostics, selected } = this.view.state.field(lintState);
25062
        let i = 0, needsSync = false, newSelectedItem = null;
1441 ariadna 25063
        let seen = new Set();
1 efrain 25064
        diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
1441 ariadna 25065
            for (let diagnostic of spec.diagnostics) {
25066
                if (seen.has(diagnostic))
25067
                    continue;
25068
                seen.add(diagnostic);
25069
                let found = -1, item;
25070
                for (let j = i; j < this.items.length; j++)
25071
                    if (this.items[j].diagnostic == diagnostic) {
25072
                        found = j;
25073
                        break;
25074
                    }
25075
                if (found < 0) {
25076
                    item = new PanelItem(this.view, diagnostic);
25077
                    this.items.splice(i, 0, item);
1 efrain 25078
                    needsSync = true;
25079
                }
1441 ariadna 25080
                else {
25081
                    item = this.items[found];
25082
                    if (found > i) {
25083
                        this.items.splice(i, found - i);
25084
                        needsSync = true;
25085
                    }
1 efrain 25086
                }
1441 ariadna 25087
                if (selected && item.diagnostic == selected.diagnostic) {
25088
                    if (!item.dom.hasAttribute("aria-selected")) {
25089
                        item.dom.setAttribute("aria-selected", "true");
25090
                        newSelectedItem = item;
25091
                    }
25092
                }
25093
                else if (item.dom.hasAttribute("aria-selected")) {
25094
                    item.dom.removeAttribute("aria-selected");
25095
                }
25096
                i++;
1 efrain 25097
            }
25098
        });
25099
        while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
25100
            needsSync = true;
25101
            this.items.pop();
25102
        }
25103
        if (this.items.length == 0) {
25104
            this.items.push(new PanelItem(this.view, {
25105
                from: -1, to: -1,
25106
                severity: "info",
25107
                message: this.view.state.phrase("No diagnostics")
25108
            }));
25109
            needsSync = true;
25110
        }
25111
        if (newSelectedItem) {
25112
            this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
25113
            this.view.requestMeasure({
25114
                key: this,
25115
                read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
25116
                write: ({ sel, panel }) => {
25117
                    let scaleY = panel.height / this.list.offsetHeight;
25118
                    if (sel.top < panel.top)
25119
                        this.list.scrollTop -= (panel.top - sel.top) / scaleY;
25120
                    else if (sel.bottom > panel.bottom)
25121
                        this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
25122
                }
25123
            });
25124
        }
25125
        else if (this.selectedIndex < 0) {
25126
            this.list.removeAttribute("aria-activedescendant");
25127
        }
25128
        if (needsSync)
25129
            this.sync();
25130
    }
25131
    sync() {
25132
        let domPos = this.list.firstChild;
25133
        function rm() {
25134
            let prev = domPos;
25135
            domPos = prev.nextSibling;
25136
            prev.remove();
25137
        }
25138
        for (let item of this.items) {
25139
            if (item.dom.parentNode == this.list) {
25140
                while (domPos != item.dom)
25141
                    rm();
25142
                domPos = item.dom.nextSibling;
25143
            }
25144
            else {
25145
                this.list.insertBefore(item.dom, domPos);
25146
            }
25147
        }
25148
        while (domPos)
25149
            rm();
25150
    }
25151
    moveSelection(selectedIndex) {
25152
        if (this.selectedIndex < 0)
25153
            return;
25154
        let field = this.view.state.field(lintState);
25155
        let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
25156
        if (!selection)
25157
            return;
25158
        this.view.dispatch({
25159
            selection: { anchor: selection.from, head: selection.to },
25160
            scrollIntoView: true,
25161
            effects: movePanelSelection.of(selection)
25162
        });
25163
    }
25164
    static open(view) { return new LintPanel(view); }
25165
}
25166
function svg(content, attrs = `viewBox="0 0 40 40"`) {
25167
    return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;
25168
}
25169
function underline(color) {
25170
    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"`);
25171
}
25172
const baseTheme = /*@__PURE__*/EditorView.baseTheme({
25173
    ".cm-diagnostic": {
25174
        padding: "3px 6px 3px 8px",
25175
        marginLeft: "-1px",
25176
        display: "block",
25177
        whiteSpace: "pre-wrap"
25178
    },
25179
    ".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
25180
    ".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
25181
    ".cm-diagnostic-info": { borderLeft: "5px solid #999" },
25182
    ".cm-diagnostic-hint": { borderLeft: "5px solid #66d" },
25183
    ".cm-diagnosticAction": {
25184
        font: "inherit",
25185
        border: "none",
25186
        padding: "2px 4px",
25187
        backgroundColor: "#444",
25188
        color: "white",
25189
        borderRadius: "3px",
25190
        marginLeft: "8px",
25191
        cursor: "pointer"
25192
    },
25193
    ".cm-diagnosticSource": {
25194
        fontSize: "70%",
25195
        opacity: .7
25196
    },
25197
    ".cm-lintRange": {
25198
        backgroundPosition: "left bottom",
25199
        backgroundRepeat: "repeat-x",
25200
        paddingBottom: "0.7px",
25201
    },
25202
    ".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") },
25203
    ".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") },
25204
    ".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") },
25205
    ".cm-lintRange-hint": { backgroundImage: /*@__PURE__*/underline("#66d") },
25206
    ".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
25207
    ".cm-tooltip-lint": {
25208
        padding: 0,
25209
        margin: 0
25210
    },
25211
    ".cm-lintPoint": {
25212
        position: "relative",
25213
        "&:after": {
25214
            content: '""',
25215
            position: "absolute",
25216
            bottom: 0,
25217
            left: "-2px",
25218
            borderLeft: "3px solid transparent",
25219
            borderRight: "3px solid transparent",
25220
            borderBottom: "4px solid #d11"
25221
        }
25222
    },
25223
    ".cm-lintPoint-warning": {
25224
        "&:after": { borderBottomColor: "orange" }
25225
    },
25226
    ".cm-lintPoint-info": {
25227
        "&:after": { borderBottomColor: "#999" }
25228
    },
25229
    ".cm-lintPoint-hint": {
25230
        "&:after": { borderBottomColor: "#66d" }
25231
    },
25232
    ".cm-panel.cm-panel-lint": {
25233
        position: "relative",
25234
        "& ul": {
25235
            maxHeight: "100px",
25236
            overflowY: "auto",
25237
            "& [aria-selected]": {
25238
                backgroundColor: "#ddd",
25239
                "& u": { textDecoration: "underline" }
25240
            },
25241
            "&:focus [aria-selected]": {
25242
                background_fallback: "#bdf",
25243
                backgroundColor: "Highlight",
25244
                color_fallback: "white",
25245
                color: "HighlightText"
25246
            },
25247
            "& u": { textDecoration: "none" },
25248
            padding: 0,
25249
            margin: 0
25250
        },
25251
        "& [name=close]": {
25252
            position: "absolute",
25253
            top: "0",
25254
            right: "2px",
25255
            background: "inherit",
25256
            border: "none",
25257
            font: "inherit",
25258
            padding: 0,
25259
            margin: 0
25260
        }
25261
    }
25262
});
1441 ariadna 25263
function severityWeight(sev) {
25264
    return sev == "error" ? 4 : sev == "warning" ? 3 : sev == "info" ? 2 : 1;
25265
}
25266
function maxSeverity(diagnostics) {
25267
    let sev = "hint", weight = 1;
25268
    for (let d of diagnostics) {
25269
        let w = severityWeight(d.severity);
25270
        if (w > weight) {
25271
            weight = w;
25272
            sev = d.severity;
25273
        }
25274
    }
25275
    return sev;
25276
}
1 efrain 25277
const lintExtensions = [
25278
    lintState,
25279
    /*@__PURE__*/EditorView.decorations.compute([lintState], state => {
25280
        let { selected, panel } = state.field(lintState);
25281
        return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
25282
            activeMark.range(selected.from, selected.to)
25283
        ]);
25284
    }),
25285
    /*@__PURE__*/hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
25286
    baseTheme
25287
];
25288
 
25289
// (The superfluous function calls around the list of extensions work
25290
// around current limitations in tree-shaking software.)
25291
/**
25292
This is an extension value that just pulls together a number of
25293
extensions that you might want in a basic editor. It is meant as a
25294
convenient helper to quickly set up CodeMirror without installing
25295
and importing a lot of separate packages.
25296
 
25297
Specifically, it includes...
25298
 
25299
 - [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
25300
 - [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
25301
 - [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
25302
 - [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
25303
 - [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
25304
 - [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
25305
 - [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
25306
 - [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
25307
 - [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
25308
 - [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
25309
 - [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
25310
 - [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
25311
 - [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
25312
 - [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
25313
 - [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
25314
 - [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
25315
 - [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
25316
 - [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
25317
 - [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
25318
 
25319
(You'll probably want to add some language package to your setup
25320
too.)
25321
 
25322
This extension does not allow customization. The idea is that,
25323
once you decide you want to configure your editor more precisely,
25324
you take this package's source (which is just a bunch of imports
25325
and an array literal), copy it into your own code, and adjust it
25326
as desired.
25327
*/
25328
const basicSetup = /*@__PURE__*/(() => [
25329
    lineNumbers(),
25330
    highlightActiveLineGutter(),
25331
    highlightSpecialChars(),
25332
    history(),
25333
    foldGutter(),
25334
    drawSelection(),
25335
    dropCursor(),
25336
    EditorState.allowMultipleSelections.of(true),
25337
    indentOnInput(),
25338
    syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
25339
    bracketMatching(),
25340
    closeBrackets(),
25341
    autocompletion(),
25342
    rectangularSelection(),
25343
    crosshairCursor(),
25344
    highlightActiveLine(),
25345
    highlightSelectionMatches(),
25346
    keymap.of([
25347
        ...closeBracketsKeymap,
25348
        ...defaultKeymap,
25349
        ...searchKeymap,
25350
        ...historyKeymap,
25351
        ...foldKeymap,
25352
        ...completionKeymap,
25353
        ...lintKeymap
25354
    ])
25355
])();
25356
 
25357
/**
25358
A parse stack. These are used internally by the parser to track
25359
parsing progress. They also provide some properties and methods
25360
that external code such as a tokenizer can use to get information
25361
about the parse state.
25362
*/
25363
class Stack {
25364
    /**
25365
    @internal
25366
    */
25367
    constructor(
25368
    /**
25369
    The parse that this stack is part of @internal
25370
    */
25371
    p,
25372
    /**
25373
    Holds state, input pos, buffer index triplets for all but the
25374
    top state @internal
25375
    */
25376
    stack,
25377
    /**
25378
    The current parse state @internal
25379
    */
25380
    state,
25381
    // The position at which the next reduce should take place. This
25382
    // can be less than `this.pos` when skipped expressions have been
25383
    // added to the stack (which should be moved outside of the next
25384
    // reduction)
25385
    /**
25386
    @internal
25387
    */
25388
    reducePos,
25389
    /**
25390
    The input position up to which this stack has parsed.
25391
    */
25392
    pos,
25393
    /**
25394
    The dynamic score of the stack, including dynamic precedence
25395
    and error-recovery penalties
25396
    @internal
25397
    */
25398
    score,
25399
    // The output buffer. Holds (type, start, end, size) quads
25400
    // representing nodes created by the parser, where `size` is
25401
    // amount of buffer array entries covered by this node.
25402
    /**
25403
    @internal
25404
    */
25405
    buffer,
25406
    // The base offset of the buffer. When stacks are split, the split
25407
    // instance shared the buffer history with its parent up to
25408
    // `bufferBase`, which is the absolute offset (including the
25409
    // offset of previous splits) into the buffer at which this stack
25410
    // starts writing.
25411
    /**
25412
    @internal
25413
    */
25414
    bufferBase,
25415
    /**
25416
    @internal
25417
    */
25418
    curContext,
25419
    /**
25420
    @internal
25421
    */
25422
    lookAhead = 0,
25423
    // A parent stack from which this was split off, if any. This is
25424
    // set up so that it always points to a stack that has some
25425
    // additional buffer content, never to a stack with an equal
25426
    // `bufferBase`.
25427
    /**
25428
    @internal
25429
    */
25430
    parent) {
25431
        this.p = p;
25432
        this.stack = stack;
25433
        this.state = state;
25434
        this.reducePos = reducePos;
25435
        this.pos = pos;
25436
        this.score = score;
25437
        this.buffer = buffer;
25438
        this.bufferBase = bufferBase;
25439
        this.curContext = curContext;
25440
        this.lookAhead = lookAhead;
25441
        this.parent = parent;
25442
    }
25443
    /**
25444
    @internal
25445
    */
25446
    toString() {
25447
        return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
25448
    }
25449
    // Start an empty stack
25450
    /**
25451
    @internal
25452
    */
25453
    static start(p, state, pos = 0) {
25454
        let cx = p.parser.context;
25455
        return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
25456
    }
25457
    /**
25458
    The stack's current [context](#lr.ContextTracker) value, if
25459
    any. Its type will depend on the context tracker's type
25460
    parameter, or it will be `null` if there is no context
25461
    tracker.
25462
    */
25463
    get context() { return this.curContext ? this.curContext.context : null; }
25464
    // Push a state onto the stack, tracking its start position as well
25465
    // as the buffer base at that point.
25466
    /**
25467
    @internal
25468
    */
25469
    pushState(state, start) {
25470
        this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
25471
        this.state = state;
25472
    }
25473
    // Apply a reduce action
25474
    /**
25475
    @internal
25476
    */
25477
    reduce(action) {
25478
        var _a;
25479
        let depth = action >> 19 /* Action.ReduceDepthShift */, type = action & 65535 /* Action.ValueMask */;
25480
        let { parser } = this.p;
1441 ariadna 25481
        let lookaheadRecord = this.reducePos < this.pos - 25 /* Lookahead.Margin */;
25482
        if (lookaheadRecord)
25483
            this.setLookAhead(this.pos);
1 efrain 25484
        let dPrec = parser.dynamicPrecedence(type);
25485
        if (dPrec)
25486
            this.score += dPrec;
25487
        if (depth == 0) {
25488
            this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
25489
            // Zero-depth reductions are a special case—they add stuff to
25490
            // the stack without popping anything off.
25491
            if (type < parser.minRepeatTerm)
1441 ariadna 25492
                this.storeNode(type, this.reducePos, this.reducePos, lookaheadRecord ? 8 : 4, true);
1 efrain 25493
            this.reduceContext(type, this.reducePos);
25494
            return;
25495
        }
25496
        // Find the base index into `this.stack`, content after which will
25497
        // be dropped. Note that with `StayFlag` reductions we need to
25498
        // consume two extra frames (the dummy parent node for the skipped
25499
        // expression and the state that we'll be staying in, which should
25500
        // be moved to `this.state`).
25501
        let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* Action.StayFlag */ ? 6 : 0);
25502
        let start = base ? this.stack[base - 2] : this.p.ranges[0].from, size = this.reducePos - start;
25503
        // This is a kludge to try and detect overly deep left-associative
25504
        // trees, which will not increase the parse stack depth and thus
25505
        // won't be caught by the regular stack-depth limit check.
25506
        if (size >= 2000 /* Recover.MinBigReduction */ && !((_a = this.p.parser.nodeSet.types[type]) === null || _a === void 0 ? void 0 : _a.isAnonymous)) {
25507
            if (start == this.p.lastBigReductionStart) {
25508
                this.p.bigReductionCount++;
25509
                this.p.lastBigReductionSize = size;
25510
            }
25511
            else if (this.p.lastBigReductionSize < size) {
25512
                this.p.bigReductionCount = 1;
25513
                this.p.lastBigReductionStart = start;
25514
                this.p.lastBigReductionSize = size;
25515
            }
25516
        }
25517
        let bufferBase = base ? this.stack[base - 1] : 0, count = this.bufferBase + this.buffer.length - bufferBase;
25518
        // Store normal terms or `R -> R R` repeat reductions
25519
        if (type < parser.minRepeatTerm || (action & 131072 /* Action.RepeatFlag */)) {
25520
            let pos = parser.stateFlag(this.state, 1 /* StateFlag.Skipped */) ? this.pos : this.reducePos;
25521
            this.storeNode(type, start, pos, count + 4, true);
25522
        }
25523
        if (action & 262144 /* Action.StayFlag */) {
25524
            this.state = this.stack[base];
25525
        }
25526
        else {
25527
            let baseStateID = this.stack[base - 3];
25528
            this.state = parser.getGoto(baseStateID, type, true);
25529
        }
25530
        while (this.stack.length > base)
25531
            this.stack.pop();
25532
        this.reduceContext(type, start);
25533
    }
25534
    // Shift a value into the buffer
25535
    /**
25536
    @internal
25537
    */
1441 ariadna 25538
    storeNode(term, start, end, size = 4, mustSink = false) {
1 efrain 25539
        if (term == 0 /* Term.Err */ &&
25540
            (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
25541
            // Try to omit/merge adjacent error nodes
25542
            let cur = this, top = this.buffer.length;
25543
            if (top == 0 && cur.parent) {
25544
                top = cur.bufferBase - cur.parent.bufferBase;
25545
                cur = cur.parent;
25546
            }
25547
            if (top > 0 && cur.buffer[top - 4] == 0 /* Term.Err */ && cur.buffer[top - 1] > -1) {
25548
                if (start == end)
25549
                    return;
25550
                if (cur.buffer[top - 2] >= start) {
25551
                    cur.buffer[top - 2] = end;
25552
                    return;
25553
                }
25554
            }
25555
        }
1441 ariadna 25556
        if (!mustSink || this.pos == end) { // Simple case, just append
1 efrain 25557
            this.buffer.push(term, start, end, size);
25558
        }
25559
        else { // There may be skipped nodes that have to be moved forward
25560
            let index = this.buffer.length;
1441 ariadna 25561
            if (index > 0 && this.buffer[index - 4] != 0 /* Term.Err */) {
25562
                let mustMove = false;
25563
                for (let scan = index; scan > 0 && this.buffer[scan - 2] > end; scan -= 4) {
25564
                    if (this.buffer[scan - 1] >= 0) {
25565
                        mustMove = true;
25566
                        break;
25567
                    }
1 efrain 25568
                }
1441 ariadna 25569
                if (mustMove)
25570
                    while (index > 0 && this.buffer[index - 2] > end) {
25571
                        // Move this record forward
25572
                        this.buffer[index] = this.buffer[index - 4];
25573
                        this.buffer[index + 1] = this.buffer[index - 3];
25574
                        this.buffer[index + 2] = this.buffer[index - 2];
25575
                        this.buffer[index + 3] = this.buffer[index - 1];
25576
                        index -= 4;
25577
                        if (size > 4)
25578
                            size -= 4;
25579
                    }
25580
            }
1 efrain 25581
            this.buffer[index] = term;
25582
            this.buffer[index + 1] = start;
25583
            this.buffer[index + 2] = end;
25584
            this.buffer[index + 3] = size;
25585
        }
25586
    }
25587
    // Apply a shift action
25588
    /**
25589
    @internal
25590
    */
25591
    shift(action, type, start, end) {
25592
        if (action & 131072 /* Action.GotoFlag */) {
25593
            this.pushState(action & 65535 /* Action.ValueMask */, this.pos);
25594
        }
25595
        else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift
25596
            let nextState = action, { parser } = this.p;
25597
            if (end > this.pos || type <= parser.maxNode) {
25598
                this.pos = end;
25599
                if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))
25600
                    this.reducePos = end;
25601
            }
25602
            this.pushState(nextState, start);
25603
            this.shiftContext(type, start);
25604
            if (type <= parser.maxNode)
25605
                this.buffer.push(type, start, end, 4);
25606
        }
25607
        else { // Shift-and-stay, which means this is a skipped token
25608
            this.pos = end;
25609
            this.shiftContext(type, start);
25610
            if (type <= this.p.parser.maxNode)
25611
                this.buffer.push(type, start, end, 4);
25612
        }
25613
    }
25614
    // Apply an action
25615
    /**
25616
    @internal
25617
    */
25618
    apply(action, next, nextStart, nextEnd) {
25619
        if (action & 65536 /* Action.ReduceFlag */)
25620
            this.reduce(action);
25621
        else
25622
            this.shift(action, next, nextStart, nextEnd);
25623
    }
25624
    // Add a prebuilt (reused) node into the buffer.
25625
    /**
25626
    @internal
25627
    */
25628
    useNode(value, next) {
25629
        let index = this.p.reused.length - 1;
25630
        if (index < 0 || this.p.reused[index] != value) {
25631
            this.p.reused.push(value);
25632
            index++;
25633
        }
25634
        let start = this.pos;
25635
        this.reducePos = this.pos = start + value.length;
25636
        this.pushState(next, start);
25637
        this.buffer.push(index, start, this.reducePos, -1 /* size == -1 means this is a reused value */);
25638
        if (this.curContext)
25639
            this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
25640
    }
25641
    // Split the stack. Due to the buffer sharing and the fact
25642
    // that `this.stack` tends to stay quite shallow, this isn't very
25643
    // expensive.
25644
    /**
25645
    @internal
25646
    */
25647
    split() {
25648
        let parent = this;
25649
        let off = parent.buffer.length;
25650
        // Because the top of the buffer (after this.pos) may be mutated
25651
        // to reorder reductions and skipped tokens, and shared buffers
25652
        // should be immutable, this copies any outstanding skipped tokens
25653
        // to the new buffer, and puts the base pointer before them.
25654
        while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
25655
            off -= 4;
25656
        let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
25657
        // Make sure parent points to an actual parent with content, if there is such a parent.
25658
        while (parent && base == parent.bufferBase)
25659
            parent = parent.parent;
25660
        return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, this.curContext, this.lookAhead, parent);
25661
    }
25662
    // Try to recover from an error by 'deleting' (ignoring) one token.
25663
    /**
25664
    @internal
25665
    */
25666
    recoverByDelete(next, nextEnd) {
25667
        let isNode = next <= this.p.parser.maxNode;
25668
        if (isNode)
25669
            this.storeNode(next, this.pos, nextEnd, 4);
25670
        this.storeNode(0 /* Term.Err */, this.pos, nextEnd, isNode ? 8 : 4);
25671
        this.pos = this.reducePos = nextEnd;
25672
        this.score -= 190 /* Recover.Delete */;
25673
    }
25674
    /**
25675
    Check if the given term would be able to be shifted (optionally
25676
    after some reductions) on this stack. This can be useful for
25677
    external tokenizers that want to make sure they only provide a
25678
    given token when it applies.
25679
    */
25680
    canShift(term) {
25681
        for (let sim = new SimulatedStack(this);;) {
25682
            let action = this.p.parser.stateSlot(sim.state, 4 /* ParseState.DefaultReduce */) || this.p.parser.hasAction(sim.state, term);
25683
            if (action == 0)
25684
                return false;
25685
            if ((action & 65536 /* Action.ReduceFlag */) == 0)
25686
                return true;
25687
            sim.reduce(action);
25688
        }
25689
    }
25690
    // Apply up to Recover.MaxNext recovery actions that conceptually
25691
    // inserts some missing token or rule.
25692
    /**
25693
    @internal
25694
    */
25695
    recoverByInsert(next) {
25696
        if (this.stack.length >= 300 /* Recover.MaxInsertStackDepth */)
25697
            return [];
25698
        let nextStates = this.p.parser.nextStates(this.state);
25699
        if (nextStates.length > 4 /* Recover.MaxNext */ << 1 || this.stack.length >= 120 /* Recover.DampenInsertStackDepth */) {
25700
            let best = [];
25701
            for (let i = 0, s; i < nextStates.length; i += 2) {
25702
                if ((s = nextStates[i + 1]) != this.state && this.p.parser.hasAction(s, next))
25703
                    best.push(nextStates[i], s);
25704
            }
25705
            if (this.stack.length < 120 /* Recover.DampenInsertStackDepth */)
25706
                for (let i = 0; best.length < 4 /* Recover.MaxNext */ << 1 && i < nextStates.length; i += 2) {
25707
                    let s = nextStates[i + 1];
25708
                    if (!best.some((v, i) => (i & 1) && v == s))
25709
                        best.push(nextStates[i], s);
25710
                }
25711
            nextStates = best;
25712
        }
25713
        let result = [];
25714
        for (let i = 0; i < nextStates.length && result.length < 4 /* Recover.MaxNext */; i += 2) {
25715
            let s = nextStates[i + 1];
25716
            if (s == this.state)
25717
                continue;
25718
            let stack = this.split();
25719
            stack.pushState(s, this.pos);
25720
            stack.storeNode(0 /* Term.Err */, stack.pos, stack.pos, 4, true);
25721
            stack.shiftContext(nextStates[i], this.pos);
25722
            stack.reducePos = this.pos;
25723
            stack.score -= 200 /* Recover.Insert */;
25724
            result.push(stack);
25725
        }
25726
        return result;
25727
    }
25728
    // Force a reduce, if possible. Return false if that can't
25729
    // be done.
25730
    /**
25731
    @internal
25732
    */
25733
    forceReduce() {
25734
        let { parser } = this.p;
25735
        let reduce = parser.stateSlot(this.state, 5 /* ParseState.ForcedReduce */);
25736
        if ((reduce & 65536 /* Action.ReduceFlag */) == 0)
25737
            return false;
25738
        if (!parser.validAction(this.state, reduce)) {
25739
            let depth = reduce >> 19 /* Action.ReduceDepthShift */, term = reduce & 65535 /* Action.ValueMask */;
25740
            let target = this.stack.length - depth * 3;
25741
            if (target < 0 || parser.getGoto(this.stack[target], term, false) < 0) {
25742
                let backup = this.findForcedReduction();
25743
                if (backup == null)
25744
                    return false;
25745
                reduce = backup;
25746
            }
25747
            this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25748
            this.score -= 100 /* Recover.Reduce */;
25749
        }
25750
        this.reducePos = this.pos;
25751
        this.reduce(reduce);
25752
        return true;
25753
    }
25754
    /**
25755
    Try to scan through the automaton to find some kind of reduction
25756
    that can be applied. Used when the regular ForcedReduce field
25757
    isn't a valid action. @internal
25758
    */
25759
    findForcedReduction() {
25760
        let { parser } = this.p, seen = [];
25761
        let explore = (state, depth) => {
25762
            if (seen.includes(state))
25763
                return;
25764
            seen.push(state);
25765
            return parser.allActions(state, (action) => {
25766
                if (action & (262144 /* Action.StayFlag */ | 131072 /* Action.GotoFlag */)) ;
25767
                else if (action & 65536 /* Action.ReduceFlag */) {
25768
                    let rDepth = (action >> 19 /* Action.ReduceDepthShift */) - depth;
25769
                    if (rDepth > 1) {
25770
                        let term = action & 65535 /* Action.ValueMask */, target = this.stack.length - rDepth * 3;
25771
                        if (target >= 0 && parser.getGoto(this.stack[target], term, false) >= 0)
25772
                            return (rDepth << 19 /* Action.ReduceDepthShift */) | 65536 /* Action.ReduceFlag */ | term;
25773
                    }
25774
                }
25775
                else {
25776
                    let found = explore(action, depth + 1);
25777
                    if (found != null)
25778
                        return found;
25779
                }
25780
            });
25781
        };
25782
        return explore(this.state, 0);
25783
    }
25784
    /**
25785
    @internal
25786
    */
25787
    forceAll() {
25788
        while (!this.p.parser.stateFlag(this.state, 2 /* StateFlag.Accepting */)) {
25789
            if (!this.forceReduce()) {
25790
                this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25791
                break;
25792
            }
25793
        }
25794
        return this;
25795
    }
25796
    /**
25797
    Check whether this state has no further actions (assumed to be a direct descendant of the
25798
    top state, since any other states must be able to continue
25799
    somehow). @internal
25800
    */
25801
    get deadEnd() {
25802
        if (this.stack.length != 3)
25803
            return false;
25804
        let { parser } = this.p;
25805
        return parser.data[parser.stateSlot(this.state, 1 /* ParseState.Actions */)] == 65535 /* Seq.End */ &&
25806
            !parser.stateSlot(this.state, 4 /* ParseState.DefaultReduce */);
25807
    }
25808
    /**
25809
    Restart the stack (put it back in its start state). Only safe
25810
    when this.stack.length == 3 (state is directly below the top
25811
    state). @internal
25812
    */
25813
    restart() {
25814
        this.storeNode(0 /* Term.Err */, this.pos, this.pos, 4, true);
25815
        this.state = this.stack[0];
25816
        this.stack.length = 0;
25817
    }
25818
    /**
25819
    @internal
25820
    */
25821
    sameState(other) {
25822
        if (this.state != other.state || this.stack.length != other.stack.length)
25823
            return false;
25824
        for (let i = 0; i < this.stack.length; i += 3)
25825
            if (this.stack[i] != other.stack[i])
25826
                return false;
25827
        return true;
25828
    }
25829
    /**
25830
    Get the parser used by this stack.
25831
    */
25832
    get parser() { return this.p.parser; }
25833
    /**
25834
    Test whether a given dialect (by numeric ID, as exported from
25835
    the terms file) is enabled.
25836
    */
25837
    dialectEnabled(dialectID) { return this.p.parser.dialect.flags[dialectID]; }
25838
    shiftContext(term, start) {
25839
        if (this.curContext)
25840
            this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
25841
    }
25842
    reduceContext(term, start) {
25843
        if (this.curContext)
25844
            this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
25845
    }
25846
    /**
25847
    @internal
25848
    */
25849
    emitContext() {
25850
        let last = this.buffer.length - 1;
25851
        if (last < 0 || this.buffer[last] != -3)
25852
            this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
25853
    }
25854
    /**
25855
    @internal
25856
    */
25857
    emitLookAhead() {
25858
        let last = this.buffer.length - 1;
25859
        if (last < 0 || this.buffer[last] != -4)
25860
            this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
25861
    }
25862
    updateContext(context) {
25863
        if (context != this.curContext.context) {
25864
            let newCx = new StackContext(this.curContext.tracker, context);
25865
            if (newCx.hash != this.curContext.hash)
25866
                this.emitContext();
25867
            this.curContext = newCx;
25868
        }
25869
    }
25870
    /**
25871
    @internal
25872
    */
25873
    setLookAhead(lookAhead) {
25874
        if (lookAhead > this.lookAhead) {
25875
            this.emitLookAhead();
25876
            this.lookAhead = lookAhead;
25877
        }
25878
    }
25879
    /**
25880
    @internal
25881
    */
25882
    close() {
25883
        if (this.curContext && this.curContext.tracker.strict)
25884
            this.emitContext();
25885
        if (this.lookAhead > 0)
25886
            this.emitLookAhead();
25887
    }
25888
}
25889
class StackContext {
25890
    constructor(tracker, context) {
25891
        this.tracker = tracker;
25892
        this.context = context;
25893
        this.hash = tracker.strict ? tracker.hash(context) : 0;
25894
    }
25895
}
25896
// Used to cheaply run some reductions to scan ahead without mutating
25897
// an entire stack
25898
class SimulatedStack {
25899
    constructor(start) {
25900
        this.start = start;
25901
        this.state = start.state;
25902
        this.stack = start.stack;
25903
        this.base = this.stack.length;
25904
    }
25905
    reduce(action) {
25906
        let term = action & 65535 /* Action.ValueMask */, depth = action >> 19 /* Action.ReduceDepthShift */;
25907
        if (depth == 0) {
25908
            if (this.stack == this.start.stack)
25909
                this.stack = this.stack.slice();
25910
            this.stack.push(this.state, 0, 0);
25911
            this.base += 3;
25912
        }
25913
        else {
25914
            this.base -= (depth - 1) * 3;
25915
        }
25916
        let goto = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
25917
        this.state = goto;
25918
    }
25919
}
25920
// This is given to `Tree.build` to build a buffer, and encapsulates
25921
// the parent-stack-walking necessary to read the nodes.
25922
class StackBufferCursor {
25923
    constructor(stack, pos, index) {
25924
        this.stack = stack;
25925
        this.pos = pos;
25926
        this.index = index;
25927
        this.buffer = stack.buffer;
25928
        if (this.index == 0)
25929
            this.maybeNext();
25930
    }
25931
    static create(stack, pos = stack.bufferBase + stack.buffer.length) {
25932
        return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
25933
    }
25934
    maybeNext() {
25935
        let next = this.stack.parent;
25936
        if (next != null) {
25937
            this.index = this.stack.bufferBase - next.bufferBase;
25938
            this.stack = next;
25939
            this.buffer = next.buffer;
25940
        }
25941
    }
25942
    get id() { return this.buffer[this.index - 4]; }
25943
    get start() { return this.buffer[this.index - 3]; }
25944
    get end() { return this.buffer[this.index - 2]; }
25945
    get size() { return this.buffer[this.index - 1]; }
25946
    next() {
25947
        this.index -= 4;
25948
        this.pos -= 4;
25949
        if (this.index == 0)
25950
            this.maybeNext();
25951
    }
25952
    fork() {
25953
        return new StackBufferCursor(this.stack, this.pos, this.index);
25954
    }
25955
}
25956
 
25957
// See lezer-generator/src/encode.ts for comments about the encoding
25958
// used here
25959
function decodeArray(input, Type = Uint16Array) {
25960
    if (typeof input != "string")
25961
        return input;
25962
    let array = null;
25963
    for (let pos = 0, out = 0; pos < input.length;) {
25964
        let value = 0;
25965
        for (;;) {
25966
            let next = input.charCodeAt(pos++), stop = false;
25967
            if (next == 126 /* Encode.BigValCode */) {
25968
                value = 65535 /* Encode.BigVal */;
25969
                break;
25970
            }
25971
            if (next >= 92 /* Encode.Gap2 */)
25972
                next--;
25973
            if (next >= 34 /* Encode.Gap1 */)
25974
                next--;
25975
            let digit = next - 32 /* Encode.Start */;
25976
            if (digit >= 46 /* Encode.Base */) {
25977
                digit -= 46 /* Encode.Base */;
25978
                stop = true;
25979
            }
25980
            value += digit;
25981
            if (stop)
25982
                break;
25983
            value *= 46 /* Encode.Base */;
25984
        }
25985
        if (array)
25986
            array[out++] = value;
25987
        else
25988
            array = new Type(value);
25989
    }
25990
    return array;
25991
}
25992
 
25993
class CachedToken {
25994
    constructor() {
25995
        this.start = -1;
25996
        this.value = -1;
25997
        this.end = -1;
25998
        this.extended = -1;
25999
        this.lookAhead = 0;
26000
        this.mask = 0;
26001
        this.context = 0;
26002
    }
26003
}
26004
const nullToken = new CachedToken;
26005
/**
26006
[Tokenizers](#lr.ExternalTokenizer) interact with the input
26007
through this interface. It presents the input as a stream of
26008
characters, tracking lookahead and hiding the complexity of
26009
[ranges](#common.Parser.parse^ranges) from tokenizer code.
26010
*/
26011
class InputStream {
26012
    /**
26013
    @internal
26014
    */
26015
    constructor(
26016
    /**
26017
    @internal
26018
    */
26019
    input,
26020
    /**
26021
    @internal
26022
    */
26023
    ranges) {
26024
        this.input = input;
26025
        this.ranges = ranges;
26026
        /**
26027
        @internal
26028
        */
26029
        this.chunk = "";
26030
        /**
26031
        @internal
26032
        */
26033
        this.chunkOff = 0;
26034
        /**
26035
        Backup chunk
26036
        */
26037
        this.chunk2 = "";
26038
        this.chunk2Pos = 0;
26039
        /**
26040
        The character code of the next code unit in the input, or -1
26041
        when the stream is at the end of the input.
26042
        */
26043
        this.next = -1;
26044
        /**
26045
        @internal
26046
        */
26047
        this.token = nullToken;
26048
        this.rangeIndex = 0;
26049
        this.pos = this.chunkPos = ranges[0].from;
26050
        this.range = ranges[0];
26051
        this.end = ranges[ranges.length - 1].to;
26052
        this.readNext();
26053
    }
26054
    /**
26055
    @internal
26056
    */
26057
    resolveOffset(offset, assoc) {
26058
        let range = this.range, index = this.rangeIndex;
26059
        let pos = this.pos + offset;
26060
        while (pos < range.from) {
26061
            if (!index)
26062
                return null;
26063
            let next = this.ranges[--index];
26064
            pos -= range.from - next.to;
26065
            range = next;
26066
        }
26067
        while (assoc < 0 ? pos > range.to : pos >= range.to) {
26068
            if (index == this.ranges.length - 1)
26069
                return null;
26070
            let next = this.ranges[++index];
26071
            pos += next.from - range.to;
26072
            range = next;
26073
        }
26074
        return pos;
26075
    }
26076
    /**
26077
    @internal
26078
    */
26079
    clipPos(pos) {
26080
        if (pos >= this.range.from && pos < this.range.to)
26081
            return pos;
26082
        for (let range of this.ranges)
26083
            if (range.to > pos)
26084
                return Math.max(pos, range.from);
26085
        return this.end;
26086
    }
26087
    /**
26088
    Look at a code unit near the stream position. `.peek(0)` equals
26089
    `.next`, `.peek(-1)` gives you the previous character, and so
26090
    on.
26091
 
26092
    Note that looking around during tokenizing creates dependencies
26093
    on potentially far-away content, which may reduce the
26094
    effectiveness incremental parsing—when looking forward—or even
26095
    cause invalid reparses when looking backward more than 25 code
26096
    units, since the library does not track lookbehind.
26097
    */
26098
    peek(offset) {
26099
        let idx = this.chunkOff + offset, pos, result;
26100
        if (idx >= 0 && idx < this.chunk.length) {
26101
            pos = this.pos + offset;
26102
            result = this.chunk.charCodeAt(idx);
26103
        }
26104
        else {
26105
            let resolved = this.resolveOffset(offset, 1);
26106
            if (resolved == null)
26107
                return -1;
26108
            pos = resolved;
26109
            if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) {
26110
                result = this.chunk2.charCodeAt(pos - this.chunk2Pos);
26111
            }
26112
            else {
26113
                let i = this.rangeIndex, range = this.range;
26114
                while (range.to <= pos)
26115
                    range = this.ranges[++i];
26116
                this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
26117
                if (pos + this.chunk2.length > range.to)
26118
                    this.chunk2 = this.chunk2.slice(0, range.to - pos);
26119
                result = this.chunk2.charCodeAt(0);
26120
            }
26121
        }
26122
        if (pos >= this.token.lookAhead)
26123
            this.token.lookAhead = pos + 1;
26124
        return result;
26125
    }
26126
    /**
26127
    Accept a token. By default, the end of the token is set to the
26128
    current stream position, but you can pass an offset (relative to
26129
    the stream position) to change that.
26130
    */
26131
    acceptToken(token, endOffset = 0) {
26132
        let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
26133
        if (end == null || end < this.token.start)
26134
            throw new RangeError("Token end out of bounds");
26135
        this.token.value = token;
26136
        this.token.end = end;
26137
    }
26138
    /**
26139
    Accept a token ending at a specific given position.
26140
    */
26141
    acceptTokenTo(token, endPos) {
26142
        this.token.value = token;
26143
        this.token.end = endPos;
26144
    }
26145
    getChunk() {
26146
        if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
26147
            let { chunk, chunkPos } = this;
26148
            this.chunk = this.chunk2;
26149
            this.chunkPos = this.chunk2Pos;
26150
            this.chunk2 = chunk;
26151
            this.chunk2Pos = chunkPos;
26152
            this.chunkOff = this.pos - this.chunkPos;
26153
        }
26154
        else {
26155
            this.chunk2 = this.chunk;
26156
            this.chunk2Pos = this.chunkPos;
26157
            let nextChunk = this.input.chunk(this.pos);
26158
            let end = this.pos + nextChunk.length;
26159
            this.chunk = end > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
26160
            this.chunkPos = this.pos;
26161
            this.chunkOff = 0;
26162
        }
26163
    }
26164
    readNext() {
26165
        if (this.chunkOff >= this.chunk.length) {
26166
            this.getChunk();
26167
            if (this.chunkOff == this.chunk.length)
26168
                return this.next = -1;
26169
        }
26170
        return this.next = this.chunk.charCodeAt(this.chunkOff);
26171
    }
26172
    /**
26173
    Move the stream forward N (defaults to 1) code units. Returns
26174
    the new value of [`next`](#lr.InputStream.next).
26175
    */
26176
    advance(n = 1) {
26177
        this.chunkOff += n;
26178
        while (this.pos + n >= this.range.to) {
26179
            if (this.rangeIndex == this.ranges.length - 1)
26180
                return this.setDone();
26181
            n -= this.range.to - this.pos;
26182
            this.range = this.ranges[++this.rangeIndex];
26183
            this.pos = this.range.from;
26184
        }
26185
        this.pos += n;
26186
        if (this.pos >= this.token.lookAhead)
26187
            this.token.lookAhead = this.pos + 1;
26188
        return this.readNext();
26189
    }
26190
    setDone() {
26191
        this.pos = this.chunkPos = this.end;
26192
        this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
26193
        this.chunk = "";
26194
        return this.next = -1;
26195
    }
26196
    /**
26197
    @internal
26198
    */
26199
    reset(pos, token) {
26200
        if (token) {
26201
            this.token = token;
26202
            token.start = pos;
26203
            token.lookAhead = pos + 1;
26204
            token.value = token.extended = -1;
26205
        }
26206
        else {
26207
            this.token = nullToken;
26208
        }
26209
        if (this.pos != pos) {
26210
            this.pos = pos;
26211
            if (pos == this.end) {
26212
                this.setDone();
26213
                return this;
26214
            }
26215
            while (pos < this.range.from)
26216
                this.range = this.ranges[--this.rangeIndex];
26217
            while (pos >= this.range.to)
26218
                this.range = this.ranges[++this.rangeIndex];
26219
            if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) {
26220
                this.chunkOff = pos - this.chunkPos;
26221
            }
26222
            else {
26223
                this.chunk = "";
26224
                this.chunkOff = 0;
26225
            }
26226
            this.readNext();
26227
        }
26228
        return this;
26229
    }
26230
    /**
26231
    @internal
26232
    */
26233
    read(from, to) {
26234
        if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length)
26235
            return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
26236
        if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length)
26237
            return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
26238
        if (from >= this.range.from && to <= this.range.to)
26239
            return this.input.read(from, to);
26240
        let result = "";
26241
        for (let r of this.ranges) {
26242
            if (r.from >= to)
26243
                break;
26244
            if (r.to > from)
26245
                result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
26246
        }
26247
        return result;
26248
    }
26249
}
26250
/**
26251
@internal
26252
*/
26253
class TokenGroup {
26254
    constructor(data, id) {
26255
        this.data = data;
26256
        this.id = id;
26257
    }
26258
    token(input, stack) {
26259
        let { parser } = stack.p;
26260
        readToken(this.data, input, stack, this.id, parser.data, parser.tokenPrecTable);
26261
    }
26262
}
26263
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
26264
/**
26265
@hide
26266
*/
26267
class LocalTokenGroup {
26268
    constructor(data, precTable, elseToken) {
26269
        this.precTable = precTable;
26270
        this.elseToken = elseToken;
26271
        this.data = typeof data == "string" ? decodeArray(data) : data;
26272
    }
26273
    token(input, stack) {
26274
        let start = input.pos, skipped = 0;
26275
        for (;;) {
26276
            let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
26277
            readToken(this.data, input, stack, 0, this.data, this.precTable);
26278
            if (input.token.value > -1)
26279
                break;
26280
            if (this.elseToken == null)
26281
                return;
26282
            if (!atEof)
26283
                skipped++;
26284
            if (nextPos == null)
26285
                break;
26286
            input.reset(nextPos, input.token);
26287
        }
26288
        if (skipped) {
26289
            input.reset(start, input.token);
26290
            input.acceptToken(this.elseToken, skipped);
26291
        }
26292
    }
26293
}
26294
LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
26295
/**
26296
`@external tokens` declarations in the grammar should resolve to
26297
an instance of this class.
26298
*/
26299
class ExternalTokenizer {
26300
    /**
26301
    Create a tokenizer. The first argument is the function that,
26302
    given an input stream, scans for the types of tokens it
26303
    recognizes at the stream's position, and calls
26304
    [`acceptToken`](#lr.InputStream.acceptToken) when it finds
26305
    one.
26306
    */
26307
    constructor(
26308
    /**
26309
    @internal
26310
    */
26311
    token, options = {}) {
26312
        this.token = token;
26313
        this.contextual = !!options.contextual;
26314
        this.fallback = !!options.fallback;
26315
        this.extend = !!options.extend;
26316
    }
26317
}
26318
// Tokenizer data is stored a big uint16 array containing, for each
26319
// state:
26320
//
26321
//  - A group bitmask, indicating what token groups are reachable from
26322
//    this state, so that paths that can only lead to tokens not in
26323
//    any of the current groups can be cut off early.
26324
//
26325
//  - The position of the end of the state's sequence of accepting
26326
//    tokens
26327
//
26328
//  - The number of outgoing edges for the state
26329
//
26330
//  - The accepting tokens, as (token id, group mask) pairs
26331
//
26332
//  - The outgoing edges, as (start character, end character, state
26333
//    index) triples, with end character being exclusive
26334
//
26335
// This function interprets that data, running through a stream as
26336
// long as new states with the a matching group mask can be reached,
26337
// and updating `input.token` when it matches a token.
26338
function readToken(data, input, stack, group, precTable, precOffset) {
26339
    let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
26340
    scan: for (;;) {
26341
        if ((groupMask & data[state]) == 0)
26342
            break;
26343
        let accEnd = data[state + 1];
26344
        // Check whether this state can lead to a token in the current group
26345
        // Accept tokens in this state, possibly overwriting
26346
        // lower-precedence / shorter tokens
26347
        for (let i = state + 3; i < accEnd; i += 2)
26348
            if ((data[i + 1] & groupMask) > 0) {
26349
                let term = data[i];
26350
                if (dialect.allows(term) &&
26351
                    (input.token.value == -1 || input.token.value == term ||
26352
                        overrides(term, input.token.value, precTable, precOffset))) {
26353
                    input.acceptToken(term);
26354
                    break;
26355
                }
26356
            }
26357
        let next = input.next, low = 0, high = data[state + 2];
26358
        // Special case for EOF
26359
        if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535 /* Seq.End */) {
26360
            state = data[accEnd + high * 3 - 1];
26361
            continue scan;
26362
        }
26363
        // Do a binary search on the state's edges
26364
        for (; low < high;) {
26365
            let mid = (low + high) >> 1;
26366
            let index = accEnd + mid + (mid << 1);
26367
            let from = data[index], to = data[index + 1] || 0x10000;
26368
            if (next < from)
26369
                high = mid;
26370
            else if (next >= to)
26371
                low = mid + 1;
26372
            else {
26373
                state = data[index + 2];
26374
                input.advance();
26375
                continue scan;
26376
            }
26377
        }
26378
        break;
26379
    }
26380
}
26381
function findOffset(data, start, term) {
26382
    for (let i = start, next; (next = data[i]) != 65535 /* Seq.End */; i++)
26383
        if (next == term)
26384
            return i - start;
26385
    return -1;
26386
}
26387
function overrides(token, prev, tableData, tableOffset) {
26388
    let iPrev = findOffset(tableData, tableOffset, prev);
26389
    return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
26390
}
26391
 
26392
// Environment variable used to control console output
26393
const verbose = typeof process != "undefined" && process.env && /\bparse\b/.test(process.env.LOG);
26394
let stackIDs = null;
26395
function cutAt(tree, pos, side) {
26396
    let cursor = tree.cursor(IterMode.IncludeAnonymous);
26397
    cursor.moveTo(pos);
26398
    for (;;) {
26399
        if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
26400
            for (;;) {
26401
                if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError)
1441 ariadna 26402
                    return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25 /* Lookahead.Margin */))
26403
                        : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25 /* Lookahead.Margin */));
1 efrain 26404
                if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
26405
                    break;
26406
                if (!cursor.parent())
26407
                    return side < 0 ? 0 : tree.length;
26408
            }
26409
    }
26410
}
26411
class FragmentCursor {
26412
    constructor(fragments, nodeSet) {
26413
        this.fragments = fragments;
26414
        this.nodeSet = nodeSet;
26415
        this.i = 0;
26416
        this.fragment = null;
26417
        this.safeFrom = -1;
26418
        this.safeTo = -1;
26419
        this.trees = [];
26420
        this.start = [];
26421
        this.index = [];
26422
        this.nextFragment();
26423
    }
26424
    nextFragment() {
26425
        let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
26426
        if (fr) {
26427
            this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
26428
            this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
26429
            while (this.trees.length) {
26430
                this.trees.pop();
26431
                this.start.pop();
26432
                this.index.pop();
26433
            }
26434
            this.trees.push(fr.tree);
26435
            this.start.push(-fr.offset);
26436
            this.index.push(0);
26437
            this.nextStart = this.safeFrom;
26438
        }
26439
        else {
26440
            this.nextStart = 1e9;
26441
        }
26442
    }
26443
    // `pos` must be >= any previously given `pos` for this cursor
26444
    nodeAt(pos) {
26445
        if (pos < this.nextStart)
26446
            return null;
26447
        while (this.fragment && this.safeTo <= pos)
26448
            this.nextFragment();
26449
        if (!this.fragment)
26450
            return null;
26451
        for (;;) {
26452
            let last = this.trees.length - 1;
26453
            if (last < 0) { // End of tree
26454
                this.nextFragment();
26455
                return null;
26456
            }
26457
            let top = this.trees[last], index = this.index[last];
26458
            if (index == top.children.length) {
26459
                this.trees.pop();
26460
                this.start.pop();
26461
                this.index.pop();
26462
                continue;
26463
            }
26464
            let next = top.children[index];
26465
            let start = this.start[last] + top.positions[index];
26466
            if (start > pos) {
26467
                this.nextStart = start;
26468
                return null;
26469
            }
26470
            if (next instanceof Tree) {
26471
                if (start == pos) {
26472
                    if (start < this.safeFrom)
26473
                        return null;
26474
                    let end = start + next.length;
26475
                    if (end <= this.safeTo) {
26476
                        let lookAhead = next.prop(NodeProp.lookAhead);
26477
                        if (!lookAhead || end + lookAhead < this.fragment.to)
26478
                            return next;
26479
                    }
26480
                }
26481
                this.index[last]++;
26482
                if (start + next.length >= Math.max(this.safeFrom, pos)) { // Enter this node
26483
                    this.trees.push(next);
26484
                    this.start.push(start);
26485
                    this.index.push(0);
26486
                }
26487
            }
26488
            else {
26489
                this.index[last]++;
26490
                this.nextStart = start + next.length;
26491
            }
26492
        }
26493
    }
26494
}
26495
class TokenCache {
26496
    constructor(parser, stream) {
26497
        this.stream = stream;
26498
        this.tokens = [];
26499
        this.mainToken = null;
26500
        this.actions = [];
26501
        this.tokens = parser.tokenizers.map(_ => new CachedToken);
26502
    }
26503
    getActions(stack) {
26504
        let actionIndex = 0;
26505
        let main = null;
26506
        let { parser } = stack.p, { tokenizers } = parser;
26507
        let mask = parser.stateSlot(stack.state, 3 /* ParseState.TokenizerMask */);
26508
        let context = stack.curContext ? stack.curContext.hash : 0;
26509
        let lookAhead = 0;
26510
        for (let i = 0; i < tokenizers.length; i++) {
26511
            if (((1 << i) & mask) == 0)
26512
                continue;
26513
            let tokenizer = tokenizers[i], token = this.tokens[i];
26514
            if (main && !tokenizer.fallback)
26515
                continue;
26516
            if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
26517
                this.updateCachedToken(token, tokenizer, stack);
26518
                token.mask = mask;
26519
                token.context = context;
26520
            }
1441 ariadna 26521
            if (token.lookAhead > token.end + 25 /* Lookahead.Margin */)
1 efrain 26522
                lookAhead = Math.max(token.lookAhead, lookAhead);
26523
            if (token.value != 0 /* Term.Err */) {
26524
                let startIndex = actionIndex;
26525
                if (token.extended > -1)
26526
                    actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
26527
                actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
26528
                if (!tokenizer.extend) {
26529
                    main = token;
26530
                    if (actionIndex > startIndex)
26531
                        break;
26532
                }
26533
            }
26534
        }
26535
        while (this.actions.length > actionIndex)
26536
            this.actions.pop();
26537
        if (lookAhead)
26538
            stack.setLookAhead(lookAhead);
26539
        if (!main && stack.pos == this.stream.end) {
26540
            main = new CachedToken;
26541
            main.value = stack.p.parser.eofTerm;
26542
            main.start = main.end = stack.pos;
26543
            actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
26544
        }
26545
        this.mainToken = main;
26546
        return this.actions;
26547
    }
26548
    getMainToken(stack) {
26549
        if (this.mainToken)
26550
            return this.mainToken;
26551
        let main = new CachedToken, { pos, p } = stack;
26552
        main.start = pos;
26553
        main.end = Math.min(pos + 1, p.stream.end);
26554
        main.value = pos == p.stream.end ? p.parser.eofTerm : 0 /* Term.Err */;
26555
        return main;
26556
    }
26557
    updateCachedToken(token, tokenizer, stack) {
26558
        let start = this.stream.clipPos(stack.pos);
26559
        tokenizer.token(this.stream.reset(start, token), stack);
26560
        if (token.value > -1) {
26561
            let { parser } = stack.p;
26562
            for (let i = 0; i < parser.specialized.length; i++)
26563
                if (parser.specialized[i] == token.value) {
26564
                    let result = parser.specializers[i](this.stream.read(token.start, token.end), stack);
26565
                    if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
26566
                        if ((result & 1) == 0 /* Specialize.Specialize */)
26567
                            token.value = result >> 1;
26568
                        else
26569
                            token.extended = result >> 1;
26570
                        break;
26571
                    }
26572
                }
26573
        }
26574
        else {
26575
            token.value = 0 /* Term.Err */;
26576
            token.end = this.stream.clipPos(start + 1);
26577
        }
26578
    }
26579
    putAction(action, token, end, index) {
26580
        // Don't add duplicate actions
26581
        for (let i = 0; i < index; i += 3)
26582
            if (this.actions[i] == action)
26583
                return index;
26584
        this.actions[index++] = action;
26585
        this.actions[index++] = token;
26586
        this.actions[index++] = end;
26587
        return index;
26588
    }
26589
    addActions(stack, token, end, index) {
26590
        let { state } = stack, { parser } = stack.p, { data } = parser;
26591
        for (let set = 0; set < 2; set++) {
26592
            for (let i = parser.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */);; i += 3) {
26593
                if (data[i] == 65535 /* Seq.End */) {
26594
                    if (data[i + 1] == 1 /* Seq.Next */) {
26595
                        i = pair(data, i + 2);
26596
                    }
26597
                    else {
26598
                        if (index == 0 && data[i + 1] == 2 /* Seq.Other */)
26599
                            index = this.putAction(pair(data, i + 2), token, end, index);
26600
                        break;
26601
                    }
26602
                }
26603
                if (data[i] == token)
26604
                    index = this.putAction(pair(data, i + 1), token, end, index);
26605
            }
26606
        }
26607
        return index;
26608
    }
26609
}
26610
class Parse {
26611
    constructor(parser, input, fragments, ranges) {
26612
        this.parser = parser;
26613
        this.input = input;
26614
        this.ranges = ranges;
26615
        this.recovering = 0;
26616
        this.nextStackID = 0x2654; // ♔, ♕, ♖, ♗, ♘, ♙, ♠, ♡, ♢, ♣, ♤, ♥, ♦, ♧
26617
        this.minStackPos = 0;
26618
        this.reused = [];
26619
        this.stoppedAt = null;
26620
        this.lastBigReductionStart = -1;
26621
        this.lastBigReductionSize = 0;
26622
        this.bigReductionCount = 0;
26623
        this.stream = new InputStream(input, ranges);
26624
        this.tokens = new TokenCache(parser, this.stream);
26625
        this.topTerm = parser.top[1];
26626
        let { from } = ranges[0];
26627
        this.stacks = [Stack.start(this, parser.top[0], from)];
26628
        this.fragments = fragments.length && this.stream.end - from > parser.bufferLength * 4
26629
            ? new FragmentCursor(fragments, parser.nodeSet) : null;
26630
    }
26631
    get parsedPos() {
26632
        return this.minStackPos;
26633
    }
26634
    // Move the parser forward. This will process all parse stacks at
26635
    // `this.pos` and try to advance them to a further position. If no
26636
    // stack for such a position is found, it'll start error-recovery.
26637
    //
26638
    // When the parse is finished, this will return a syntax tree. When
26639
    // not, it returns `null`.
26640
    advance() {
26641
        let stacks = this.stacks, pos = this.minStackPos;
26642
        // This will hold stacks beyond `pos`.
26643
        let newStacks = this.stacks = [];
26644
        let stopped, stoppedTokens;
26645
        // If a large amount of reductions happened with the same start
26646
        // position, force the stack out of that production in order to
26647
        // avoid creating a tree too deep to recurse through.
26648
        // (This is an ugly kludge, because unfortunately there is no
26649
        // straightforward, cheap way to check for this happening, due to
26650
        // the history of reductions only being available in an
26651
        // expensive-to-access format in the stack buffers.)
26652
        if (this.bigReductionCount > 300 /* Rec.MaxLeftAssociativeReductionCount */ && stacks.length == 1) {
26653
            let [s] = stacks;
26654
            while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart) { }
26655
            this.bigReductionCount = this.lastBigReductionSize = 0;
26656
        }
26657
        // Keep advancing any stacks at `pos` until they either move
26658
        // forward or can't be advanced. Gather stacks that can't be
26659
        // advanced further in `stopped`.
26660
        for (let i = 0; i < stacks.length; i++) {
26661
            let stack = stacks[i];
26662
            for (;;) {
26663
                this.tokens.mainToken = null;
26664
                if (stack.pos > pos) {
26665
                    newStacks.push(stack);
26666
                }
26667
                else if (this.advanceStack(stack, newStacks, stacks)) {
26668
                    continue;
26669
                }
26670
                else {
26671
                    if (!stopped) {
26672
                        stopped = [];
26673
                        stoppedTokens = [];
26674
                    }
26675
                    stopped.push(stack);
26676
                    let tok = this.tokens.getMainToken(stack);
26677
                    stoppedTokens.push(tok.value, tok.end);
26678
                }
26679
                break;
26680
            }
26681
        }
26682
        if (!newStacks.length) {
26683
            let finished = stopped && findFinished(stopped);
26684
            if (finished) {
26685
                if (verbose)
26686
                    console.log("Finish with " + this.stackID(finished));
26687
                return this.stackToTree(finished);
26688
            }
26689
            if (this.parser.strict) {
26690
                if (verbose && stopped)
26691
                    console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
26692
                throw new SyntaxError("No parse at " + pos);
26693
            }
26694
            if (!this.recovering)
26695
                this.recovering = 5 /* Rec.Distance */;
26696
        }
26697
        if (this.recovering && stopped) {
26698
            let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0]
26699
                : this.runRecovery(stopped, stoppedTokens, newStacks);
26700
            if (finished) {
26701
                if (verbose)
26702
                    console.log("Force-finish " + this.stackID(finished));
26703
                return this.stackToTree(finished.forceAll());
26704
            }
26705
        }
26706
        if (this.recovering) {
26707
            let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* Rec.MaxRemainingPerStep */;
26708
            if (newStacks.length > maxRemaining) {
26709
                newStacks.sort((a, b) => b.score - a.score);
26710
                while (newStacks.length > maxRemaining)
26711
                    newStacks.pop();
26712
            }
26713
            if (newStacks.some(s => s.reducePos > pos))
26714
                this.recovering--;
26715
        }
26716
        else if (newStacks.length > 1) {
26717
            // Prune stacks that are in the same state, or that have been
26718
            // running without splitting for a while, to avoid getting stuck
26719
            // with multiple successful stacks running endlessly on.
26720
            outer: for (let i = 0; i < newStacks.length - 1; i++) {
26721
                let stack = newStacks[i];
26722
                for (let j = i + 1; j < newStacks.length; j++) {
26723
                    let other = newStacks[j];
26724
                    if (stack.sameState(other) ||
26725
                        stack.buffer.length > 500 /* Rec.MinBufferLengthPrune */ && other.buffer.length > 500 /* Rec.MinBufferLengthPrune */) {
26726
                        if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
26727
                            newStacks.splice(j--, 1);
26728
                        }
26729
                        else {
26730
                            newStacks.splice(i--, 1);
26731
                            continue outer;
26732
                        }
26733
                    }
26734
                }
26735
            }
26736
            if (newStacks.length > 12 /* Rec.MaxStackCount */)
26737
                newStacks.splice(12 /* Rec.MaxStackCount */, newStacks.length - 12 /* Rec.MaxStackCount */);
26738
        }
26739
        this.minStackPos = newStacks[0].pos;
26740
        for (let i = 1; i < newStacks.length; i++)
26741
            if (newStacks[i].pos < this.minStackPos)
26742
                this.minStackPos = newStacks[i].pos;
26743
        return null;
26744
    }
26745
    stopAt(pos) {
26746
        if (this.stoppedAt != null && this.stoppedAt < pos)
26747
            throw new RangeError("Can't move stoppedAt forward");
26748
        this.stoppedAt = pos;
26749
    }
26750
    // Returns an updated version of the given stack, or null if the
26751
    // stack can't advance normally. When `split` and `stacks` are
26752
    // given, stacks split off by ambiguous operations will be pushed to
26753
    // `split`, or added to `stacks` if they move `pos` forward.
26754
    advanceStack(stack, stacks, split) {
26755
        let start = stack.pos, { parser } = this;
26756
        let base = verbose ? this.stackID(stack) + " -> " : "";
26757
        if (this.stoppedAt != null && start > this.stoppedAt)
26758
            return stack.forceReduce() ? stack : null;
26759
        if (this.fragments) {
26760
            let strictCx = stack.curContext && stack.curContext.tracker.strict, cxHash = strictCx ? stack.curContext.hash : 0;
26761
            for (let cached = this.fragments.nodeAt(start); cached;) {
26762
                let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
26763
                if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
26764
                    stack.useNode(cached, match);
26765
                    if (verbose)
26766
                        console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
26767
                    return true;
26768
                }
26769
                if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
26770
                    break;
26771
                let inner = cached.children[0];
26772
                if (inner instanceof Tree && cached.positions[0] == 0)
26773
                    cached = inner;
26774
                else
26775
                    break;
26776
            }
26777
        }
26778
        let defaultReduce = parser.stateSlot(stack.state, 4 /* ParseState.DefaultReduce */);
26779
        if (defaultReduce > 0) {
26780
            stack.reduce(defaultReduce);
26781
            if (verbose)
26782
                console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* Action.ValueMask */)})`);
26783
            return true;
26784
        }
26785
        if (stack.stack.length >= 8400 /* Rec.CutDepth */) {
26786
            while (stack.stack.length > 6000 /* Rec.CutTo */ && stack.forceReduce()) { }
26787
        }
26788
        let actions = this.tokens.getActions(stack);
26789
        for (let i = 0; i < actions.length;) {
26790
            let action = actions[i++], term = actions[i++], end = actions[i++];
26791
            let last = i == actions.length || !split;
26792
            let localStack = last ? stack : stack.split();
26793
            let main = this.tokens.mainToken;
26794
            localStack.apply(action, term, main ? main.start : localStack.pos, end);
26795
            if (verbose)
26796
                console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* Action.ReduceFlag */) == 0 ? "shift"
26797
                    : `reduce of ${parser.getName(action & 65535 /* Action.ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
26798
            if (last)
26799
                return true;
26800
            else if (localStack.pos > start)
26801
                stacks.push(localStack);
26802
            else
26803
                split.push(localStack);
26804
        }
26805
        return false;
26806
    }
26807
    // Advance a given stack forward as far as it will go. Returns the
26808
    // (possibly updated) stack if it got stuck, or null if it moved
26809
    // forward and was given to `pushStackDedup`.
26810
    advanceFully(stack, newStacks) {
26811
        let pos = stack.pos;
26812
        for (;;) {
26813
            if (!this.advanceStack(stack, null, null))
26814
                return false;
26815
            if (stack.pos > pos) {
26816
                pushStackDedup(stack, newStacks);
26817
                return true;
26818
            }
26819
        }
26820
    }
26821
    runRecovery(stacks, tokens, newStacks) {
26822
        let finished = null, restarted = false;
26823
        for (let i = 0; i < stacks.length; i++) {
26824
            let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
26825
            let base = verbose ? this.stackID(stack) + " -> " : "";
26826
            if (stack.deadEnd) {
26827
                if (restarted)
26828
                    continue;
26829
                restarted = true;
26830
                stack.restart();
26831
                if (verbose)
26832
                    console.log(base + this.stackID(stack) + " (restarted)");
26833
                let done = this.advanceFully(stack, newStacks);
26834
                if (done)
26835
                    continue;
26836
            }
26837
            let force = stack.split(), forceBase = base;
26838
            for (let j = 0; force.forceReduce() && j < 10 /* Rec.ForceReduceLimit */; j++) {
26839
                if (verbose)
26840
                    console.log(forceBase + this.stackID(force) + " (via force-reduce)");
26841
                let done = this.advanceFully(force, newStacks);
26842
                if (done)
26843
                    break;
26844
                if (verbose)
26845
                    forceBase = this.stackID(force) + " -> ";
26846
            }
26847
            for (let insert of stack.recoverByInsert(token)) {
26848
                if (verbose)
26849
                    console.log(base + this.stackID(insert) + " (via recover-insert)");
26850
                this.advanceFully(insert, newStacks);
26851
            }
26852
            if (this.stream.end > stack.pos) {
26853
                if (tokenEnd == stack.pos) {
26854
                    tokenEnd++;
26855
                    token = 0 /* Term.Err */;
26856
                }
26857
                stack.recoverByDelete(token, tokenEnd);
26858
                if (verbose)
26859
                    console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
26860
                pushStackDedup(stack, newStacks);
26861
            }
26862
            else if (!finished || finished.score < stack.score) {
26863
                finished = stack;
26864
            }
26865
        }
26866
        return finished;
26867
    }
26868
    // Convert the stack's buffer to a syntax tree.
26869
    stackToTree(stack) {
26870
        stack.close();
26871
        return Tree.build({ buffer: StackBufferCursor.create(stack),
26872
            nodeSet: this.parser.nodeSet,
26873
            topID: this.topTerm,
26874
            maxBufferLength: this.parser.bufferLength,
26875
            reused: this.reused,
26876
            start: this.ranges[0].from,
26877
            length: stack.pos - this.ranges[0].from,
26878
            minRepeatType: this.parser.minRepeatTerm });
26879
    }
26880
    stackID(stack) {
26881
        let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
26882
        if (!id)
26883
            stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
26884
        return id + stack;
26885
    }
26886
}
26887
function pushStackDedup(stack, newStacks) {
26888
    for (let i = 0; i < newStacks.length; i++) {
26889
        let other = newStacks[i];
26890
        if (other.pos == stack.pos && other.sameState(stack)) {
26891
            if (newStacks[i].score < stack.score)
26892
                newStacks[i] = stack;
26893
            return;
26894
        }
26895
    }
26896
    newStacks.push(stack);
26897
}
26898
class Dialect {
26899
    constructor(source, flags, disabled) {
26900
        this.source = source;
26901
        this.flags = flags;
26902
        this.disabled = disabled;
26903
    }
26904
    allows(term) { return !this.disabled || this.disabled[term] == 0; }
26905
}
26906
const id = x => x;
26907
/**
26908
Context trackers are used to track stateful context (such as
26909
indentation in the Python grammar, or parent elements in the XML
26910
grammar) needed by external tokenizers. You declare them in a
26911
grammar file as `@context exportName from "module"`.
26912
 
26913
Context values should be immutable, and can be updated (replaced)
26914
on shift or reduce actions.
26915
 
26916
The export used in a `@context` declaration should be of this
26917
type.
26918
*/
26919
class ContextTracker {
26920
    /**
26921
    Define a context tracker.
26922
    */
26923
    constructor(spec) {
26924
        this.start = spec.start;
26925
        this.shift = spec.shift || id;
26926
        this.reduce = spec.reduce || id;
26927
        this.reuse = spec.reuse || id;
26928
        this.hash = spec.hash || (() => 0);
26929
        this.strict = spec.strict !== false;
26930
    }
26931
}
26932
/**
26933
Holds the parse tables for a given grammar, as generated by
26934
`lezer-generator`, and provides [methods](#common.Parser) to parse
26935
content with.
26936
*/
26937
class LRParser extends Parser {
26938
    /**
26939
    @internal
26940
    */
26941
    constructor(spec) {
26942
        super();
26943
        /**
26944
        @internal
26945
        */
26946
        this.wrappers = [];
26947
        if (spec.version != 14 /* File.Version */)
26948
            throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${14 /* File.Version */})`);
26949
        let nodeNames = spec.nodeNames.split(" ");
26950
        this.minRepeatTerm = nodeNames.length;
26951
        for (let i = 0; i < spec.repeatNodeCount; i++)
26952
            nodeNames.push("");
26953
        let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
26954
        let nodeProps = [];
26955
        for (let i = 0; i < nodeNames.length; i++)
26956
            nodeProps.push([]);
26957
        function setProp(nodeID, prop, value) {
26958
            nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
26959
        }
26960
        if (spec.nodeProps)
26961
            for (let propSpec of spec.nodeProps) {
26962
                let prop = propSpec[0];
26963
                if (typeof prop == "string")
26964
                    prop = NodeProp[prop];
26965
                for (let i = 1; i < propSpec.length;) {
26966
                    let next = propSpec[i++];
26967
                    if (next >= 0) {
26968
                        setProp(next, prop, propSpec[i++]);
26969
                    }
26970
                    else {
26971
                        let value = propSpec[i + -next];
26972
                        for (let j = -next; j > 0; j--)
26973
                            setProp(propSpec[i++], prop, value);
26974
                        i++;
26975
                    }
26976
                }
26977
            }
26978
        this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
26979
            name: i >= this.minRepeatTerm ? undefined : name,
26980
            id: i,
26981
            props: nodeProps[i],
26982
            top: topTerms.indexOf(i) > -1,
26983
            error: i == 0,
26984
            skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
26985
        })));
26986
        if (spec.propSources)
26987
            this.nodeSet = this.nodeSet.extend(...spec.propSources);
26988
        this.strict = false;
26989
        this.bufferLength = DefaultBufferLength;
26990
        let tokenArray = decodeArray(spec.tokenData);
26991
        this.context = spec.context;
26992
        this.specializerSpecs = spec.specialized || [];
26993
        this.specialized = new Uint16Array(this.specializerSpecs.length);
26994
        for (let i = 0; i < this.specializerSpecs.length; i++)
26995
            this.specialized[i] = this.specializerSpecs[i].term;
26996
        this.specializers = this.specializerSpecs.map(getSpecializer);
26997
        this.states = decodeArray(spec.states, Uint32Array);
26998
        this.data = decodeArray(spec.stateData);
26999
        this.goto = decodeArray(spec.goto);
27000
        this.maxTerm = spec.maxTerm;
27001
        this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
27002
        this.topRules = spec.topRules;
27003
        this.dialects = spec.dialects || {};
27004
        this.dynamicPrecedences = spec.dynamicPrecedences || null;
27005
        this.tokenPrecTable = spec.tokenPrec;
27006
        this.termNames = spec.termNames || null;
27007
        this.maxNode = this.nodeSet.types.length - 1;
27008
        this.dialect = this.parseDialect();
27009
        this.top = this.topRules[Object.keys(this.topRules)[0]];
27010
    }
27011
    createParse(input, fragments, ranges) {
27012
        let parse = new Parse(this, input, fragments, ranges);
27013
        for (let w of this.wrappers)
27014
            parse = w(parse, input, fragments, ranges);
27015
        return parse;
27016
    }
27017
    /**
27018
    Get a goto table entry @internal
27019
    */
27020
    getGoto(state, term, loose = false) {
27021
        let table = this.goto;
27022
        if (term >= table[0])
27023
            return -1;
27024
        for (let pos = table[term + 1];;) {
27025
            let groupTag = table[pos++], last = groupTag & 1;
27026
            let target = table[pos++];
27027
            if (last && loose)
27028
                return target;
27029
            for (let end = pos + (groupTag >> 1); pos < end; pos++)
27030
                if (table[pos] == state)
27031
                    return target;
27032
            if (last)
27033
                return -1;
27034
        }
27035
    }
27036
    /**
27037
    Check if this state has an action for a given terminal @internal
27038
    */
27039
    hasAction(state, terminal) {
27040
        let data = this.data;
27041
        for (let set = 0; set < 2; set++) {
27042
            for (let i = this.stateSlot(state, set ? 2 /* ParseState.Skip */ : 1 /* ParseState.Actions */), next;; i += 3) {
27043
                if ((next = data[i]) == 65535 /* Seq.End */) {
27044
                    if (data[i + 1] == 1 /* Seq.Next */)
27045
                        next = data[i = pair(data, i + 2)];
27046
                    else if (data[i + 1] == 2 /* Seq.Other */)
27047
                        return pair(data, i + 2);
27048
                    else
27049
                        break;
27050
                }
27051
                if (next == terminal || next == 0 /* Term.Err */)
27052
                    return pair(data, i + 1);
27053
            }
27054
        }
27055
        return 0;
27056
    }
27057
    /**
27058
    @internal
27059
    */
27060
    stateSlot(state, slot) {
27061
        return this.states[(state * 6 /* ParseState.Size */) + slot];
27062
    }
27063
    /**
27064
    @internal
27065
    */
27066
    stateFlag(state, flag) {
27067
        return (this.stateSlot(state, 0 /* ParseState.Flags */) & flag) > 0;
27068
    }
27069
    /**
27070
    @internal
27071
    */
27072
    validAction(state, action) {
27073
        return !!this.allActions(state, a => a == action ? true : null);
27074
    }
27075
    /**
27076
    @internal
27077
    */
27078
    allActions(state, action) {
27079
        let deflt = this.stateSlot(state, 4 /* ParseState.DefaultReduce */);
27080
        let result = deflt ? action(deflt) : undefined;
27081
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */); result == null; i += 3) {
27082
            if (this.data[i] == 65535 /* Seq.End */) {
27083
                if (this.data[i + 1] == 1 /* Seq.Next */)
27084
                    i = pair(this.data, i + 2);
27085
                else
27086
                    break;
27087
            }
27088
            result = action(pair(this.data, i + 1));
27089
        }
27090
        return result;
27091
    }
27092
    /**
27093
    Get the states that can follow this one through shift actions or
27094
    goto jumps. @internal
27095
    */
27096
    nextStates(state) {
27097
        let result = [];
27098
        for (let i = this.stateSlot(state, 1 /* ParseState.Actions */);; i += 3) {
27099
            if (this.data[i] == 65535 /* Seq.End */) {
27100
                if (this.data[i + 1] == 1 /* Seq.Next */)
27101
                    i = pair(this.data, i + 2);
27102
                else
27103
                    break;
27104
            }
27105
            if ((this.data[i + 2] & (65536 /* Action.ReduceFlag */ >> 16)) == 0) {
27106
                let value = this.data[i + 1];
27107
                if (!result.some((v, i) => (i & 1) && v == value))
27108
                    result.push(this.data[i], value);
27109
            }
27110
        }
27111
        return result;
27112
    }
27113
    /**
27114
    Configure the parser. Returns a new parser instance that has the
27115
    given settings modified. Settings not provided in `config` are
27116
    kept from the original parser.
27117
    */
27118
    configure(config) {
27119
        // Hideous reflection-based kludge to make it easy to create a
27120
        // slightly modified copy of a parser.
27121
        let copy = Object.assign(Object.create(LRParser.prototype), this);
27122
        if (config.props)
27123
            copy.nodeSet = this.nodeSet.extend(...config.props);
27124
        if (config.top) {
27125
            let info = this.topRules[config.top];
27126
            if (!info)
27127
                throw new RangeError(`Invalid top rule name ${config.top}`);
27128
            copy.top = info;
27129
        }
27130
        if (config.tokenizers)
27131
            copy.tokenizers = this.tokenizers.map(t => {
27132
                let found = config.tokenizers.find(r => r.from == t);
27133
                return found ? found.to : t;
27134
            });
27135
        if (config.specializers) {
27136
            copy.specializers = this.specializers.slice();
27137
            copy.specializerSpecs = this.specializerSpecs.map((s, i) => {
27138
                let found = config.specializers.find(r => r.from == s.external);
27139
                if (!found)
27140
                    return s;
27141
                let spec = Object.assign(Object.assign({}, s), { external: found.to });
27142
                copy.specializers[i] = getSpecializer(spec);
27143
                return spec;
27144
            });
27145
        }
27146
        if (config.contextTracker)
27147
            copy.context = config.contextTracker;
27148
        if (config.dialect)
27149
            copy.dialect = this.parseDialect(config.dialect);
27150
        if (config.strict != null)
27151
            copy.strict = config.strict;
27152
        if (config.wrap)
27153
            copy.wrappers = copy.wrappers.concat(config.wrap);
27154
        if (config.bufferLength != null)
27155
            copy.bufferLength = config.bufferLength;
27156
        return copy;
27157
    }
27158
    /**
27159
    Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
27160
    are registered for this parser.
27161
    */
27162
    hasWrappers() {
27163
        return this.wrappers.length > 0;
27164
    }
27165
    /**
27166
    Returns the name associated with a given term. This will only
27167
    work for all terms when the parser was generated with the
27168
    `--names` option. By default, only the names of tagged terms are
27169
    stored.
27170
    */
27171
    getName(term) {
27172
        return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
27173
    }
27174
    /**
27175
    The eof term id is always allocated directly after the node
27176
    types. @internal
27177
    */
27178
    get eofTerm() { return this.maxNode + 1; }
27179
    /**
27180
    The type of top node produced by the parser.
27181
    */
27182
    get topNode() { return this.nodeSet.types[this.top[1]]; }
27183
    /**
27184
    @internal
27185
    */
27186
    dynamicPrecedence(term) {
27187
        let prec = this.dynamicPrecedences;
27188
        return prec == null ? 0 : prec[term] || 0;
27189
    }
27190
    /**
27191
    @internal
27192
    */
27193
    parseDialect(dialect) {
27194
        let values = Object.keys(this.dialects), flags = values.map(() => false);
27195
        if (dialect)
27196
            for (let part of dialect.split(" ")) {
27197
                let id = values.indexOf(part);
27198
                if (id >= 0)
27199
                    flags[id] = true;
27200
            }
27201
        let disabled = null;
27202
        for (let i = 0; i < values.length; i++)
27203
            if (!flags[i]) {
27204
                for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* Seq.End */;)
27205
                    (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
27206
            }
27207
        return new Dialect(dialect, flags, disabled);
27208
    }
27209
    /**
27210
    Used by the output of the parser generator. Not available to
27211
    user code. @hide
27212
    */
27213
    static deserialize(spec) {
27214
        return new LRParser(spec);
27215
    }
27216
}
27217
function pair(data, off) { return data[off] | (data[off + 1] << 16); }
27218
function findFinished(stacks) {
27219
    let best = null;
27220
    for (let stack of stacks) {
27221
        let stopped = stack.p.stoppedAt;
27222
        if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) &&
27223
            stack.p.parser.stateFlag(stack.state, 2 /* StateFlag.Accepting */) &&
27224
            (!best || best.score < stack.score))
27225
            best = stack;
27226
    }
27227
    return best;
27228
}
27229
function getSpecializer(spec) {
27230
    if (spec.external) {
27231
        let mask = spec.extend ? 1 /* Specialize.Extend */ : 0 /* Specialize.Specialize */;
27232
        return (value, stack) => (spec.external(value, stack) << 1) | mask;
27233
    }
27234
    return spec.get;
27235
}
27236
 
27237
// This file was generated by lezer-generator. You probably shouldn't edit it.
27238
const scriptText = 54,
27239
  StartCloseScriptTag = 1,
27240
  styleText = 55,
27241
  StartCloseStyleTag = 2,
27242
  textareaText = 56,
27243
  StartCloseTextareaTag = 3,
27244
  EndTag = 4,
27245
  SelfClosingEndTag = 5,
27246
  StartTag$1 = 6,
27247
  StartScriptTag = 7,
27248
  StartStyleTag = 8,
27249
  StartTextareaTag = 9,
27250
  StartSelfClosingTag = 10,
27251
  StartCloseTag$1 = 11,
27252
  NoMatchStartCloseTag = 12,
27253
  MismatchedStartCloseTag = 13,
27254
  missingCloseTag = 57,
27255
  IncompleteCloseTag = 14,
27256
  commentContent$1$1 = 58,
27257
  Element$2 = 20,
27258
  TagName = 22,
27259
  Attribute = 23,
27260
  AttributeName = 24,
27261
  AttributeValue = 26,
27262
  UnquotedAttributeValue = 27,
27263
  ScriptText = 28,
27264
  StyleText = 31,
27265
  TextareaText = 34,
27266
  OpenTag$1 = 36,
27267
  CloseTag = 37,
27268
  Dialect_noMatch = 0,
27269
  Dialect_selfClosing = 1;
27270
 
27271
/* Hand-written tokenizers for HTML. */
27272
 
27273
const selfClosers$1 = {
27274
  area: true, base: true, br: true, col: true, command: true,
27275
  embed: true, frame: true, hr: true, img: true, input: true,
27276
  keygen: true, link: true, meta: true, param: true, source: true,
27277
  track: true, wbr: true, menuitem: true
27278
};
27279
 
27280
const implicitlyClosed = {
27281
  dd: true, li: true, optgroup: true, option: true, p: true,
27282
  rp: true, rt: true, tbody: true, td: true, tfoot: true,
27283
  th: true, tr: true
27284
};
27285
 
27286
const closeOnOpen = {
27287
  dd: {dd: true, dt: true},
27288
  dt: {dd: true, dt: true},
27289
  li: {li: true},
27290
  option: {option: true, optgroup: true},
27291
  optgroup: {optgroup: true},
27292
  p: {
27293
    address: true, article: true, aside: true, blockquote: true, dir: true,
27294
    div: true, dl: true, fieldset: true, footer: true, form: true,
27295
    h1: true, h2: true, h3: true, h4: true, h5: true, h6: true,
27296
    header: true, hgroup: true, hr: true, menu: true, nav: true, ol: true,
27297
    p: true, pre: true, section: true, table: true, ul: true
27298
  },
27299
  rp: {rp: true, rt: true},
27300
  rt: {rp: true, rt: true},
27301
  tbody: {tbody: true, tfoot: true},
27302
  td: {td: true, th: true},
27303
  tfoot: {tbody: true},
27304
  th: {td: true, th: true},
27305
  thead: {tbody: true, tfoot: true},
27306
  tr: {tr: true}
27307
};
27308
 
27309
function nameChar$1(ch) {
27310
  return ch == 45 || ch == 46 || ch == 58 || ch >= 65 && ch <= 90 || ch == 95 || ch >= 97 && ch <= 122 || ch >= 161
27311
}
27312
 
27313
function isSpace$1(ch) {
27314
  return ch == 9 || ch == 10 || ch == 13 || ch == 32
27315
}
27316
 
27317
let cachedName$1 = null, cachedInput$1 = null, cachedPos$1 = 0;
27318
function tagNameAfter$1(input, offset) {
27319
  let pos = input.pos + offset;
27320
  if (cachedPos$1 == pos && cachedInput$1 == input) return cachedName$1
27321
  let next = input.peek(offset);
27322
  while (isSpace$1(next)) next = input.peek(++offset);
27323
  let name = "";
27324
  for (;;) {
27325
    if (!nameChar$1(next)) break
27326
    name += String.fromCharCode(next);
27327
    next = input.peek(++offset);
27328
  }
27329
  // Undefined to signal there's a <? or <!, null for just missing
27330
  cachedInput$1 = input; cachedPos$1 = pos;
1441 ariadna 27331
  return cachedName$1 = name ? name.toLowerCase() : next == question$1 || next == bang ? undefined : null
1 efrain 27332
}
27333
 
1441 ariadna 27334
const lessThan = 60, greaterThan = 62, slash$1 = 47, question$1 = 63, bang = 33, dash$1 = 45;
1 efrain 27335
 
27336
function ElementContext$1(name, parent) {
27337
  this.name = name;
27338
  this.parent = parent;
27339
}
27340
 
27341
const startTagTerms = [StartTag$1, StartSelfClosingTag, StartScriptTag, StartStyleTag, StartTextareaTag];
27342
 
27343
const elementContext$1 = new ContextTracker({
27344
  start: null,
27345
  shift(context, term, stack, input) {
27346
    return startTagTerms.indexOf(term) > -1 ? new ElementContext$1(tagNameAfter$1(input, 1) || "", context) : context
27347
  },
27348
  reduce(context, term) {
27349
    return term == Element$2 && context ? context.parent : context
27350
  },
27351
  reuse(context, node, stack, input) {
27352
    let type = node.type.id;
27353
    return type == StartTag$1 || type == OpenTag$1
27354
      ? new ElementContext$1(tagNameAfter$1(input, 1) || "", context) : context
27355
  },
27356
  strict: false
27357
});
27358
 
27359
const tagStart = new ExternalTokenizer((input, stack) => {
27360
  if (input.next != lessThan) {
27361
    // End of file, close any open tags
27362
    if (input.next < 0 && stack.context) input.acceptToken(missingCloseTag);
27363
    return
27364
  }
27365
  input.advance();
27366
  let close = input.next == slash$1;
27367
  if (close) input.advance();
27368
  let name = tagNameAfter$1(input, 0);
27369
  if (name === undefined) return
27370
  if (!name) return input.acceptToken(close ? IncompleteCloseTag : StartTag$1)
27371
 
27372
  let parent = stack.context ? stack.context.name : null;
27373
  if (close) {
27374
    if (name == parent) return input.acceptToken(StartCloseTag$1)
27375
    if (parent && implicitlyClosed[parent]) return input.acceptToken(missingCloseTag, -2)
27376
    if (stack.dialectEnabled(Dialect_noMatch)) return input.acceptToken(NoMatchStartCloseTag)
27377
    for (let cx = stack.context; cx; cx = cx.parent) if (cx.name == name) return
27378
    input.acceptToken(MismatchedStartCloseTag);
27379
  } else {
27380
    if (name == "script") return input.acceptToken(StartScriptTag)
27381
    if (name == "style") return input.acceptToken(StartStyleTag)
27382
    if (name == "textarea") return input.acceptToken(StartTextareaTag)
27383
    if (selfClosers$1.hasOwnProperty(name)) return input.acceptToken(StartSelfClosingTag)
27384
    if (parent && closeOnOpen[parent] && closeOnOpen[parent][name]) input.acceptToken(missingCloseTag, -1);
27385
    else input.acceptToken(StartTag$1);
27386
  }
27387
}, {contextual: true});
27388
 
27389
const commentContent$2 = new ExternalTokenizer(input => {
27390
  for (let dashes = 0, i = 0;; i++) {
27391
    if (input.next < 0) {
27392
      if (i) input.acceptToken(commentContent$1$1);
27393
      break
27394
    }
27395
    if (input.next == dash$1) {
27396
      dashes++;
27397
    } else if (input.next == greaterThan && dashes >= 2) {
27398
      if (i >= 3) input.acceptToken(commentContent$1$1, -2);
27399
      break
27400
    } else {
27401
      dashes = 0;
27402
    }
27403
    input.advance();
27404
  }
27405
});
27406
 
27407
function inForeignElement(context) {
27408
  for (; context; context = context.parent)
27409
    if (context.name == "svg" || context.name == "math") return true
27410
  return false
27411
}
27412
 
27413
const endTag = new ExternalTokenizer((input, stack) => {
27414
  if (input.next == slash$1 && input.peek(1) == greaterThan) {
27415
    let selfClosing = stack.dialectEnabled(Dialect_selfClosing) || inForeignElement(stack.context);
27416
    input.acceptToken(selfClosing ? SelfClosingEndTag : EndTag, 2);
27417
  } else if (input.next == greaterThan) {
27418
    input.acceptToken(EndTag, 1);
27419
  }
27420
});
27421
 
27422
function contentTokenizer(tag, textToken, endToken) {
27423
  let lastState = 2 + tag.length;
27424
  return new ExternalTokenizer(input => {
27425
    // state means:
27426
    // - 0 nothing matched
27427
    // - 1 '<' matched
27428
    // - 2 '</' + possibly whitespace matched
27429
    // - 3-(1+tag.length) part of the tag matched
27430
    // - lastState whole tag + possibly whitespace matched
27431
    for (let state = 0, matchedLen = 0, i = 0;; i++) {
27432
      if (input.next < 0) {
27433
        if (i) input.acceptToken(textToken);
27434
        break
27435
      }
27436
      if (state == 0 && input.next == lessThan ||
27437
          state == 1 && input.next == slash$1 ||
27438
          state >= 2 && state < lastState && input.next == tag.charCodeAt(state - 2)) {
27439
        state++;
27440
        matchedLen++;
27441
      } else if ((state == 2 || state == lastState) && isSpace$1(input.next)) {
27442
        matchedLen++;
27443
      } else if (state == lastState && input.next == greaterThan) {
27444
        if (i > matchedLen)
27445
          input.acceptToken(textToken, -matchedLen);
27446
        else
27447
          input.acceptToken(endToken, -(matchedLen - 2));
27448
        break
27449
      } else if ((input.next == 10 /* '\n' */ || input.next == 13 /* '\r' */) && i) {
27450
        input.acceptToken(textToken, 1);
27451
        break
27452
      } else {
27453
        state = matchedLen = 0;
27454
      }
27455
      input.advance();
27456
    }
27457
  })
27458
}
27459
 
27460
const scriptTokens = contentTokenizer("script", scriptText, StartCloseScriptTag);
27461
 
27462
const styleTokens = contentTokenizer("style", styleText, StartCloseStyleTag);
27463
 
27464
const textareaTokens = contentTokenizer("textarea", textareaText, StartCloseTextareaTag);
27465
 
27466
const htmlHighlighting = styleTags({
27467
  "Text RawText": tags$1.content,
27468
  "StartTag StartCloseTag SelfClosingEndTag EndTag": tags$1.angleBracket,
27469
  TagName: tags$1.tagName,
27470
  "MismatchedCloseTag/TagName": [tags$1.tagName,  tags$1.invalid],
27471
  AttributeName: tags$1.attributeName,
27472
  "AttributeValue UnquotedAttributeValue": tags$1.attributeValue,
27473
  Is: tags$1.definitionOperator,
27474
  "EntityReference CharacterReference": tags$1.character,
27475
  Comment: tags$1.blockComment,
27476
  ProcessingInst: tags$1.processingInstruction,
27477
  DoctypeDecl: tags$1.documentMeta
27478
});
27479
 
27480
// This file was generated by lezer-generator. You probably shouldn't edit it.
27481
const parser$3 = LRParser.deserialize({
27482
  version: 14,
27483
  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_'#D_O&lObO'#C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X~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~",
27485
  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",
27486
  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",
27487
  maxTerm: 67,
27488
  context: elementContext$1,
27489
  nodeProps: [
27490
    ["closedBy", -10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,21,30,33,36,"CloseTag"],
27491
    ["openedBy", 4,"StartTag StartCloseTag",5,"StartTag",-4,29,32,35,37,"OpenTag"],
27492
    ["group", -9,14,17,18,19,20,39,40,41,42,"Entity",16,"Entity TextContent",-3,28,31,34,"TextContent Entity"],
27493
    ["isolate", -11,21,29,30,32,33,35,36,37,38,41,42,"ltr",-3,26,27,39,""]
27494
  ],
27495
  propSources: [htmlHighlighting],
27496
  skippedNodes: [0],
27497
  repeatNodeCount: 9,
27498
  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)e`)|P;=`<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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",
27499
  tokenizers: [scriptTokens, styleTokens, textareaTokens, endTag, tagStart, commentContent$2, 0, 1, 2, 3, 4, 5],
27500
  topRules: {"Document":[0,15]},
27501
  dialects: {noMatch: 0, selfClosing: 509},
27502
  tokenPrec: 511
27503
});
27504
 
27505
function getAttrs(openTag, input) {
27506
  let attrs = Object.create(null);
27507
  for (let att of openTag.getChildren(Attribute)) {
27508
    let name = att.getChild(AttributeName), value = att.getChild(AttributeValue) || att.getChild(UnquotedAttributeValue);
27509
    if (name) attrs[input.read(name.from, name.to)] =
27510
      !value ? "" : value.type.id == AttributeValue ? input.read(value.from + 1, value.to - 1) : input.read(value.from, value.to);
27511
  }
27512
  return attrs
27513
}
27514
 
27515
function findTagName(openTag, input) {
27516
  let tagNameNode = openTag.getChild(TagName);
27517
  return tagNameNode ? input.read(tagNameNode.from, tagNameNode.to) : " "
27518
}
27519
 
27520
function maybeNest(node, input, tags) {
27521
  let attrs;
27522
  for (let tag of tags) {
27523
    if (!tag.attrs || tag.attrs(attrs || (attrs = getAttrs(node.node.parent.firstChild, input))))
27524
      return {parser: tag.parser}
27525
  }
27526
  return null
27527
}
27528
 
27529
// tags?: {
27530
//   tag: string,
27531
//   attrs?: ({[attr: string]: string}) => boolean,
27532
//   parser: Parser
27533
// }[]
27534
// attributes?: {
27535
//   name: string,
27536
//   tagName?: string,
27537
//   parser: Parser
27538
// }[]
27539
 
27540
function configureNesting(tags = [], attributes = []) {
27541
  let script = [], style = [], textarea = [], other = [];
27542
  for (let tag of tags) {
27543
    let array = tag.tag == "script" ? script : tag.tag == "style" ? style : tag.tag == "textarea" ? textarea : other;
27544
    array.push(tag);
27545
  }
27546
  let attrs = attributes.length ? Object.create(null) : null;
27547
  for (let attr of attributes) (attrs[attr.name] || (attrs[attr.name] = [])).push(attr);
27548
 
27549
  return parseMixed((node, input) => {
27550
    let id = node.type.id;
27551
    if (id == ScriptText) return maybeNest(node, input, script)
27552
    if (id == StyleText) return maybeNest(node, input, style)
27553
    if (id == TextareaText) return maybeNest(node, input, textarea)
27554
 
27555
    if (id == Element$2 && other.length) {
27556
      let n = node.node, open = n.firstChild, tagName = open && findTagName(open, input), attrs;
27557
      if (tagName) for (let tag of other) {
1441 ariadna 27558
        if (tag.tag == tagName && (!tag.attrs || tag.attrs(attrs || (attrs = getAttrs(open, input))))) {
1 efrain 27559
          let close = n.lastChild;
27560
          let to = close.type.id == CloseTag ? close.from : n.to;
27561
          if (to > open.to)
27562
            return {parser: tag.parser, overlay: [{from: open.to, to}]}
27563
        }
27564
      }
27565
    }
27566
 
27567
    if (attrs && id == Attribute) {
27568
      let n = node.node, nameNode;
27569
      if (nameNode = n.firstChild) {
27570
        let matches = attrs[input.read(nameNode.from, nameNode.to)];
27571
        if (matches) for (let attr of matches) {
27572
          if (attr.tagName && attr.tagName != findTagName(n.parent, input)) continue
27573
          let value = n.lastChild;
27574
          if (value.type.id == AttributeValue) {
27575
            let from = value.from + 1;
27576
            let last = value.lastChild, to = value.to - (last && last.isError ? 0 : 1);
27577
            if (to > from) return {parser: attr.parser, overlay: [{from, to}]}
27578
          } else if (value.type.id == UnquotedAttributeValue) {
27579
            return {parser: attr.parser, overlay: [{from: value.from, to: value.to}]}
27580
          }
27581
        }
27582
      }
27583
    }
27584
    return null
27585
  })
27586
}
27587
 
27588
// This file was generated by lezer-generator. You probably shouldn't edit it.
1441 ariadna 27589
const descendantOp = 100,
1 efrain 27590
  Unit = 1,
1441 ariadna 27591
  callee = 101,
27592
  identifier$2 = 102,
1 efrain 27593
  VariableName = 2;
27594
 
27595
/* Hand-written tokenizers for CSS tokens that can't be
27596
   expressed by Lezer's built-in tokenizer. */
27597
 
27598
const space$1 = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197,
27599
               8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288];
1441 ariadna 27600
const colon = 58, parenL = 40, underscore = 95, bracketL$1 = 91, dash = 45, period = 46,
1 efrain 27601
      hash = 35, percent = 37, ampersand = 38, backslash = 92, newline$1 = 10;
27602
 
27603
function isAlpha(ch) { return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 161 }
27604
 
27605
function isDigit(ch) { return ch >= 48 && ch <= 57 }
27606
 
27607
const identifiers = new ExternalTokenizer((input, stack) => {
27608
  for (let inside = false, dashes = 0, i = 0;; i++) {
27609
    let {next} = input;
27610
    if (isAlpha(next) || next == dash || next == underscore || (inside && isDigit(next))) {
27611
      if (!inside && (next != dash || i > 0)) inside = true;
27612
      if (dashes === i && next == dash) dashes++;
27613
      input.advance();
27614
    } else if (next == backslash && input.peek(1) != newline$1) {
27615
      input.advance();
27616
      if (input.next > -1) input.advance();
27617
      inside = true;
27618
    } else {
27619
      if (inside)
27620
        input.acceptToken(next == parenL ? callee : dashes == 2 && stack.canShift(VariableName) ? VariableName : identifier$2);
27621
      break
27622
    }
27623
  }
27624
});
27625
 
27626
const descendant = new ExternalTokenizer(input => {
27627
  if (space$1.includes(input.peek(-1))) {
27628
    let {next} = input;
27629
    if (isAlpha(next) || next == underscore || next == hash || next == period ||
1441 ariadna 27630
        next == bracketL$1 || next == colon && isAlpha(input.peek(1)) ||
1 efrain 27631
        next == dash || next == ampersand)
27632
      input.acceptToken(descendantOp);
27633
  }
27634
});
27635
 
27636
const unitToken = new ExternalTokenizer(input => {
27637
  if (!space$1.includes(input.peek(-1))) {
27638
    let {next} = input;
27639
    if (next == percent) { input.advance(); input.acceptToken(Unit); }
27640
    if (isAlpha(next)) {
27641
      do { input.advance(); } while (isAlpha(input.next) || isDigit(input.next))
27642
      input.acceptToken(Unit);
27643
    }
27644
  }
27645
});
27646
 
27647
const cssHighlighting = styleTags({
27648
  "AtKeyword import charset namespace keyframes media supports": tags$1.definitionKeyword,
27649
  "from to selector": tags$1.keyword,
27650
  NamespaceName: tags$1.namespace,
27651
  KeyframeName: tags$1.labelName,
27652
  KeyframeRangeName: tags$1.operatorKeyword,
27653
  TagName: tags$1.tagName,
27654
  ClassName: tags$1.className,
27655
  PseudoClassName: tags$1.constant(tags$1.className),
27656
  IdName: tags$1.labelName,
27657
  "FeatureName PropertyName": tags$1.propertyName,
27658
  AttributeName: tags$1.attributeName,
27659
  NumberLiteral: tags$1.number,
27660
  KeywordQuery: tags$1.keyword,
27661
  UnaryQueryOp: tags$1.operatorKeyword,
27662
  "CallTag ValueName": tags$1.atom,
27663
  VariableName: tags$1.variableName,
27664
  Callee: tags$1.operatorKeyword,
27665
  Unit: tags$1.unit,
27666
  "UniversalSelector NestingSelector": tags$1.definitionOperator,
27667
  MatchOp: tags$1.compareOperator,
27668
  "ChildOp SiblingOp, LogicOp": tags$1.logicOperator,
27669
  BinOp: tags$1.arithmeticOperator,
27670
  Important: tags$1.modifier,
27671
  Comment: tags$1.blockComment,
27672
  ColorLiteral: tags$1.color,
27673
  "ParenthesizedContent StringLiteral": tags$1.string,
27674
  ":": tags$1.punctuation,
27675
  "PseudoOp #": tags$1.derefOperator,
27676
  "; ,": tags$1.separator,
27677
  "( )": tags$1.paren,
27678
  "[ ]": tags$1.squareBracket,
27679
  "{ }": tags$1.brace
27680
});
27681
 
27682
// This file was generated by lezer-generator. You probably shouldn't edit it.
1441 ariadna 27683
const spec_callee = {__proto__:null,lang:34, "nth-child":34, "nth-last-child":34, "nth-of-type":34, "nth-last-of-type":34, dir:34, "host-context":34, url:62, "url-prefix":62, domain:62, regexp:62, selector:140};
27684
const spec_AtKeyword = {__proto__:null,"@import":120, "@media":144, "@charset":148, "@namespace":152, "@keyframes":158, "@supports":170};
27685
const spec_identifier$1 = {__proto__:null,not:134, only:134};
1 efrain 27686
const parser$2 = LRParser.deserialize({
27687
  version: 14,
1441 ariadna 27688
  states: ":jQYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#CiO$qQ[O'#DUO$vQ[O'#DXOOQP'#En'#EnO${QdO'#DhO%jQ[O'#DuO${QdO'#DwO%{Q[O'#DyO&WQ[O'#D|O&`Q[O'#ESO&nQ[O'#EUOOQS'#Em'#EmOOQS'#EX'#EXQYQ[OOO&uQXO'#CdO'jQWO'#DdO'oQWO'#EsO'zQ[O'#EsQOQWOOP(UO#tO'#C_POOO)C@])C@]OOQP'#Ch'#ChOOQP,59Q,59QO#kQ[O,59QO(aQ[O'#E]O({QWO,58{O)TQ[O,59TO$qQ[O,59pO$vQ[O,59sO(aQ[O,59vO(aQ[O,59xO(aQ[O,59yO)`Q[O'#DcOOQS,58{,58{OOQP'#Cl'#ClOOQO'#DS'#DSOOQP,59T,59TO)gQWO,59TO)lQWO,59TOOQP'#DW'#DWOOQP,59p,59pOOQO'#DY'#DYO)qQ`O,59sOOQS'#Cq'#CqO${QdO'#CrO)yQvO'#CtO+ZQtO,5:SOOQO'#Cy'#CyO)lQWO'#CxO+oQWO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hw!n#t^UOPdhw!n#tQ!uoQ!}tQ#OuQ#PvQ#}#RR$a#hR$R#SQ!VZQ!d]Q#V!TQ#q!m[$P#S$Q$[$s$x%UQ$S#UQ$U#XS$j#q$lQ$o#{R%Q$kR$O#RQiPR#QwQ!c[Q!kaR#Y!VU!_[a!VQ!j`Q#c!^Q#g!`Q$^#dR$_#e",
27691
  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",
1 efrain 27692
  maxTerm: 117,
27693
  nodeProps: [
1441 ariadna 27694
    ["isolate", -2,3,25,""],
27695
    ["openedBy", 18,"(",33,"[",51,"{"],
27696
    ["closedBy", 19,")",34,"]",52,"}"]
1 efrain 27697
  ],
27698
  propSources: [cssHighlighting],
1441 ariadna 27699
  skippedNodes: [0,3,88],
1 efrain 27700
  repeatNodeCount: 11,
1441 ariadna 27701
  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#UG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c!}Ed!}#T%^#T#oEd#o;'S%^;'S;=`%o<%lO%^nFfSr^Oy%^z;'S%^;'S;=`%o<%lO%^nFwSq^Oy%^z;'S%^;'S;=`%o<%lO%^bGWUOy%^z#b%^#b#cGj#c;'S%^;'S;=`%o<%lO%^bGoUp`Oy%^z#W%^#W#XHR#X;'S%^;'S;=`%o<%lO%^bHYS!cQp`Oy%^z;'S%^;'S;=`%o<%lO%^bHiUOy%^z#f%^#f#gHR#g;'S%^;'S;=`%o<%lO%^fIQS!UUOy%^z;'S%^;'S;=`%o<%lO%^nIcS!T^Oy%^z;'S%^;'S;=`%o<%lO%^fItU!SQOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^`JZP;=`<%l$}",
27702
  tokenizers: [descendant, unitToken, identifiers, 1, 2, 3, 4, new LocalTokenGroup("m~RRYZ[z{a~~g~aO#_~~dP!P!Qg~lO#`~~", 28, 106)],
27703
  topRules: {"StyleSheet":[0,4],"Styles":[1,87]},
27704
  specialized: [{term: 101, get: (value) => spec_callee[value] || -1},{term: 59, get: (value) => spec_AtKeyword[value] || -1},{term: 102, get: (value) => spec_identifier$1[value] || -1}],
27705
  tokenPrec: 1219
1 efrain 27706
});
27707
 
27708
let _properties = null;
27709
function properties() {
27710
    if (!_properties && typeof document == "object" && document.body) {
27711
        let { style } = document.body, names = [], seen = new Set;
27712
        for (let prop in style)
27713
            if (prop != "cssText" && prop != "cssFloat") {
27714
                if (typeof style[prop] == "string") {
27715
                    if (/[A-Z]/.test(prop))
27716
                        prop = prop.replace(/[A-Z]/g, ch => "-" + ch.toLowerCase());
27717
                    if (!seen.has(prop)) {
27718
                        names.push(prop);
27719
                        seen.add(prop);
27720
                    }
27721
                }
27722
            }
1441 ariadna 27723
        _properties = names.sort().map(name => ({ type: "property", label: name, apply: name + ": " }));
1 efrain 27724
    }
27725
    return _properties || [];
27726
}
27727
const pseudoClasses = /*@__PURE__*/[
27728
    "active", "after", "any-link", "autofill", "backdrop", "before",
27729
    "checked", "cue", "default", "defined", "disabled", "empty",
27730
    "enabled", "file-selector-button", "first", "first-child",
27731
    "first-letter", "first-line", "first-of-type", "focus",
27732
    "focus-visible", "focus-within", "fullscreen", "has", "host",
27733
    "host-context", "hover", "in-range", "indeterminate", "invalid",
27734
    "is", "lang", "last-child", "last-of-type", "left", "link", "marker",
27735
    "modal", "not", "nth-child", "nth-last-child", "nth-last-of-type",
27736
    "nth-of-type", "only-child", "only-of-type", "optional", "out-of-range",
27737
    "part", "placeholder", "placeholder-shown", "read-only", "read-write",
27738
    "required", "right", "root", "scope", "selection", "slotted", "target",
27739
    "target-text", "valid", "visited", "where"
27740
].map(name => ({ type: "class", label: name }));
27741
const values = /*@__PURE__*/[
27742
    "above", "absolute", "activeborder", "additive", "activecaption", "after-white-space",
27743
    "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always",
27744
    "antialiased", "appworkspace", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column",
27745
    "avoid-page", "avoid-region", "axis-pan", "background", "backwards", "baseline", "below",
27746
    "bidi-override", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
27747
    "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
27748
    "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "capitalize",
27749
    "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle",
27750
    "cjk-decimal", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn",
27751
    "color-dodge", "column", "column-reverse", "compact", "condensed", "contain", "content",
27752
    "contents", "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover",
27753
    "crop", "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
27754
    "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in",
27755
    "destination-out", "destination-over", "difference", "disc", "discard", "disclosure-closed",
27756
    "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize",
27757
    "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end",
27758
    "ethiopic-abegede-gez", "ethiopic-halehame-aa-er", "ethiopic-halehame-gez", "ew-resize", "exclusion",
27759
    "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fill-box",
27760
    "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from",
27761
    "geometricPrecision", "graytext", "grid", "groove", "hand", "hard-light", "help", "hidden", "hide",
27762
    "higher", "highlight", "highlighttext", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
27763
    "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext",
27764
    "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid",
27765
    "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "keep-all",
27766
    "landscape", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear",
27767
    "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower",
27768
    "lower-hexadecimal", "lower-latin", "lower-norwegian", "lowercase", "ltr", "luminosity", "manipulation",
27769
    "match", "matrix", "matrix3d", "medium", "menu", "menutext", "message-box", "middle", "min-intrinsic",
27770
    "mix", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "n-resize", "narrower",
27771
    "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none",
27772
    "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize",
27773
    "oblique", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "outset", "outside",
27774
    "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused",
27775
    "perspective", "pinch-zoom", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait",
27776
    "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio",
27777
    "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat",
27778
    "repeating-linear-gradient", "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
27779
    "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round",
27780
    "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturation",
27781
    "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position",
27782
    "se-resize", "self-start", "self-end", "semi-condensed", "semi-expanded", "separate", "serif", "show",
27783
    "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
27784
    "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps",
27785
    "small-caption", "smaller", "soft-light", "solid", "source-atop", "source-in", "source-out",
27786
    "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "start",
27787
    "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", "subpixel-antialiased", "svg_masks",
27788
    "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", "table-caption", "table-cell",
27789
    "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row",
27790
    "table-row-group", "text", "text-bottom", "text-top", "textarea", "textfield", "thick", "thin",
27791
    "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "to", "top",
27792
    "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent",
27793
    "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", "upper-latin",
27794
    "uppercase", "url", "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill",
27795
    "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe",
27796
    "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small"
27797
].map(name => ({ type: "keyword", label: name })).concat(/*@__PURE__*/[
27798
    "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
27799
    "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
27800
    "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
27801
    "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
27802
    "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
27803
    "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
27804
    "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
27805
    "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
27806
    "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
27807
    "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
27808
    "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
27809
    "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
27810
    "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
27811
    "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
27812
    "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
27813
    "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
27814
    "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
27815
    "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
27816
    "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
27817
    "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
27818
    "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
27819
    "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
27820
    "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
27821
    "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
27822
    "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
27823
    "whitesmoke", "yellow", "yellowgreen"
27824
].map(name => ({ type: "constant", label: name })));
27825
const tags = /*@__PURE__*/[
27826
    "a", "abbr", "address", "article", "aside", "b", "bdi", "bdo", "blockquote", "body",
27827
    "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "dd", "del",
27828
    "details", "dfn", "dialog", "div", "dl", "dt", "em", "figcaption", "figure", "footer",
27829
    "form", "header", "hgroup", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "html", "i", "iframe",
27830
    "img", "input", "ins", "kbd", "label", "legend", "li", "main", "meter", "nav", "ol", "output",
27831
    "p", "pre", "ruby", "section", "select", "small", "source", "span", "strong", "sub", "summary",
27832
    "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "tr", "u", "ul"
27833
].map(name => ({ type: "type", label: name }));
1441 ariadna 27834
const atRules = /*@__PURE__*/[
27835
    "@charset", "@color-profile", "@container", "@counter-style", "@font-face", "@font-feature-values",
27836
    "@font-palette-values", "@import", "@keyframes", "@layer", "@media", "@namespace", "@page",
27837
    "@position-try", "@property", "@scope", "@starting-style", "@supports", "@view-transition"
27838
].map(label => ({ type: "keyword", label }));
1 efrain 27839
const identifier$1 = /^(\w[\w-]*|-\w[\w-]*|)$/, variable = /^-(-[\w-]*)?$/;
27840
function isVarArg(node, doc) {
27841
    var _a;
27842
    if (node.name == "(" || node.type.isError)
27843
        node = node.parent || node;
27844
    if (node.name != "ArgList")
27845
        return false;
27846
    let callee = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.firstChild;
27847
    if ((callee === null || callee === void 0 ? void 0 : callee.name) != "Callee")
27848
        return false;
27849
    return doc.sliceString(callee.from, callee.to) == "var";
27850
}
27851
const VariablesByNode = /*@__PURE__*/new NodeWeakMap();
27852
const declSelector = ["Declaration"];
27853
function astTop(node) {
27854
    for (let cur = node;;) {
27855
        if (cur.type.isTop)
27856
            return cur;
27857
        if (!(cur = cur.parent))
27858
            return node;
27859
    }
27860
}
27861
function variableNames(doc, node, isVariable) {
27862
    if (node.to - node.from > 4096) {
27863
        let known = VariablesByNode.get(node);
27864
        if (known)
27865
            return known;
27866
        let result = [], seen = new Set, cursor = node.cursor(IterMode.IncludeAnonymous);
27867
        if (cursor.firstChild())
27868
            do {
27869
                for (let option of variableNames(doc, cursor.node, isVariable))
27870
                    if (!seen.has(option.label)) {
27871
                        seen.add(option.label);
27872
                        result.push(option);
27873
                    }
27874
            } while (cursor.nextSibling());
27875
        VariablesByNode.set(node, result);
27876
        return result;
27877
    }
27878
    else {
27879
        let result = [], seen = new Set;
27880
        node.cursor().iterate(node => {
27881
            var _a;
27882
            if (isVariable(node) && node.matchContext(declSelector) && ((_a = node.node.nextSibling) === null || _a === void 0 ? void 0 : _a.name) == ":") {
27883
                let name = doc.sliceString(node.from, node.to);
27884
                if (!seen.has(name)) {
27885
                    seen.add(name);
27886
                    result.push({ label: name, type: "variable" });
27887
                }
27888
            }
27889
        });
27890
        return result;
27891
    }
27892
}
27893
/**
27894
Create a completion source for a CSS dialect, providing a
27895
predicate for determining what kind of syntax node can act as a
27896
completable variable. This is used by language modes like Sass and
27897
Less to reuse this package's completion logic.
27898
*/
27899
const defineCSSCompletionSource = (isVariable) => context => {
27900
    let { state, pos } = context, node = syntaxTree(state).resolveInner(pos, -1);
27901
    let isDash = node.type.isError && node.from == node.to - 1 && state.doc.sliceString(node.from, node.to) == "-";
27902
    if (node.name == "PropertyName" ||
27903
        (isDash || node.name == "TagName") && /^(Block|Styles)$/.test(node.resolve(node.to).name))
27904
        return { from: node.from, options: properties(), validFor: identifier$1 };
27905
    if (node.name == "ValueName")
27906
        return { from: node.from, options: values, validFor: identifier$1 };
27907
    if (node.name == "PseudoClassName")
27908
        return { from: node.from, options: pseudoClasses, validFor: identifier$1 };
27909
    if (isVariable(node) || (context.explicit || isDash) && isVarArg(node, state.doc))
27910
        return { from: isVariable(node) || isDash ? node.from : pos,
27911
            options: variableNames(state.doc, astTop(node), isVariable),
27912
            validFor: variable };
27913
    if (node.name == "TagName") {
27914
        for (let { parent } = node; parent; parent = parent.parent)
27915
            if (parent.name == "Block")
27916
                return { from: node.from, options: properties(), validFor: identifier$1 };
27917
        return { from: node.from, options: tags, validFor: identifier$1 };
27918
    }
1441 ariadna 27919
    if (node.name == "AtKeyword")
27920
        return { from: node.from, options: atRules, validFor: identifier$1 };
1 efrain 27921
    if (!context.explicit)
27922
        return null;
27923
    let above = node.resolve(pos), before = above.childBefore(pos);
27924
    if (before && before.name == ":" && above.name == "PseudoClassSelector")
27925
        return { from: pos, options: pseudoClasses, validFor: identifier$1 };
27926
    if (before && before.name == ":" && above.name == "Declaration" || above.name == "ArgList")
27927
        return { from: pos, options: values, validFor: identifier$1 };
27928
    if (above.name == "Block" || above.name == "Styles")
27929
        return { from: pos, options: properties(), validFor: identifier$1 };
27930
    return null;
27931
};
27932
/**
27933
CSS property, variable, and value keyword completion source.
27934
*/
27935
const cssCompletionSource = /*@__PURE__*/defineCSSCompletionSource(n => n.name == "VariableName");
27936
 
27937
/**
27938
A language provider based on the [Lezer CSS
27939
parser](https://github.com/lezer-parser/css), extended with
27940
highlighting and indentation information.
27941
*/
27942
const cssLanguage = /*@__PURE__*/LRLanguage.define({
27943
    name: "css",
27944
    parser: /*@__PURE__*/parser$2.configure({
27945
        props: [
27946
            /*@__PURE__*/indentNodeProp.add({
27947
                Declaration: /*@__PURE__*/continuedIndent()
27948
            }),
27949
            /*@__PURE__*/foldNodeProp.add({
27950
                "Block KeyframeList": foldInside
27951
            })
27952
        ]
27953
    }),
27954
    languageData: {
27955
        commentTokens: { block: { open: "/*", close: "*/" } },
27956
        indentOnInput: /^\s*\}$/,
27957
        wordChars: "-"
27958
    }
27959
});
27960
/**
27961
Language support for CSS.
27962
*/
27963
function css() {
27964
    return new LanguageSupport(cssLanguage, cssLanguage.data.of({ autocomplete: cssCompletionSource }));
27965
}
27966
 
27967
// This file was generated by lezer-generator. You probably shouldn't edit it.
1441 ariadna 27968
const noSemi = 314,
27969
  noSemiType = 315,
1 efrain 27970
  incdec = 1,
27971
  incdecPrefix = 2,
1441 ariadna 27972
  questionDot = 3,
27973
  JSXStartTag = 4,
27974
  insertSemi = 316,
27975
  spaces = 318,
27976
  newline = 319,
27977
  LineComment = 5,
27978
  BlockComment = 6,
1 efrain 27979
  Dialect_jsx = 0;
27980
 
27981
/* Hand-written tokenizers for JavaScript tokens that can't be
27982
   expressed by lezer's built-in tokenizer. */
27983
 
27984
const space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200,
27985
               8201, 8202, 8232, 8233, 8239, 8287, 12288];
27986
 
1441 ariadna 27987
const braceR = 125, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45, lt = 60, comma = 44,
27988
      question = 63, dot = 46, bracketL = 91;
1 efrain 27989
 
27990
const trackNewline = new ContextTracker({
27991
  start: false,
27992
  shift(context, term) {
27993
    return term == LineComment || term == BlockComment || term == spaces ? context : term == newline
27994
  },
27995
  strict: false
27996
});
27997
 
27998
const insertSemicolon = new ExternalTokenizer((input, stack) => {
27999
  let {next} = input;
28000
  if (next == braceR || next == -1 || stack.context)
28001
    input.acceptToken(insertSemi);
28002
}, {contextual: true, fallback: true});
28003
 
28004
const noSemicolon = new ExternalTokenizer((input, stack) => {
28005
  let {next} = input, after;
28006
  if (space.indexOf(next) > -1) return
28007
  if (next == slash && ((after = input.peek(1)) == slash || after == star)) return
28008
  if (next != braceR && next != semicolon && next != -1 && !stack.context)
28009
    input.acceptToken(noSemi);
28010
}, {contextual: true});
28011
 
1441 ariadna 28012
const noSemicolonType = new ExternalTokenizer((input, stack) => {
28013
  if (input.next == bracketL && !stack.context) input.acceptToken(noSemiType);
28014
}, {contextual: true});
28015
 
28016
const operatorToken = new ExternalTokenizer((input, stack) => {
1 efrain 28017
  let {next} = input;
28018
  if (next == plus || next == minus) {
28019
    input.advance();
28020
    if (next == input.next) {
28021
      input.advance();
28022
      let mayPostfix = !stack.context && stack.canShift(incdec);
28023
      input.acceptToken(mayPostfix ? incdec : incdecPrefix);
28024
    }
1441 ariadna 28025
  } else if (next == question && input.peek(1) == dot) {
28026
    input.advance(); input.advance();
28027
    if (input.next < 48 || input.next > 57) // No digit after
28028
      input.acceptToken(questionDot);
1 efrain 28029
  }
28030
}, {contextual: true});
28031
 
28032
function identifierChar(ch, start) {
28033
  return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch == 95 || ch >= 192 ||
28034
    !start && ch >= 48 && ch <= 57
28035
}
28036
 
28037
const jsx = new ExternalTokenizer((input, stack) => {
28038
  if (input.next != lt || !stack.dialectEnabled(Dialect_jsx)) return
28039
  input.advance();
28040
  if (input.next == slash) return
28041
  // Scan for an identifier followed by a comma or 'extends', don't
28042
  // treat this as a start tag if present.
28043
  let back = 0;
28044
  while (space.indexOf(input.next) > -1) { input.advance(); back++; }
28045
  if (identifierChar(input.next, true)) {
28046
    input.advance();
28047
    back++;
28048
    while (identifierChar(input.next, false)) { input.advance(); back++; }
28049
    while (space.indexOf(input.next) > -1) { input.advance(); back++; }
28050
    if (input.next == comma) return
28051
    for (let i = 0;; i++) {
28052
      if (i == 7) {
28053
        if (!identifierChar(input.next, true)) return
28054
        break
28055
      }
28056
      if (input.next != "extends".charCodeAt(i)) break
28057
      input.advance();
28058
      back++;
28059
    }
28060
  }
28061
  input.acceptToken(JSXStartTag, -back);
28062
});
28063
 
28064
const jsHighlight = styleTags({
28065
  "get set async static": tags$1.modifier,
28066
  "for while do if else switch try catch finally return throw break continue default case": tags$1.controlKeyword,
28067
  "in of await yield void typeof delete instanceof": tags$1.operatorKeyword,
28068
  "let var const using function class extends": tags$1.definitionKeyword,
28069
  "import export from": tags$1.moduleKeyword,
28070
  "with debugger as new": tags$1.keyword,
28071
  TemplateString: tags$1.special(tags$1.string),
28072
  super: tags$1.atom,
28073
  BooleanLiteral: tags$1.bool,
28074
  this: tags$1.self,
28075
  null: tags$1.null,
28076
  Star: tags$1.modifier,
28077
  VariableName: tags$1.variableName,
28078
  "CallExpression/VariableName TaggedTemplateExpression/VariableName": tags$1.function(tags$1.variableName),
28079
  VariableDefinition: tags$1.definition(tags$1.variableName),
28080
  Label: tags$1.labelName,
28081
  PropertyName: tags$1.propertyName,
28082
  PrivatePropertyName: tags$1.special(tags$1.propertyName),
28083
  "CallExpression/MemberExpression/PropertyName": tags$1.function(tags$1.propertyName),
28084
  "FunctionDeclaration/VariableDefinition": tags$1.function(tags$1.definition(tags$1.variableName)),
28085
  "ClassDeclaration/VariableDefinition": tags$1.definition(tags$1.className),
1441 ariadna 28086
  "NewExpression/VariableName": tags$1.className,
1 efrain 28087
  PropertyDefinition: tags$1.definition(tags$1.propertyName),
28088
  PrivatePropertyDefinition: tags$1.definition(tags$1.special(tags$1.propertyName)),
28089
  UpdateOp: tags$1.updateOperator,
28090
  "LineComment Hashbang": tags$1.lineComment,
28091
  BlockComment: tags$1.blockComment,
28092
  Number: tags$1.number,
28093
  String: tags$1.string,
28094
  Escape: tags$1.escape,
28095
  ArithOp: tags$1.arithmeticOperator,
28096
  LogicOp: tags$1.logicOperator,
28097
  BitOp: tags$1.bitwiseOperator,
28098
  CompareOp: tags$1.compareOperator,
28099
  RegExp: tags$1.regexp,
28100
  Equals: tags$1.definitionOperator,
28101
  Arrow: tags$1.function(tags$1.punctuation),
28102
  ": Spread": tags$1.punctuation,
28103
  "( )": tags$1.paren,
28104
  "[ ]": tags$1.squareBracket,
28105
  "{ }": tags$1.brace,
28106
  "InterpolationStart InterpolationEnd": tags$1.special(tags$1.brace),
28107
  ".": tags$1.derefOperator,
28108
  ", ;": tags$1.separator,
28109
  "@": tags$1.meta,
28110
 
28111
  TypeName: tags$1.typeName,
28112
  TypeDefinition: tags$1.definition(tags$1.typeName),
28113
  "type enum interface implements namespace module declare": tags$1.definitionKeyword,
28114
  "abstract global Privacy readonly override": tags$1.modifier,
1441 ariadna 28115
  "is keyof unique infer asserts": tags$1.operatorKeyword,
1 efrain 28116
 
28117
  JSXAttributeValue: tags$1.attributeValue,
28118
  JSXText: tags$1.content,
28119
  "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags$1.angleBracket,
28120
  "JSXIdentifier JSXNameSpacedName": tags$1.tagName,
28121
  "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags$1.attributeName,
28122
  "JSXBuiltin/JSXIdentifier": tags$1.standard(tags$1.tagName)
28123
});
28124
 
28125
// This file was generated by lezer-generator. You probably shouldn't edit it.
1441 ariadna 28126
const spec_identifier = {__proto__:null,export:20, as:25, from:33, default:36, async:41, function:42, const:52, extends:56, this:60, true:68, false:68, null:80, void:84, typeof:88, super:104, new:138, delete:150, yield:159, await:163, class:168, public:231, private:231, protected:231, readonly:233, instanceof:252, satisfies:255, in:256, import:290, keyof:347, unique:351, infer:357, asserts:393, is:395, abstract:415, implements:417, type:419, let:422, var:424, using:427, interface:433, enum:437, namespace:443, module:445, declare:449, global:453, for:472, of:481, while:484, with:488, do:492, if:496, else:498, switch:502, case:508, try:514, catch:518, finally:522, return:526, throw:530, break:534, continue:538, debugger:542};
28127
const spec_word = {__proto__:null,async:125, get:127, set:129, declare:191, public:193, private:193, protected:193, static:195, abstract:197, override:199, readonly:205, accessor:207, new:399};
28128
const spec_LessThan = {__proto__:null,"<":189};
1 efrain 28129
const parser$1 = LRParser.deserialize({
28130
  version: 14,
1441 ariadna 28131
  states: "$EOQ%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#D_O.QQlO'#DeO.bQlO'#DpO%[QlO'#DxO0fQlO'#EQOOQ!0Lf'#EY'#EYO1PQ`O'#EVOOQO'#En'#EnOOQO'#Ij'#IjO1XQ`O'#GrO1dQ`O'#EmO1iQ`O'#EmO3hQ!0MxO'#JpO6[Q!0MxO'#JqO6uQ`O'#F[O6zQ,UO'#FsOOQ!0Lf'#Fe'#FeO7VO7dO'#FeO7eQMhO'#F{O9UQ`O'#FzOOQ!0Lf'#Jq'#JqOOQ!0Lb'#Jp'#JpO9ZQ`O'#GvOOQ['#K]'#K]O9fQ`O'#IWO9kQ!0LrO'#IXOOQ['#J^'#J^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ctionDeclaration async function VariableDefinition > < TypeParamList const 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 : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < 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 CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression 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 InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts 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",
28135
  maxTerm: 378,
1 efrain 28136
  context: trackNewline,
28137
  nodeProps: [
1441 ariadna 28138
    ["isolate", -8,5,6,14,35,37,49,51,53,""],
28139
    ["group", -26,9,17,19,66,206,210,214,215,217,220,223,233,235,241,243,245,247,250,256,262,264,266,268,270,272,273,"Statement",-34,13,14,30,33,34,40,49,52,53,55,60,68,70,74,78,80,82,83,108,109,118,119,135,138,140,141,142,143,144,146,147,166,168,170,"Expression",-23,29,31,35,39,41,43,172,174,176,177,179,180,181,183,184,185,187,188,189,200,202,204,205,"Type",-3,86,101,107,"ClassItem"],
28140
    ["openedBy", 23,"<",36,"InterpolationStart",54,"[",58,"{",71,"(",159,"JSXStartCloseTag"],
28141
    ["closedBy", -2,24,167,">",38,"InterpolationEnd",48,"]",59,"}",72,")",164,"JSXEndTag"]
1 efrain 28142
  ],
28143
  propSources: [jsHighlight],
1441 ariadna 28144
  skippedNodes: [0,5,6,276],
1 efrain 28145
  repeatNodeCount: 37,
1441 ariadna 28146
  tokenData: "$Fq07[R!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$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$<r#p#q$=h#q#r$>x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`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up(X!b'{0/l$[#t(R,2j(c$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",
28147
  tokenizers: [noSemicolon, noSemicolonType, operatorToken, jsx, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, insertSemicolon, new LocalTokenGroup("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOv~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!S~~!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(a~~", 141, 338), new LocalTokenGroup("j~RQYZXz{^~^O(O~~aP!P!Qd~iO(P~~", 25, 321)],
28148
  topRules: {"Script":[0,7],"SingleExpression":[1,274],"SingleClassItem":[2,275]},
28149
  dialects: {jsx: 0, ts: 15091},
28150
  dynamicPrecedences: {"78":1,"80":1,"92":1,"168":1,"198":1},
28151
  specialized: [{term: 325, get: (value) => spec_identifier[value] || -1},{term: 341, get: (value) => spec_word[value] || -1},{term: 93, get: (value) => spec_LessThan[value] || -1}],
28152
  tokenPrec: 15116
1 efrain 28153
});
28154
 
28155
/**
28156
A collection of JavaScript-related
28157
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
28158
*/
28159
const snippets = [
28160
    /*@__PURE__*/snippetCompletion("function ${name}(${params}) {\n\t${}\n}", {
28161
        label: "function",
28162
        detail: "definition",
28163
        type: "keyword"
28164
    }),
28165
    /*@__PURE__*/snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}", {
28166
        label: "for",
28167
        detail: "loop",
28168
        type: "keyword"
28169
    }),
28170
    /*@__PURE__*/snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}", {
28171
        label: "for",
28172
        detail: "of loop",
28173
        type: "keyword"
28174
    }),
28175
    /*@__PURE__*/snippetCompletion("do {\n\t${}\n} while (${})", {
28176
        label: "do",
28177
        detail: "loop",
28178
        type: "keyword"
28179
    }),
28180
    /*@__PURE__*/snippetCompletion("while (${}) {\n\t${}\n}", {
28181
        label: "while",
28182
        detail: "loop",
28183
        type: "keyword"
28184
    }),
28185
    /*@__PURE__*/snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}", {
28186
        label: "try",
28187
        detail: "/ catch block",
28188
        type: "keyword"
28189
    }),
28190
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n}", {
28191
        label: "if",
28192
        detail: "block",
28193
        type: "keyword"
28194
    }),
28195
    /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}", {
28196
        label: "if",
28197
        detail: "/ else block",
28198
        type: "keyword"
28199
    }),
28200
    /*@__PURE__*/snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}", {
28201
        label: "class",
28202
        detail: "definition",
28203
        type: "keyword"
28204
    }),
28205
    /*@__PURE__*/snippetCompletion("import {${names}} from \"${module}\"\n${}", {
28206
        label: "import",
28207
        detail: "named",
28208
        type: "keyword"
28209
    }),
28210
    /*@__PURE__*/snippetCompletion("import ${name} from \"${module}\"\n${}", {
28211
        label: "import",
28212
        detail: "default",
28213
        type: "keyword"
28214
    })
28215
];
28216
/**
28217
A collection of snippet completions for TypeScript. Includes the
28218
JavaScript [snippets](https://codemirror.net/6/docs/ref/#lang-javascript.snippets).
28219
*/
28220
const typescriptSnippets = /*@__PURE__*/snippets.concat([
28221
    /*@__PURE__*/snippetCompletion("interface ${name} {\n\t${}\n}", {
28222
        label: "interface",
28223
        detail: "definition",
28224
        type: "keyword"
28225
    }),
28226
    /*@__PURE__*/snippetCompletion("type ${name} = ${type}", {
28227
        label: "type",
28228
        detail: "definition",
28229
        type: "keyword"
28230
    }),
28231
    /*@__PURE__*/snippetCompletion("enum ${name} {\n\t${}\n}", {
28232
        label: "enum",
28233
        detail: "definition",
28234
        type: "keyword"
28235
    })
28236
]);
28237
 
28238
const cache = /*@__PURE__*/new NodeWeakMap();
28239
const ScopeNodes = /*@__PURE__*/new Set([
28240
    "Script", "Block",
28241
    "FunctionExpression", "FunctionDeclaration", "ArrowFunction", "MethodDeclaration",
28242
    "ForStatement"
28243
]);
28244
function defID(type) {
28245
    return (node, def) => {
28246
        let id = node.node.getChild("VariableDefinition");
28247
        if (id)
28248
            def(id, type);
28249
        return true;
28250
    };
28251
}
28252
const functionContext = ["FunctionDeclaration"];
28253
const gatherCompletions = {
28254
    FunctionDeclaration: /*@__PURE__*/defID("function"),
28255
    ClassDeclaration: /*@__PURE__*/defID("class"),
28256
    ClassExpression: () => true,
28257
    EnumDeclaration: /*@__PURE__*/defID("constant"),
28258
    TypeAliasDeclaration: /*@__PURE__*/defID("type"),
28259
    NamespaceDeclaration: /*@__PURE__*/defID("namespace"),
28260
    VariableDefinition(node, def) { if (!node.matchContext(functionContext))
28261
        def(node, "variable"); },
28262
    TypeDefinition(node, def) { def(node, "type"); },
28263
    __proto__: null
28264
};
28265
function getScope(doc, node) {
28266
    let cached = cache.get(node);
28267
    if (cached)
28268
        return cached;
28269
    let completions = [], top = true;
28270
    function def(node, type) {
28271
        let name = doc.sliceString(node.from, node.to);
28272
        completions.push({ label: name, type });
28273
    }
28274
    node.cursor(IterMode.IncludeAnonymous).iterate(node => {
28275
        if (top) {
28276
            top = false;
28277
        }
28278
        else if (node.name) {
28279
            let gather = gatherCompletions[node.name];
28280
            if (gather && gather(node, def) || ScopeNodes.has(node.name))
28281
                return false;
28282
        }
28283
        else if (node.to - node.from > 8192) {
28284
            // Allow caching for bigger internal nodes
28285
            for (let c of getScope(doc, node.node))
28286
                completions.push(c);
28287
            return false;
28288
        }
28289
    });
28290
    cache.set(node, completions);
28291
    return completions;
28292
}
28293
const Identifier$1 = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
28294
const dontComplete = [
28295
    "TemplateString", "String", "RegExp",
28296
    "LineComment", "BlockComment",
28297
    "VariableDefinition", "TypeDefinition", "Label",
28298
    "PropertyDefinition", "PropertyName",
28299
    "PrivatePropertyDefinition", "PrivatePropertyName",
1441 ariadna 28300
    "JSXText", "JSXAttributeValue", "JSXOpenTag", "JSXCloseTag", "JSXSelfClosingTag",
1 efrain 28301
    ".", "?."
28302
];
28303
/**
28304
Completion source that looks up locally defined names in
28305
JavaScript code.
28306
*/
28307
function localCompletionSource(context) {
28308
    let inner = syntaxTree(context.state).resolveInner(context.pos, -1);
28309
    if (dontComplete.indexOf(inner.name) > -1)
28310
        return null;
28311
    let isWord = inner.name == "VariableName" ||
28312
        inner.to - inner.from < 20 && Identifier$1.test(context.state.sliceDoc(inner.from, inner.to));
28313
    if (!isWord && !context.explicit)
28314
        return null;
28315
    let options = [];
28316
    for (let pos = inner; pos; pos = pos.parent) {
28317
        if (ScopeNodes.has(pos.name))
28318
            options = options.concat(getScope(context.state.doc, pos));
28319
    }
28320
    return {
28321
        options,
28322
        from: isWord ? inner.from : context.pos,
28323
        validFor: Identifier$1
28324
    };
28325
}
28326
 
28327
/**
28328
A language provider based on the [Lezer JavaScript
28329
parser](https://github.com/lezer-parser/javascript), extended with
28330
highlighting and indentation information.
28331
*/
28332
const javascriptLanguage = /*@__PURE__*/LRLanguage.define({
28333
    name: "javascript",
28334
    parser: /*@__PURE__*/parser$1.configure({
28335
        props: [
28336
            /*@__PURE__*/indentNodeProp.add({
28337
                IfStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|else\b)/ }),
28338
                TryStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|catch\b|finally\b)/ }),
28339
                LabeledStatement: flatIndent,
28340
                SwitchBody: context => {
28341
                    let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
28342
                    return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
28343
                },
28344
                Block: /*@__PURE__*/delimitedIndent({ closing: "}" }),
28345
                ArrowFunction: cx => cx.baseIndent + cx.unit,
28346
                "TemplateString BlockComment": () => null,
28347
                "Statement Property": /*@__PURE__*/continuedIndent({ except: /^{/ }),
28348
                JSXElement(context) {
28349
                    let closed = /^\s*<\//.test(context.textAfter);
28350
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
28351
                },
28352
                JSXEscape(context) {
28353
                    let closed = /\s*\}/.test(context.textAfter);
28354
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
28355
                },
28356
                "JSXOpenTag JSXSelfClosingTag"(context) {
28357
                    return context.column(context.node.from) + context.unit;
28358
                }
28359
            }),
28360
            /*@__PURE__*/foldNodeProp.add({
28361
                "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType": foldInside,
28362
                BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
28363
            })
28364
        ]
28365
    }),
28366
    languageData: {
28367
        closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
28368
        commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
28369
        indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/,
28370
        wordChars: "$"
28371
    }
28372
});
28373
const jsxSublanguage = {
28374
    test: node => /^JSX/.test(node.name),
28375
    facet: /*@__PURE__*/defineLanguageFacet({ commentTokens: { block: { open: "{/*", close: "*/}" } } })
28376
};
28377
/**
28378
A language provider for TypeScript.
28379
*/
28380
const typescriptLanguage = /*@__PURE__*/javascriptLanguage.configure({ dialect: "ts" }, "typescript");
28381
/**
28382
Language provider for JSX.
28383
*/
28384
const jsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
28385
    dialect: "jsx",
28386
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
28387
});
28388
/**
28389
Language provider for JSX + TypeScript.
28390
*/
28391
const tsxLanguage = /*@__PURE__*/javascriptLanguage.configure({
28392
    dialect: "jsx ts",
28393
    props: [/*@__PURE__*/sublanguageProp.add(n => n.isTop ? [jsxSublanguage] : undefined)]
28394
}, "typescript");
28395
let kwCompletion = (name) => ({ label: name, type: "keyword" });
28396
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);
28397
const typescriptKeywords = /*@__PURE__*/keywords.concat(/*@__PURE__*/["declare", "implements", "private", "protected", "public"].map(kwCompletion));
28398
/**
28399
JavaScript support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-javascript.snippets)
28400
and local variable completion.
28401
*/
28402
function javascript(config = {}) {
28403
    let lang = config.jsx ? (config.typescript ? tsxLanguage : jsxLanguage)
28404
        : config.typescript ? typescriptLanguage : javascriptLanguage;
28405
    let completions = config.typescript ? typescriptSnippets.concat(typescriptKeywords) : snippets.concat(keywords);
28406
    return new LanguageSupport(lang, [
28407
        javascriptLanguage.data.of({
28408
            autocomplete: ifNotIn(dontComplete, completeFromList(completions))
28409
        }),
28410
        javascriptLanguage.data.of({
28411
            autocomplete: localCompletionSource
28412
        }),
28413
        config.jsx ? autoCloseTags$2 : [],
28414
    ]);
28415
}
28416
function findOpenTag(node) {
28417
    for (;;) {
28418
        if (node.name == "JSXOpenTag" || node.name == "JSXSelfClosingTag" || node.name == "JSXFragmentTag")
28419
            return node;
28420
        if (node.name == "JSXEscape" || !node.parent)
28421
            return null;
28422
        node = node.parent;
28423
    }
28424
}
28425
function elementName$3(doc, tree, max = doc.length) {
28426
    for (let ch = tree === null || tree === void 0 ? void 0 : tree.firstChild; ch; ch = ch.nextSibling) {
28427
        if (ch.name == "JSXIdentifier" || ch.name == "JSXBuiltin" || ch.name == "JSXNamespacedName" ||
28428
            ch.name == "JSXMemberExpression")
28429
            return doc.sliceString(ch.from, Math.min(ch.to, max));
28430
    }
28431
    return "";
28432
}
28433
const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
28434
/**
28435
Extension that will automatically insert JSX close tags when a `>` or
28436
`/` is typed.
28437
*/
28438
const autoCloseTags$2 = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, defaultInsert) => {
28439
    if ((android ? view.composing : view.compositionStarted) || view.state.readOnly ||
28440
        from != to || (text != ">" && text != "/") ||
28441
        !javascriptLanguage.isActiveAt(view.state, from, -1))
28442
        return false;
28443
    let base = defaultInsert(), { state } = base;
28444
    let closeTags = state.changeByRange(range => {
28445
        var _a;
28446
        let { head } = range, around = syntaxTree(state).resolveInner(head - 1, -1), name;
28447
        if (around.name == "JSXStartTag")
28448
            around = around.parent;
28449
        if (state.doc.sliceString(head - 1, head) != text || around.name == "JSXAttributeValue" && around.to > head) ;
28450
        else if (text == ">" && around.name == "JSXFragmentTag") {
28451
            return { range, changes: { from: head, insert: `</>` } };
28452
        }
28453
        else if (text == "/" && around.name == "JSXStartCloseTag") {
28454
            let empty = around.parent, base = empty.parent;
28455
            if (base && empty.from == head - 2 &&
28456
                ((name = elementName$3(state.doc, base.firstChild, head)) || ((_a = base.firstChild) === null || _a === void 0 ? void 0 : _a.name) == "JSXFragmentTag")) {
28457
                let insert = `${name}>`;
28458
                return { range: EditorSelection.cursor(head + insert.length, -1), changes: { from: head, insert } };
28459
            }
28460
        }
28461
        else if (text == ">") {
28462
            let openTag = findOpenTag(around);
28463
            if (openTag && openTag.name == "JSXOpenTag" &&
28464
                !/^\/?>|^<\//.test(state.doc.sliceString(head, head + 2)) &&
28465
                (name = elementName$3(state.doc, openTag, head)))
28466
                return { range, changes: { from: head, insert: `</${name}>` } };
28467
        }
28468
        return { range };
28469
    });
28470
    if (closeTags.changes.empty)
28471
        return false;
28472
    view.dispatch([
28473
        base,
28474
        state.update(closeTags, { userEvent: "input.complete", scrollIntoView: true })
28475
    ]);
28476
    return true;
28477
});
28478
 
28479
const Targets = ["_blank", "_self", "_top", "_parent"];
28480
const Charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
28481
const Methods = ["get", "post", "put", "delete"];
28482
const Encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
28483
const Bool = ["true", "false"];
28484
const S = {}; // Empty tag spec
28485
const Tags = {
28486
    a: {
28487
        attrs: {
28488
            href: null, ping: null, type: null,
28489
            media: null,
28490
            target: Targets,
28491
            hreflang: null
28492
        }
28493
    },
28494
    abbr: S,
28495
    address: S,
28496
    area: {
28497
        attrs: {
28498
            alt: null, coords: null, href: null, target: null, ping: null,
28499
            media: null, hreflang: null, type: null,
28500
            shape: ["default", "rect", "circle", "poly"]
28501
        }
28502
    },
28503
    article: S,
28504
    aside: S,
28505
    audio: {
28506
        attrs: {
28507
            src: null, mediagroup: null,
28508
            crossorigin: ["anonymous", "use-credentials"],
28509
            preload: ["none", "metadata", "auto"],
28510
            autoplay: ["autoplay"],
28511
            loop: ["loop"],
28512
            controls: ["controls"]
28513
        }
28514
    },
28515
    b: S,
28516
    base: { attrs: { href: null, target: Targets } },
28517
    bdi: S,
28518
    bdo: S,
28519
    blockquote: { attrs: { cite: null } },
28520
    body: S,
28521
    br: S,
28522
    button: {
28523
        attrs: {
28524
            form: null, formaction: null, name: null, value: null,
28525
            autofocus: ["autofocus"],
28526
            disabled: ["autofocus"],
28527
            formenctype: Encs,
28528
            formmethod: Methods,
28529
            formnovalidate: ["novalidate"],
28530
            formtarget: Targets,
28531
            type: ["submit", "reset", "button"]
28532
        }
28533
    },
28534
    canvas: { attrs: { width: null, height: null } },
28535
    caption: S,
28536
    center: S,
28537
    cite: S,
28538
    code: S,
28539
    col: { attrs: { span: null } },
28540
    colgroup: { attrs: { span: null } },
28541
    command: {
28542
        attrs: {
28543
            type: ["command", "checkbox", "radio"],
28544
            label: null, icon: null, radiogroup: null, command: null, title: null,
28545
            disabled: ["disabled"],
28546
            checked: ["checked"]
28547
        }
28548
    },
28549
    data: { attrs: { value: null } },
28550
    datagrid: { attrs: { disabled: ["disabled"], multiple: ["multiple"] } },
28551
    datalist: { attrs: { data: null } },
28552
    dd: S,
28553
    del: { attrs: { cite: null, datetime: null } },
28554
    details: { attrs: { open: ["open"] } },
28555
    dfn: S,
28556
    div: S,
28557
    dl: S,
28558
    dt: S,
28559
    em: S,
28560
    embed: { attrs: { src: null, type: null, width: null, height: null } },
28561
    eventsource: { attrs: { src: null } },
28562
    fieldset: { attrs: { disabled: ["disabled"], form: null, name: null } },
28563
    figcaption: S,
28564
    figure: S,
28565
    footer: S,
28566
    form: {
28567
        attrs: {
28568
            action: null, name: null,
28569
            "accept-charset": Charsets,
28570
            autocomplete: ["on", "off"],
28571
            enctype: Encs,
28572
            method: Methods,
28573
            novalidate: ["novalidate"],
28574
            target: Targets
28575
        }
28576
    },
28577
    h1: S, h2: S, h3: S, h4: S, h5: S, h6: S,
28578
    head: {
28579
        children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
28580
    },
28581
    header: S,
28582
    hgroup: S,
28583
    hr: S,
28584
    html: {
28585
        attrs: { manifest: null }
28586
    },
28587
    i: S,
28588
    iframe: {
28589
        attrs: {
28590
            src: null, srcdoc: null, name: null, width: null, height: null,
28591
            sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
28592
            seamless: ["seamless"]
28593
        }
28594
    },
28595
    img: {
28596
        attrs: {
28597
            alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
28598
            crossorigin: ["anonymous", "use-credentials"]
28599
        }
28600
    },
28601
    input: {
28602
        attrs: {
28603
            alt: null, dirname: null, form: null, formaction: null,
28604
            height: null, list: null, max: null, maxlength: null, min: null,
28605
            name: null, pattern: null, placeholder: null, size: null, src: null,
28606
            step: null, value: null, width: null,
28607
            accept: ["audio/*", "video/*", "image/*"],
28608
            autocomplete: ["on", "off"],
28609
            autofocus: ["autofocus"],
28610
            checked: ["checked"],
28611
            disabled: ["disabled"],
28612
            formenctype: Encs,
28613
            formmethod: Methods,
28614
            formnovalidate: ["novalidate"],
28615
            formtarget: Targets,
28616
            multiple: ["multiple"],
28617
            readonly: ["readonly"],
28618
            required: ["required"],
28619
            type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
28620
                "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
28621
                "file", "submit", "image", "reset", "button"]
28622
        }
28623
    },
28624
    ins: { attrs: { cite: null, datetime: null } },
28625
    kbd: S,
28626
    keygen: {
28627
        attrs: {
28628
            challenge: null, form: null, name: null,
28629
            autofocus: ["autofocus"],
28630
            disabled: ["disabled"],
28631
            keytype: ["RSA"]
28632
        }
28633
    },
28634
    label: { attrs: { for: null, form: null } },
28635
    legend: S,
28636
    li: { attrs: { value: null } },
28637
    link: {
28638
        attrs: {
28639
            href: null, type: null,
28640
            hreflang: null,
28641
            media: null,
28642
            sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
28643
        }
28644
    },
28645
    map: { attrs: { name: null } },
28646
    mark: S,
28647
    menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
28648
    meta: {
28649
        attrs: {
28650
            content: null,
28651
            charset: Charsets,
28652
            name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
28653
            "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
28654
        }
28655
    },
28656
    meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
28657
    nav: S,
28658
    noscript: S,
28659
    object: {
28660
        attrs: {
28661
            data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
28662
            typemustmatch: ["typemustmatch"]
28663
        }
28664
    },
28665
    ol: { attrs: { reversed: ["reversed"], start: null, type: ["1", "a", "A", "i", "I"] },
28666
        children: ["li", "script", "template", "ul", "ol"] },
28667
    optgroup: { attrs: { disabled: ["disabled"], label: null } },
28668
    option: { attrs: { disabled: ["disabled"], label: null, selected: ["selected"], value: null } },
28669
    output: { attrs: { for: null, form: null, name: null } },
28670
    p: S,
28671
    param: { attrs: { name: null, value: null } },
28672
    pre: S,
28673
    progress: { attrs: { value: null, max: null } },
28674
    q: { attrs: { cite: null } },
28675
    rp: S,
28676
    rt: S,
28677
    ruby: S,
28678
    samp: S,
28679
    script: {
28680
        attrs: {
28681
            type: ["text/javascript"],
28682
            src: null,
28683
            async: ["async"],
28684
            defer: ["defer"],
28685
            charset: Charsets
28686
        }
28687
    },
28688
    section: S,
28689
    select: {
28690
        attrs: {
28691
            form: null, name: null, size: null,
28692
            autofocus: ["autofocus"],
28693
            disabled: ["disabled"],
28694
            multiple: ["multiple"]
28695
        }
28696
    },
28697
    slot: { attrs: { name: null } },
28698
    small: S,
28699
    source: { attrs: { src: null, type: null, media: null } },
28700
    span: S,
28701
    strong: S,
28702
    style: {
28703
        attrs: {
28704
            type: ["text/css"],
28705
            media: null,
28706
            scoped: null
28707
        }
28708
    },
28709
    sub: S,
28710
    summary: S,
28711
    sup: S,
28712
    table: S,
28713
    tbody: S,
28714
    td: { attrs: { colspan: null, rowspan: null, headers: null } },
28715
    template: S,
28716
    textarea: {
28717
        attrs: {
28718
            dirname: null, form: null, maxlength: null, name: null, placeholder: null,
28719
            rows: null, cols: null,
28720
            autofocus: ["autofocus"],
28721
            disabled: ["disabled"],
28722
            readonly: ["readonly"],
28723
            required: ["required"],
28724
            wrap: ["soft", "hard"]
28725
        }
28726
    },
28727
    tfoot: S,
28728
    th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
28729
    thead: S,
28730
    time: { attrs: { datetime: null } },
28731
    title: S,
28732
    tr: S,
28733
    track: {
28734
        attrs: {
28735
            src: null, label: null, default: null,
28736
            kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
28737
            srclang: null
28738
        }
28739
    },
28740
    ul: { children: ["li", "script", "template", "ul", "ol"] },
28741
    var: S,
28742
    video: {
28743
        attrs: {
28744
            src: null, poster: null, width: null, height: null,
28745
            crossorigin: ["anonymous", "use-credentials"],
28746
            preload: ["auto", "metadata", "none"],
28747
            autoplay: ["autoplay"],
28748
            mediagroup: ["movie"],
28749
            muted: ["muted"],
28750
            controls: ["controls"]
28751
        }
28752
    },
28753
    wbr: S
28754
};
28755
const GlobalAttrs = {
28756
    accesskey: null,
28757
    class: null,
28758
    contenteditable: Bool,
28759
    contextmenu: null,
28760
    dir: ["ltr", "rtl", "auto"],
28761
    draggable: ["true", "false", "auto"],
28762
    dropzone: ["copy", "move", "link", "string:", "file:"],
28763
    hidden: ["hidden"],
28764
    id: null,
28765
    inert: ["inert"],
28766
    itemid: null,
28767
    itemprop: null,
28768
    itemref: null,
28769
    itemscope: ["itemscope"],
28770
    itemtype: null,
28771
    lang: ["ar", "bn", "de", "en-GB", "en-US", "es", "fr", "hi", "id", "ja", "pa", "pt", "ru", "tr", "zh"],
28772
    spellcheck: Bool,
28773
    autocorrect: Bool,
28774
    autocapitalize: Bool,
28775
    style: null,
28776
    tabindex: null,
28777
    title: null,
28778
    translate: ["yes", "no"],
28779
    rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"],
28780
    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(" "),
28781
    "aria-activedescendant": null,
28782
    "aria-atomic": Bool,
28783
    "aria-autocomplete": ["inline", "list", "both", "none"],
28784
    "aria-busy": Bool,
28785
    "aria-checked": ["true", "false", "mixed", "undefined"],
28786
    "aria-controls": null,
28787
    "aria-describedby": null,
28788
    "aria-disabled": Bool,
28789
    "aria-dropeffect": null,
28790
    "aria-expanded": ["true", "false", "undefined"],
28791
    "aria-flowto": null,
28792
    "aria-grabbed": ["true", "false", "undefined"],
28793
    "aria-haspopup": Bool,
28794
    "aria-hidden": Bool,
28795
    "aria-invalid": ["true", "false", "grammar", "spelling"],
28796
    "aria-label": null,
28797
    "aria-labelledby": null,
28798
    "aria-level": null,
28799
    "aria-live": ["off", "polite", "assertive"],
28800
    "aria-multiline": Bool,
28801
    "aria-multiselectable": Bool,
28802
    "aria-owns": null,
28803
    "aria-posinset": null,
28804
    "aria-pressed": ["true", "false", "mixed", "undefined"],
28805
    "aria-readonly": Bool,
28806
    "aria-relevant": null,
28807
    "aria-required": Bool,
28808
    "aria-selected": ["true", "false", "undefined"],
28809
    "aria-setsize": null,
28810
    "aria-sort": ["ascending", "descending", "none", "other"],
28811
    "aria-valuemax": null,
28812
    "aria-valuemin": null,
28813
    "aria-valuenow": null,
28814
    "aria-valuetext": null
28815
};
28816
const eventAttributes = /*@__PURE__*/("beforeunload copy cut dragstart dragover dragleave dragenter dragend " +
28817
    "drag paste focus blur change click load mousedown mouseenter mouseleave " +
28818
    "mouseup keydown keyup resize scroll unload").split(" ").map(n => "on" + n);
28819
for (let a of eventAttributes)
28820
    GlobalAttrs[a] = null;
28821
class Schema {
28822
    constructor(extraTags, extraAttrs) {
28823
        this.tags = Object.assign(Object.assign({}, Tags), extraTags);
28824
        this.globalAttrs = Object.assign(Object.assign({}, GlobalAttrs), extraAttrs);
28825
        this.allTags = Object.keys(this.tags);
28826
        this.globalAttrNames = Object.keys(this.globalAttrs);
28827
    }
28828
}
28829
Schema.default = /*@__PURE__*/new Schema;
28830
function elementName$2(doc, tree, max = doc.length) {
28831
    if (!tree)
28832
        return "";
28833
    let tag = tree.firstChild;
28834
    let name = tag && tag.getChild("TagName");
28835
    return name ? doc.sliceString(name.from, Math.min(name.to, max)) : "";
28836
}
28837
function findParentElement$1(tree, skip = false) {
28838
    for (; tree; tree = tree.parent)
28839
        if (tree.name == "Element") {
28840
            if (skip)
28841
                skip = false;
28842
            else
28843
                return tree;
28844
        }
28845
    return null;
28846
}
28847
function allowedChildren(doc, tree, schema) {
28848
    let parentInfo = schema.tags[elementName$2(doc, findParentElement$1(tree))];
28849
    return (parentInfo === null || parentInfo === void 0 ? void 0 : parentInfo.children) || schema.allTags;
28850
}
28851
function openTags(doc, tree) {
28852
    let open = [];
28853
    for (let parent = findParentElement$1(tree); parent && !parent.type.isTop; parent = findParentElement$1(parent.parent)) {
28854
        let tagName = elementName$2(doc, parent);
28855
        if (tagName && parent.lastChild.name == "CloseTag")
28856
            break;
28857
        if (tagName && open.indexOf(tagName) < 0 && (tree.name == "EndTag" || tree.from >= parent.firstChild.to))
28858
            open.push(tagName);
28859
    }
28860
    return open;
28861
}
28862
const identifier = /^[:\-\.\w\u00b7-\uffff]*$/;
28863
function completeTag(state, schema, tree, from, to) {
28864
    let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
28865
    let parent = findParentElement$1(tree, true);
28866
    return { from, to,
28867
        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,
28868
            type: "type", boost: 99 - i }))),
28869
        validFor: /^\/?[:\-\.\w\u00b7-\uffff]*$/ };
28870
}
28871
function completeCloseTag(state, tree, from, to) {
28872
    let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
28873
    return { from, to,
28874
        options: openTags(state.doc, tree).map((tag, i) => ({ label: tag, apply: tag + end, type: "type", boost: 99 - i })),
28875
        validFor: identifier };
28876
}
28877
function completeStartTag(state, schema, tree, pos) {
28878
    let options = [], level = 0;
28879
    for (let tagName of allowedChildren(state.doc, tree, schema))
28880
        options.push({ label: "<" + tagName, type: "type" });
28881
    for (let open of openTags(state.doc, tree))
28882
        options.push({ label: "</" + open + ">", type: "type", boost: 99 - level++ });
28883
    return { from: pos, to: pos, options, validFor: /^<\/?[:\-\.\w\u00b7-\uffff]*$/ };
28884
}
28885
function completeAttrName(state, schema, tree, from, to) {
28886
    let elt = findParentElement$1(tree), info = elt ? schema.tags[elementName$2(state.doc, elt)] : null;
28887
    let localAttrs = info && info.attrs ? Object.keys(info.attrs) : [];
28888
    let names = info && info.globalAttrs === false ? localAttrs
28889
        : localAttrs.length ? localAttrs.concat(schema.globalAttrNames) : schema.globalAttrNames;
28890
    return { from, to,
28891
        options: names.map(attrName => ({ label: attrName, type: "property" })),
28892
        validFor: identifier };
28893
}
28894
function completeAttrValue(state, schema, tree, from, to) {
28895
    var _a;
28896
    let nameNode = (_a = tree.parent) === null || _a === void 0 ? void 0 : _a.getChild("AttributeName");
28897
    let options = [], token = undefined;
28898
    if (nameNode) {
28899
        let attrName = state.sliceDoc(nameNode.from, nameNode.to);
28900
        let attrs = schema.globalAttrs[attrName];
28901
        if (!attrs) {
28902
            let elt = findParentElement$1(tree), info = elt ? schema.tags[elementName$2(state.doc, elt)] : null;
28903
            attrs = (info === null || info === void 0 ? void 0 : info.attrs) && info.attrs[attrName];
28904
        }
28905
        if (attrs) {
28906
            let base = state.sliceDoc(from, to).toLowerCase(), quoteStart = '"', quoteEnd = '"';
28907
            if (/^['"]/.test(base)) {
28908
                token = base[0] == '"' ? /^[^"]*$/ : /^[^']*$/;
28909
                quoteStart = "";
28910
                quoteEnd = state.sliceDoc(to, to + 1) == base[0] ? "" : base[0];
28911
                base = base.slice(1);
28912
                from++;
28913
            }
28914
            else {
28915
                token = /^[^\s<>='"]*$/;
28916
            }
28917
            for (let value of attrs)
28918
                options.push({ label: value, apply: quoteStart + value + quoteEnd, type: "constant" });
28919
        }
28920
    }
28921
    return { from, to, options, validFor: token };
28922
}
28923
function htmlCompletionFor(schema, context) {
28924
    let { state, pos } = context, tree = syntaxTree(state).resolveInner(pos, -1), around = tree.resolve(pos);
28925
    for (let scan = pos, before; around == tree && (before = tree.childBefore(scan));) {
28926
        let last = before.lastChild;
28927
        if (!last || !last.type.isError || last.from < last.to)
28928
            break;
28929
        around = tree = before;
28930
        scan = last.from;
28931
    }
28932
    if (tree.name == "TagName") {
28933
        return tree.parent && /CloseTag$/.test(tree.parent.name) ? completeCloseTag(state, tree, tree.from, pos)
28934
            : completeTag(state, schema, tree, tree.from, pos);
28935
    }
28936
    else if (tree.name == "StartTag") {
28937
        return completeTag(state, schema, tree, pos, pos);
28938
    }
28939
    else if (tree.name == "StartCloseTag" || tree.name == "IncompleteCloseTag") {
28940
        return completeCloseTag(state, tree, pos, pos);
28941
    }
28942
    else if (tree.name == "OpenTag" || tree.name == "SelfClosingTag" || tree.name == "AttributeName") {
28943
        return completeAttrName(state, schema, tree, tree.name == "AttributeName" ? tree.from : pos, pos);
28944
    }
28945
    else if (tree.name == "Is" || tree.name == "AttributeValue" || tree.name == "UnquotedAttributeValue") {
28946
        return completeAttrValue(state, schema, tree, tree.name == "Is" ? pos : tree.from, pos);
28947
    }
28948
    else if (context.explicit && (around.name == "Element" || around.name == "Text" || around.name == "Document")) {
28949
        return completeStartTag(state, schema, tree, pos);
28950
    }
28951
    else {
28952
        return null;
28953
    }
28954
}
28955
/**
28956
Create a completion source for HTML extended with additional tags
28957
or attributes.
28958
*/
28959
function htmlCompletionSourceWith(config) {
28960
    let { extraTags, extraGlobalAttributes: extraAttrs } = config;
28961
    let schema = extraAttrs || extraTags ? new Schema(extraTags, extraAttrs) : Schema.default;
28962
    return (context) => htmlCompletionFor(schema, context);
28963
}
28964
 
28965
const jsonParser = /*@__PURE__*/javascriptLanguage.parser.configure({ top: "SingleExpression" });
28966
const defaultNesting = [
28967
    { tag: "script",
28968
        attrs: attrs => attrs.type == "text/typescript" || attrs.lang == "ts",
28969
        parser: typescriptLanguage.parser },
28970
    { tag: "script",
28971
        attrs: attrs => attrs.type == "text/babel" || attrs.type == "text/jsx",
28972
        parser: jsxLanguage.parser },
28973
    { tag: "script",
28974
        attrs: attrs => attrs.type == "text/typescript-jsx",
28975
        parser: tsxLanguage.parser },
28976
    { tag: "script",
28977
        attrs(attrs) {
28978
            return /^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(attrs.type);
28979
        },
28980
        parser: jsonParser },
28981
    { tag: "script",
28982
        attrs(attrs) {
28983
            return !attrs.type || /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(attrs.type);
28984
        },
28985
        parser: javascriptLanguage.parser },
28986
    { tag: "style",
28987
        attrs(attrs) {
28988
            return (!attrs.lang || attrs.lang == "css") && (!attrs.type || /^(text\/)?(x-)?(stylesheet|css)$/i.test(attrs.type));
28989
        },
28990
        parser: cssLanguage.parser }
28991
];
28992
const defaultAttrs = /*@__PURE__*/[
28993
    { name: "style",
28994
        parser: /*@__PURE__*/cssLanguage.parser.configure({ top: "Styles" }) }
28995
].concat(/*@__PURE__*/eventAttributes.map(name => ({ name, parser: javascriptLanguage.parser })));
28996
/**
28997
A language provider based on the [Lezer HTML
28998
parser](https://github.com/lezer-parser/html), extended with the
28999
JavaScript and CSS parsers to parse the content of `<script>` and
29000
`<style>` tags.
29001
*/
29002
const htmlPlain = /*@__PURE__*/LRLanguage.define({
29003
    name: "html",
29004
    parser: /*@__PURE__*/parser$3.configure({
29005
        props: [
29006
            /*@__PURE__*/indentNodeProp.add({
29007
                Element(context) {
29008
                    let after = /^(\s*)(<\/)?/.exec(context.textAfter);
29009
                    if (context.node.to <= context.pos + after[0].length)
29010
                        return context.continue();
29011
                    return context.lineIndent(context.node.from) + (after[2] ? 0 : context.unit);
29012
                },
29013
                "OpenTag CloseTag SelfClosingTag"(context) {
29014
                    return context.column(context.node.from) + context.unit;
29015
                },
29016
                Document(context) {
29017
                    if (context.pos + /\s*/.exec(context.textAfter)[0].length < context.node.to)
29018
                        return context.continue();
29019
                    let endElt = null, close;
29020
                    for (let cur = context.node;;) {
29021
                        let last = cur.lastChild;
29022
                        if (!last || last.name != "Element" || last.to != cur.to)
29023
                            break;
29024
                        endElt = cur = last;
29025
                    }
29026
                    if (endElt && !((close = endElt.lastChild) && (close.name == "CloseTag" || close.name == "SelfClosingTag")))
29027
                        return context.lineIndent(endElt.from) + context.unit;
29028
                    return null;
29029
                }
29030
            }),
29031
            /*@__PURE__*/foldNodeProp.add({
29032
                Element(node) {
29033
                    let first = node.firstChild, last = node.lastChild;
29034
                    if (!first || first.name != "OpenTag")
29035
                        return null;
29036
                    return { from: first.to, to: last.name == "CloseTag" ? last.from : node.to };
29037
                }
29038
            }),
29039
            /*@__PURE__*/bracketMatchingHandle.add({
29040
                "OpenTag CloseTag": node => node.getChild("TagName")
29041
            })
29042
        ]
29043
    }),
29044
    languageData: {
29045
        commentTokens: { block: { open: "<!--", close: "-->" } },
29046
        indentOnInput: /^\s*<\/\w+\W$/,
29047
        wordChars: "-._"
29048
    }
29049
});
29050
/**
29051
A language provider based on the [Lezer HTML
29052
parser](https://github.com/lezer-parser/html), extended with the
29053
JavaScript and CSS parsers to parse the content of `<script>` and
29054
`<style>` tags.
29055
*/
29056
const htmlLanguage = /*@__PURE__*/htmlPlain.configure({
29057
    wrap: /*@__PURE__*/configureNesting(defaultNesting, defaultAttrs)
29058
});
29059
/**
29060
Language support for HTML, including
29061
[`htmlCompletion`](https://codemirror.net/6/docs/ref/#lang-html.htmlCompletion) and JavaScript and
29062
CSS support extensions.
29063
*/
29064
function html(config = {}) {
29065
    let dialect = "", wrap;
29066
    if (config.matchClosingTags === false)
29067
        dialect = "noMatch";
29068
    if (config.selfClosingTags === true)
29069
        dialect = (dialect ? dialect + " " : "") + "selfClosing";
29070
    if (config.nestedLanguages && config.nestedLanguages.length ||
29071
        config.nestedAttributes && config.nestedAttributes.length)
29072
        wrap = configureNesting((config.nestedLanguages || []).concat(defaultNesting), (config.nestedAttributes || []).concat(defaultAttrs));
29073
    let lang = wrap ? htmlPlain.configure({ wrap, dialect }) : dialect ? htmlLanguage.configure({ dialect }) : htmlLanguage;
29074
    return new LanguageSupport(lang, [
29075
        htmlLanguage.data.of({ autocomplete: htmlCompletionSourceWith(config) }),
29076
        config.autoCloseTags !== false ? autoCloseTags$1 : [],
29077
        javascript().support,
29078
        css().support
29079
    ]);
29080
}
29081
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(" "));
29082
/**
29083
Extension that will automatically insert close tags when a `>` or
29084
`/` is typed.
29085
*/
29086
const autoCloseTags$1 = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, insertTransaction) => {
29087
    if (view.composing || view.state.readOnly || from != to || (text != ">" && text != "/") ||
29088
        !htmlLanguage.isActiveAt(view.state, from, -1))
29089
        return false;
29090
    let base = insertTransaction(), { state } = base;
29091
    let closeTags = state.changeByRange(range => {
29092
        var _a, _b, _c;
29093
        let didType = state.doc.sliceString(range.from - 1, range.to) == text;
1441 ariadna 29094
        let { head } = range, after = syntaxTree(state).resolveInner(head, -1), name;
29095
        if (didType && text == ">" && after.name == "EndTag") {
29096
            let tag = after.parent;
29097
            if (((_b = (_a = tag.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "CloseTag" &&
29098
                (name = elementName$2(state.doc, tag.parent, head)) &&
1 efrain 29099
                !selfClosers.has(name)) {
29100
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
29101
                let insert = `</${name}>`;
29102
                return { range, changes: { from: head, to, insert } };
29103
            }
29104
        }
1441 ariadna 29105
        else if (didType && text == "/" && after.name == "IncompleteCloseTag") {
29106
            let tag = after.parent;
29107
            if (after.from == head - 2 && ((_c = tag.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "CloseTag" &&
29108
                (name = elementName$2(state.doc, tag, head)) && !selfClosers.has(name)) {
1 efrain 29109
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
29110
                let insert = `${name}>`;
29111
                return {
29112
                    range: EditorSelection.cursor(head + insert.length, -1),
29113
                    changes: { from: head, to, insert }
29114
                };
29115
            }
29116
        }
29117
        return { range };
29118
    });
29119
    if (closeTags.changes.empty)
29120
        return false;
29121
    view.dispatch([
29122
        base,
29123
        state.update(closeTags, {
29124
            userEvent: "input.complete",
29125
            scrollIntoView: true
29126
        })
29127
    ]);
29128
    return true;
29129
});
29130
 
29131
// This file was generated by lezer-generator. You probably shouldn't edit it.
29132
const StartTag = 1,
29133
  StartCloseTag = 2,
29134
  MissingCloseTag = 3,
29135
  mismatchedStartCloseTag = 4,
29136
  incompleteStartCloseTag = 5,
1441 ariadna 29137
  commentContent$1 = 36,
29138
  piContent$1 = 37,
29139
  cdataContent$1 = 38,
1 efrain 29140
  Element$1 = 11,
29141
  OpenTag = 13;
29142
 
29143
/* Hand-written tokenizer for XML tag matching. */
29144
 
29145
function nameChar(ch) {
29146
  return ch == 45 || ch == 46 || ch == 58 || ch >= 65 && ch <= 90 || ch == 95 || ch >= 97 && ch <= 122 || ch >= 161
29147
}
29148
 
29149
function isSpace(ch) {
29150
  return ch == 9 || ch == 10 || ch == 13 || ch == 32
29151
}
29152
 
29153
let cachedName = null, cachedInput = null, cachedPos = 0;
29154
function tagNameAfter(input, offset) {
29155
  let pos = input.pos + offset;
29156
  if (cachedInput == input && cachedPos == pos) return cachedName
29157
  while (isSpace(input.peek(offset))) offset++;
29158
  let name = "";
29159
  for (;;) {
29160
    let next = input.peek(offset);
29161
    if (!nameChar(next)) break
29162
    name += String.fromCharCode(next);
29163
    offset++;
29164
  }
29165
  cachedInput = input; cachedPos = pos;
29166
  return cachedName = name || null
29167
}
29168
 
29169
function ElementContext(name, parent) {
29170
  this.name = name;
29171
  this.parent = parent;
29172
}
29173
 
29174
const elementContext = new ContextTracker({
29175
  start: null,
29176
  shift(context, term, stack, input) {
29177
    return term == StartTag ? new ElementContext(tagNameAfter(input, 1) || "", context) : context
29178
  },
29179
  reduce(context, term) {
29180
    return term == Element$1 && context ? context.parent : context
29181
  },
29182
  reuse(context, node, _stack, input) {
29183
    let type = node.type.id;
29184
    return type == StartTag || type == OpenTag
29185
      ? new ElementContext(tagNameAfter(input, 1) || "", context) : context
29186
  },
29187
  strict: false
29188
});
29189
 
29190
const startTag = new ExternalTokenizer((input, stack) => {
29191
  if (input.next != 60 /* '<' */) return
29192
  input.advance();
29193
  if (input.next == 47 /* '/' */) {
29194
    input.advance();
29195
    let name = tagNameAfter(input, 0);
29196
    if (!name) return input.acceptToken(incompleteStartCloseTag)
29197
    if (stack.context && name == stack.context.name) return input.acceptToken(StartCloseTag)
29198
    for (let cx = stack.context; cx; cx = cx.parent) if (cx.name == name) return input.acceptToken(MissingCloseTag, -2)
29199
    input.acceptToken(mismatchedStartCloseTag);
29200
  } else if (input.next != 33 /* '!' */ && input.next != 63 /* '?' */) {
29201
    return input.acceptToken(StartTag)
29202
  }
29203
}, {contextual: true});
29204
 
29205
function scanTo(type, end) {
29206
  return new ExternalTokenizer(input => {
29207
    let len = 0, first = end.charCodeAt(0);
29208
    scan: for (;; input.advance(), len++) {
29209
      if (input.next < 0) break
29210
      if (input.next == first) {
29211
        for (let i = 1; i < end.length; i++)
29212
          if (input.peek(i) != end.charCodeAt(i)) continue scan
29213
        break
29214
      }
29215
    }
29216
    if (len) input.acceptToken(type);
29217
  })
29218
}
29219
 
29220
const commentContent = scanTo(commentContent$1, "-->");
29221
const piContent = scanTo(piContent$1, "?>");
29222
const cdataContent = scanTo(cdataContent$1, "]]>");
29223
 
29224
const xmlHighlighting = styleTags({
29225
  Text: tags$1.content,
29226
  "StartTag StartCloseTag EndTag SelfCloseEndTag": tags$1.angleBracket,
29227
  TagName: tags$1.tagName,
29228
  "MismatchedCloseTag/TagName": [tags$1.tagName, tags$1.invalid],
29229
  AttributeName: tags$1.attributeName,
29230
  AttributeValue: tags$1.attributeValue,
29231
  Is: tags$1.definitionOperator,
29232
  "EntityReference CharacterReference": tags$1.character,
29233
  Comment: tags$1.blockComment,
29234
  ProcessingInst: tags$1.processingInstruction,
29235
  DoctypeDecl: tags$1.documentMeta,
29236
  Cdata: tags$1.special(tags$1.string)
29237
});
29238
 
29239
// This file was generated by lezer-generator. You probably shouldn't edit it.
29240
const parser = LRParser.deserialize({
29241
  version: 14,
1441 ariadna 29242
  states: ",lOQOaOOOrOxO'#CfOzOpO'#CiO!tOaO'#CgOOOP'#Cg'#CgO!{OrO'#CrO#TOtO'#CsO#]OpO'#CtOOOP'#DT'#DTOOOP'#Cv'#CvQQOaOOOOOW'#Cw'#C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~P!SO^{Oz^O~OteO!P}O~OuhO!R!PO~O^!QOz^O~O[!SOz^O~O[!VO`sOd!WOz^O~Oa!YOz^O~Oz^O[mX`mXdmX~O[!VO`sOd!WO~O^!]Oz^O~O[!_Oz^O~O[!aOz^O~O[!cO`sOd!dOz^O~O[!cO`sOd!dO~Oa!eOz^O~Oz^O{!gO}!hO~Oz^O[ma`madma~O[!kOz^O~O[!lOz^O~O[!mO`sOd!nO~OW!qOX!qO{!sO|!qO~OW!tOX!tO}!sO!O!tO~O[!vOz^O~OW!qOX!qO{!yO|!qO~OW!tOX!tO}!yO!O!tO~O",
29244
  goto: "%cxPPPPPPPPPPyyP!PP!VPP!`!jP!pyyyP!v!|#S$[$k$q$w$}%TPPPP%ZXWORYbXRORYb_t`qru!T!U!bQ!i!YS!p!e!fR!w!oQdRRybXSORYbQYORmYQ[PRn[Q_QQkVjp_krz!R!T!X!Z!^!`!f!j!oQr`QzcQ!RlQ!TqQ!XsQ!ZtQ!^{Q!`!QQ!f!YQ!j!]R!o!eQu`S!UqrU![u!U!bR!b!TQ!r!gR!x!rQ!u!hR!z!uQbRRxbQfTR|fQiUR!OiSXOYTaRb",
1 efrain 29245
  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",
1441 ariadna 29246
  maxTerm: 50,
1 efrain 29247
  context: elementContext,
29248
  nodeProps: [
29249
    ["closedBy", 1,"SelfCloseEndTag EndTag",13,"CloseTag MissingCloseTag"],
29250
    ["openedBy", 12,"StartTag StartCloseTag",19,"OpenTag",20,"StartTag"],
29251
    ["isolate", -6,13,18,19,21,22,24,""]
29252
  ],
29253
  propSources: [xmlHighlighting],
29254
  skippedNodes: [0],
1441 ariadna 29255
  repeatNodeCount: 9,
29256
  tokenData: "!)v~R!YOX$qXY)iYZ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'S;=`)c<%lO$qk!&kX!RQVP|W!O`Or$qrs%gsv$qwx'^x!^$q!^!_(o!_;'S$q;'S;=`)c<%lO$qk!'aZVP|W!O`Or$qrs%gsv$qwx'^x!^$q!^!_(o!_#P$q#P#Q!(S#Q;'S$q;'S;=`)c<%lO$qk!(]ZVP|W!O`Or$qrs%gsv$qwx'^x!^$q!^!_(o!_!`$q!`!a!)O!a;'S$q;'S;=`)c<%lO$qk!)ZXxQVP|W!O`Or$qrs%gsv$qwx'^x!^$q!^!_(o!_;'S$q;'S;=`)c<%lO$q",
29257
  tokenizers: [startTag, commentContent, piContent, cdataContent, 0, 1, 2, 3, 4],
1 efrain 29258
  topRules: {"Document":[0,6]},
29259
  tokenPrec: 0
29260
});
29261
 
29262
function tagName(doc, tag) {
29263
    let name = tag && tag.getChild("TagName");
29264
    return name ? doc.sliceString(name.from, name.to) : "";
29265
}
29266
function elementName$1(doc, tree) {
29267
    let tag = tree && tree.firstChild;
29268
    return !tag || tag.name != "OpenTag" ? "" : tagName(doc, tag);
29269
}
29270
function attrName(doc, tag, pos) {
29271
    let attr = tag && tag.getChildren("Attribute").find(a => a.from <= pos && a.to >= pos);
29272
    let name = attr && attr.getChild("AttributeName");
29273
    return name ? doc.sliceString(name.from, name.to) : "";
29274
}
29275
function findParentElement(tree) {
29276
    for (let cur = tree && tree.parent; cur; cur = cur.parent)
29277
        if (cur.name == "Element")
29278
            return cur;
29279
    return null;
29280
}
29281
function findLocation(state, pos) {
29282
    var _a;
29283
    let at = syntaxTree(state).resolveInner(pos, -1), inTag = null;
29284
    for (let cur = at; !inTag && cur.parent; cur = cur.parent)
29285
        if (cur.name == "OpenTag" || cur.name == "CloseTag" || cur.name == "SelfClosingTag" || cur.name == "MismatchedCloseTag")
29286
            inTag = cur;
29287
    if (inTag && (inTag.to > pos || inTag.lastChild.type.isError)) {
29288
        let elt = inTag.parent;
29289
        if (at.name == "TagName")
29290
            return inTag.name == "CloseTag" || inTag.name == "MismatchedCloseTag"
29291
                ? { type: "closeTag", from: at.from, context: elt }
29292
                : { type: "openTag", from: at.from, context: findParentElement(elt) };
29293
        if (at.name == "AttributeName")
29294
            return { type: "attrName", from: at.from, context: inTag };
29295
        if (at.name == "AttributeValue")
29296
            return { type: "attrValue", from: at.from, context: inTag };
29297
        let before = at == inTag || at.name == "Attribute" ? at.childBefore(pos) : at;
29298
        if ((before === null || before === void 0 ? void 0 : before.name) == "StartTag")
29299
            return { type: "openTag", from: pos, context: findParentElement(elt) };
29300
        if ((before === null || before === void 0 ? void 0 : before.name) == "StartCloseTag" && before.to <= pos)
29301
            return { type: "closeTag", from: pos, context: elt };
29302
        if ((before === null || before === void 0 ? void 0 : before.name) == "Is")
29303
            return { type: "attrValue", from: pos, context: inTag };
29304
        if (before)
29305
            return { type: "attrName", from: pos, context: inTag };
29306
        return null;
29307
    }
29308
    else if (at.name == "StartCloseTag") {
29309
        return { type: "closeTag", from: pos, context: at.parent };
29310
    }
29311
    while (at.parent && at.to == pos && !((_a = at.lastChild) === null || _a === void 0 ? void 0 : _a.type.isError))
29312
        at = at.parent;
29313
    if (at.name == "Element" || at.name == "Text" || at.name == "Document")
29314
        return { type: "tag", from: pos, context: at.name == "Element" ? at : findParentElement(at) };
29315
    return null;
29316
}
29317
class Element {
29318
    constructor(spec, attrs, attrValues) {
29319
        this.attrs = attrs;
29320
        this.attrValues = attrValues;
29321
        this.children = [];
29322
        this.name = spec.name;
29323
        this.completion = Object.assign(Object.assign({ type: "type" }, spec.completion || {}), { label: this.name });
29324
        this.openCompletion = Object.assign(Object.assign({}, this.completion), { label: "<" + this.name });
29325
        this.closeCompletion = Object.assign(Object.assign({}, this.completion), { label: "</" + this.name + ">", boost: 2 });
29326
        this.closeNameCompletion = Object.assign(Object.assign({}, this.completion), { label: this.name + ">" });
29327
        this.text = spec.textContent ? spec.textContent.map(s => ({ label: s, type: "text" })) : [];
29328
    }
29329
}
29330
const Identifier = /^[:\-\.\w\u00b7-\uffff]*$/;
29331
function attrCompletion(spec) {
29332
    return Object.assign(Object.assign({ type: "property" }, spec.completion || {}), { label: spec.name });
29333
}
29334
function valueCompletion(spec) {
29335
    return typeof spec == "string" ? { label: `"${spec}"`, type: "constant" }
29336
        : /^"/.test(spec.label) ? spec
29337
            : Object.assign(Object.assign({}, spec), { label: `"${spec.label}"` });
29338
}
29339
/**
29340
Create a completion source for the given schema.
29341
*/
29342
function completeFromSchema(eltSpecs, attrSpecs) {
29343
    let allAttrs = [], globalAttrs = [];
29344
    let attrValues = Object.create(null);
29345
    for (let s of attrSpecs) {
29346
        let completion = attrCompletion(s);
29347
        allAttrs.push(completion);
29348
        if (s.global)
29349
            globalAttrs.push(completion);
29350
        if (s.values)
29351
            attrValues[s.name] = s.values.map(valueCompletion);
29352
    }
29353
    let allElements = [], topElements = [];
29354
    let byName = Object.create(null);
29355
    for (let s of eltSpecs) {
29356
        let attrs = globalAttrs, attrVals = attrValues;
29357
        if (s.attributes)
29358
            attrs = attrs.concat(s.attributes.map(s => {
29359
                if (typeof s == "string")
29360
                    return allAttrs.find(a => a.label == s) || { label: s, type: "property" };
29361
                if (s.values) {
29362
                    if (attrVals == attrValues)
29363
                        attrVals = Object.create(attrVals);
29364
                    attrVals[s.name] = s.values.map(valueCompletion);
29365
                }
29366
                return attrCompletion(s);
29367
            }));
29368
        let elt = new Element(s, attrs, attrVals);
29369
        byName[elt.name] = elt;
29370
        allElements.push(elt);
29371
        if (s.top)
29372
            topElements.push(elt);
29373
    }
29374
    if (!topElements.length)
29375
        topElements = allElements;
29376
    for (let i = 0; i < allElements.length; i++) {
29377
        let s = eltSpecs[i], elt = allElements[i];
29378
        if (s.children) {
29379
            for (let ch of s.children)
29380
                if (byName[ch])
29381
                    elt.children.push(byName[ch]);
29382
        }
29383
        else {
29384
            elt.children = allElements;
29385
        }
29386
    }
29387
    return cx => {
29388
        var _a;
29389
        let { doc } = cx.state, loc = findLocation(cx.state, cx.pos);
29390
        if (!loc || (loc.type == "tag" && !cx.explicit))
29391
            return null;
29392
        let { type, from, context } = loc;
29393
        if (type == "openTag") {
29394
            let children = topElements;
29395
            let parentName = elementName$1(doc, context);
29396
            if (parentName) {
29397
                let parent = byName[parentName];
29398
                children = (parent === null || parent === void 0 ? void 0 : parent.children) || allElements;
29399
            }
29400
            return {
29401
                from,
29402
                options: children.map(ch => ch.completion),
29403
                validFor: Identifier
29404
            };
29405
        }
29406
        else if (type == "closeTag") {
29407
            let parentName = elementName$1(doc, context);
29408
            return parentName ? {
29409
                from,
29410
                to: cx.pos + (doc.sliceString(cx.pos, cx.pos + 1) == ">" ? 1 : 0),
29411
                options: [((_a = byName[parentName]) === null || _a === void 0 ? void 0 : _a.closeNameCompletion) || { label: parentName + ">", type: "type" }],
29412
                validFor: Identifier
29413
            } : null;
29414
        }
29415
        else if (type == "attrName") {
29416
            let parent = byName[tagName(doc, context)];
29417
            return {
29418
                from,
29419
                options: (parent === null || parent === void 0 ? void 0 : parent.attrs) || globalAttrs,
29420
                validFor: Identifier
29421
            };
29422
        }
29423
        else if (type == "attrValue") {
29424
            let attr = attrName(doc, context, from);
29425
            if (!attr)
29426
                return null;
29427
            let parent = byName[tagName(doc, context)];
29428
            let values = ((parent === null || parent === void 0 ? void 0 : parent.attrValues) || attrValues)[attr];
29429
            if (!values || !values.length)
29430
                return null;
29431
            return {
29432
                from,
29433
                to: cx.pos + (doc.sliceString(cx.pos, cx.pos + 1) == '"' ? 1 : 0),
29434
                options: values,
29435
                validFor: /^"[^"]*"?$/
29436
            };
29437
        }
29438
        else if (type == "tag") {
29439
            let parentName = elementName$1(doc, context), parent = byName[parentName];
29440
            let closing = [], last = context && context.lastChild;
29441
            if (parentName && (!last || last.name != "CloseTag" || tagName(doc, last) != parentName))
29442
                closing.push(parent ? parent.closeCompletion : { label: "</" + parentName + ">", type: "type", boost: 2 });
29443
            let options = closing.concat(((parent === null || parent === void 0 ? void 0 : parent.children) || (context ? allElements : topElements)).map(e => e.openCompletion));
29444
            if (context && (parent === null || parent === void 0 ? void 0 : parent.text.length)) {
29445
                let openTag = context.firstChild;
29446
                if (openTag.to > cx.pos - 20 && !/\S/.test(cx.state.sliceDoc(openTag.to, cx.pos)))
29447
                    options = options.concat(parent.text);
29448
            }
29449
            return {
29450
                from,
29451
                options,
29452
                validFor: /^<\/?[:\-\.\w\u00b7-\uffff]*$/
29453
            };
29454
        }
29455
        else {
29456
            return null;
29457
        }
29458
    };
29459
}
29460
 
29461
/**
29462
A language provider based on the [Lezer XML
29463
parser](https://github.com/lezer-parser/xml), extended with
29464
highlighting and indentation information.
29465
*/
29466
const xmlLanguage = /*@__PURE__*/LRLanguage.define({
29467
    name: "xml",
29468
    parser: /*@__PURE__*/parser.configure({
29469
        props: [
29470
            /*@__PURE__*/indentNodeProp.add({
29471
                Element(context) {
29472
                    let closed = /^\s*<\//.test(context.textAfter);
29473
                    return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
29474
                },
29475
                "OpenTag CloseTag SelfClosingTag"(context) {
29476
                    return context.column(context.node.from) + context.unit;
29477
                }
29478
            }),
29479
            /*@__PURE__*/foldNodeProp.add({
29480
                Element(subtree) {
29481
                    let first = subtree.firstChild, last = subtree.lastChild;
29482
                    if (!first || first.name != "OpenTag")
29483
                        return null;
29484
                    return { from: first.to, to: last.name == "CloseTag" ? last.from : subtree.to };
29485
                }
29486
            }),
29487
            /*@__PURE__*/bracketMatchingHandle.add({
29488
                "OpenTag CloseTag": node => node.getChild("TagName")
29489
            })
29490
        ]
29491
    }),
29492
    languageData: {
29493
        commentTokens: { block: { open: "<!--", close: "-->" } },
29494
        indentOnInput: /^\s*<\/$/
29495
    }
29496
});
29497
/**
29498
XML language support. Includes schema-based autocompletion when
29499
configured.
29500
*/
29501
function xml(conf = {}) {
29502
    let support = [xmlLanguage.data.of({
29503
            autocomplete: completeFromSchema(conf.elements || [], conf.attributes || [])
29504
        })];
29505
    if (conf.autoCloseTags !== false)
29506
        support.push(autoCloseTags);
29507
    return new LanguageSupport(xmlLanguage, support);
29508
}
29509
function elementName(doc, tree, max = doc.length) {
29510
    if (!tree)
29511
        return "";
29512
    let tag = tree.firstChild;
29513
    let name = tag && tag.getChild("TagName");
29514
    return name ? doc.sliceString(name.from, Math.min(name.to, max)) : "";
29515
}
29516
/**
29517
Extension that will automatically insert close tags when a `>` or
29518
`/` is typed.
29519
*/
29520
const autoCloseTags = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, text, insertTransaction) => {
29521
    if (view.composing || view.state.readOnly || from != to || (text != ">" && text != "/") ||
29522
        !xmlLanguage.isActiveAt(view.state, from, -1))
29523
        return false;
29524
    let base = insertTransaction(), { state } = base;
29525
    let closeTags = state.changeByRange(range => {
29526
        var _a, _b, _c;
29527
        let { head } = range;
29528
        let didType = state.doc.sliceString(head - 1, head) == text;
29529
        let after = syntaxTree(state).resolveInner(head, -1), name;
29530
        if (didType && text == ">" && after.name == "EndTag") {
29531
            let tag = after.parent;
29532
            if (((_b = (_a = tag.parent) === null || _a === void 0 ? void 0 : _a.lastChild) === null || _b === void 0 ? void 0 : _b.name) != "CloseTag" &&
29533
                (name = elementName(state.doc, tag.parent, head))) {
29534
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
29535
                let insert = `</${name}>`;
29536
                return { range, changes: { from: head, to, insert } };
29537
            }
29538
        }
29539
        else if (didType && text == "/" && after.name == "StartCloseTag") {
29540
            let base = after.parent;
29541
            if (after.from == head - 2 && ((_c = base.lastChild) === null || _c === void 0 ? void 0 : _c.name) != "CloseTag" &&
29542
                (name = elementName(state.doc, base, head))) {
29543
                let to = head + (state.doc.sliceString(head, head + 1) === ">" ? 1 : 0);
29544
                let insert = `${name}>`;
29545
                return {
29546
                    range: EditorSelection.cursor(head + insert.length, -1),
29547
                    changes: { from: head, to, insert }
29548
                };
29549
            }
29550
        }
29551
        return { range };
29552
    });
29553
    if (closeTags.changes.empty)
29554
        return false;
29555
    view.dispatch([
29556
        base,
29557
        state.update(closeTags, {
29558
            userEvent: "input.complete",
29559
            scrollIntoView: true
29560
        })
29561
    ]);
29562
    return true;
29563
});
29564
 
29565
// This file is part of Moodle - https://moodle.org/
29566
//
29567
// Moodle is free software: you can redistribute it and/or modify
29568
// it under the terms of the GNU General Public License as published by
29569
// the Free Software Foundation, either version 3 of the License, or
29570
// (at your option) any later version.
29571
//
29572
// Moodle is distributed in the hope that it will be useful,
29573
// but WITHOUT ANY WARRANTY; without even the implied warranty of
29574
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29575
// GNU General Public License for more details.
29576
//
29577
// You should have received a copy of the GNU General Public License
29578
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
29579
 
29580
 
29581
const lang = {
29582
    html,
29583
    javascript,
29584
    xml,
29585
};
29586
 
29587
export { EditorState, EditorView, basicSetup, lang };