Debian Codegraph @

resources/lib/codemirror6.bundle.dist.js

raw
1 'use strict';
2
3 /**
4 The data structure for documents. @nonabstract
5 */
6 class Text {
7 /**
8 Get the line description around the given position.
9 */
10 lineAt(pos) {
11 if (pos < 0 || pos > this.length)
12 throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
13 return this.lineInner(pos, false, 1, 0);
14 }
15 /**
16 Get the description for the given (1-based) line number.
17 */
18 line(n) {
19 if (n < 1 || n > this.lines)
20 throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
21 return this.lineInner(n, true, 1, 0);
22 }
23 /**
24 Replace a range of the text with the given content.
25 */
26 replace(from, to, text) {
27 let parts = [];
28 this.decompose(0, from, parts, 2 /* Open.To */);
29 if (text.length)
30 text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);
31 this.decompose(to, this.length, parts, 1 /* Open.From */);
32 return TextNode.from(parts, this.length - (to - from) + text.length);
33 }
34 /**
35 Append another document to this one.
36 */
37 append(other) {
38 return this.replace(this.length, this.length, other);
39 }
40 /**
41 Retrieve the text between the given points.
42 */
43 slice(from, to = this.length) {
44 let parts = [];
45 this.decompose(from, to, parts, 0);
46 return TextNode.from(parts, to - from);
47 }
48 /**
49 Test whether this text is equal to another instance.
50 */
51 eq(other) {
52 if (other == this)
53 return true;
54 if (other.length != this.length || other.lines != this.lines)
55 return false;
56 let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
57 let a = new RawTextCursor(this), b = new RawTextCursor(other);
58 for (let skip = start, pos = start;;) {
59 a.next(skip);
60 b.next(skip);
61 skip = 0;
62 if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
63 return false;
64 pos += a.value.length;
65 if (a.done || pos >= end)
66 return true;
67 }
68 }
69 /**
70 Iterate over the text. When `dir` is `-1`, iteration happens
71 from end to start. This will return lines and the breaks between
72 them as separate strings.
73 */
74 iter(dir = 1) { return new RawTextCursor(this, dir); }
75 /**
76 Iterate over a range of the text. When `from` > `to`, the
77 iterator will run in reverse.
78 */
79 iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
80 /**
81 Return a cursor that iterates over the given range of lines,
82 _without_ returning the line breaks between, and yielding empty
83 strings for empty lines.
84
85 When `from` and `to` are given, they should be 1-based line numbers.
86 */
87 iterLines(from, to) {
88 let inner;
89 if (from == null) {
90 inner = this.iter();
91 }
92 else {
93 if (to == null)
94 to = this.lines + 1;
95 let start = this.line(from).from;
96 inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
97 }
98 return new LineCursor(inner);
99 }
100 /**
101 Return the document as a string, using newline characters to
102 separate lines.
103 */
104 toString() { return this.sliceString(0); }
105 /**
106 Convert the document to an array of lines (which can be
107 deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
108 */
109 toJSON() {
110 let lines = [];
111 this.flatten(lines);
112 return lines;
113 }
114 /**
115 @internal
116 */
117 constructor() { }
118 /**
119 Create a `Text` instance for the given array of lines.
120 */
121 static of(text) {
122 if (text.length == 0)
123 throw new RangeError("A document must have at least one line");
124 if (text.length == 1 && !text[0])
125 return Text.empty;
126 return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
127 }
128 }
129 // Leaves store an array of line strings. There are always line breaks
130 // between these strings. Leaves are limited in size and have to be
131 // contained in TextNode instances for bigger documents.
132 class TextLeaf extends Text {
133 constructor(text, length = textLength(text)) {
134 super();
135 this.text = text;
136 this.length = length;
137 }
138 get lines() { return this.text.length; }
139 get children() { return null; }
140 lineInner(target, isLine, line, offset) {
141 for (let i = 0;; i++) {
142 let string = this.text[i], end = offset + string.length;
143 if ((isLine ? line : end) >= target)
144 return new Line(offset, end, line, string);
145 offset = end + 1;
146 line++;
147 }
148 }
149 decompose(from, to, target, open) {
150 let text = from <= 0 && to >= this.length ? this
151 : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
152 if (open & 1 /* Open.From */) {
153 let prev = target.pop();
154 let joined = appendText(text.text, prev.text.slice(), 0, text.length);
155 if (joined.length <= 32 /* Tree.Branch */) {
156 target.push(new TextLeaf(joined, prev.length + text.length));
157 }
158 else {
159 let mid = joined.length >> 1;
160 target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
161 }
162 }
163 else {
164 target.push(text);
165 }
166 }
167 replace(from, to, text) {
168 if (!(text instanceof TextLeaf))
169 return super.replace(from, to, text);
170 let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
171 let newLen = this.length + text.length - (to - from);
172 if (lines.length <= 32 /* Tree.Branch */)
173 return new TextLeaf(lines, newLen);
174 return TextNode.from(TextLeaf.split(lines, []), newLen);
175 }
176 sliceString(from, to = this.length, lineSep = "\n") {
177 let result = "";
178 for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
179 let line = this.text[i], end = pos + line.length;
180 if (pos > from && i)
181 result += lineSep;
182 if (from < end && to > pos)
183 result += line.slice(Math.max(0, from - pos), to - pos);
184 pos = end + 1;
185 }
186 return result;
187 }
188 flatten(target) {
189 for (let line of this.text)
190 target.push(line);
191 }
192 scanIdentical() { return 0; }
193 static split(text, target) {
194 let part = [], len = -1;
195 for (let line of text) {
196 part.push(line);
197 len += line.length + 1;
198 if (part.length == 32 /* Tree.Branch */) {
199 target.push(new TextLeaf(part, len));
200 part = [];
201 len = -1;
202 }
203 }
204 if (len > -1)
205 target.push(new TextLeaf(part, len));
206 return target;
207 }
208 }
209 // Nodes provide the tree structure of the `Text` type. They store a
210 // number of other nodes or leaves, taking care to balance themselves
211 // on changes. There are implied line breaks _between_ the children of
212 // a node (but not before the first or after the last child).
213 class TextNode extends Text {
214 constructor(children, length) {
215 super();
216 this.children = children;
217 this.length = length;
218 this.lines = 0;
219 for (let child of children)
220 this.lines += child.lines;
221 }
222 lineInner(target, isLine, line, offset) {
223 for (let i = 0;; i++) {
224 let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
225 if ((isLine ? endLine : end) >= target)
226 return child.lineInner(target, isLine, line, offset);
227 offset = end + 1;
228 line = endLine + 1;
229 }
230 }
231 decompose(from, to, target, open) {
232 for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
233 let child = this.children[i], end = pos + child.length;
234 if (from <= end && to >= pos) {
235 let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));
236 if (pos >= from && end <= to && !childOpen)
237 target.push(child);
238 else
239 child.decompose(from - pos, to - pos, target, childOpen);
240 }
241 pos = end + 1;
242 }
243 }
244 replace(from, to, text) {
245 if (text.lines < this.lines)
246 for (let i = 0, pos = 0; i < this.children.length; i++) {
247 let child = this.children[i], end = pos + child.length;
248 // Fast path: if the change only affects one child and the
249 // child's size remains in the acceptable range, only update
250 // that child
251 if (from >= pos && to <= end) {
252 let updated = child.replace(from - pos, to - pos, text);
253 let totalLines = this.lines - child.lines + updated.lines;
254 if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&
255 updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {
256 let copy = this.children.slice();
257 copy[i] = updated;
258 return new TextNode(copy, this.length - (to - from) + text.length);
259 }
260 return super.replace(pos, end, updated);
261 }
262 pos = end + 1;
263 }
264 return super.replace(from, to, text);
265 }
266 sliceString(from, to = this.length, lineSep = "\n") {
267 let result = "";
268 for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
269 let child = this.children[i], end = pos + child.length;
270 if (pos > from && i)
271 result += lineSep;
272 if (from < end && to > pos)
273 result += child.sliceString(from - pos, to - pos, lineSep);
274 pos = end + 1;
275 }
276 return result;
277 }
278 flatten(target) {
279 for (let child of this.children)
280 child.flatten(target);
281 }
282 scanIdentical(other, dir) {
283 if (!(other instanceof TextNode))
284 return 0;
285 let length = 0;
286 let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
287 : [this.children.length - 1, other.children.length - 1, -1, -1];
288 for (;; iA += dir, iB += dir) {
289 if (iA == eA || iB == eB)
290 return length;
291 let chA = this.children[iA], chB = other.children[iB];
292 if (chA != chB)
293 return length + chA.scanIdentical(chB, dir);
294 length += chA.length + 1;
295 }
296 }
297 static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
298 let lines = 0;
299 for (let ch of children)
300 lines += ch.lines;
301 if (lines < 32 /* Tree.Branch */) {
302 let flat = [];
303 for (let ch of children)
304 ch.flatten(flat);
305 return new TextLeaf(flat, length);
306 }
307 let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
308 let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
309 function add(child) {
310 let last;
311 if (child.lines > maxChunk && child instanceof TextNode) {
312 for (let node of child.children)
313 add(node);
314 }
315 else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
316 flush();
317 chunked.push(child);
318 }
319 else if (child instanceof TextLeaf && currentLines &&
320 (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
321 child.lines + last.lines <= 32 /* Tree.Branch */) {
322 currentLines += child.lines;
323 currentLen += child.length + 1;
324 currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
325 }
326 else {
327 if (currentLines + child.lines > chunk)
328 flush();
329 currentLines += child.lines;
330 currentLen += child.length + 1;
331 currentChunk.push(child);
332 }
333 }
334 function flush() {
335 if (currentLines == 0)
336 return;
337 chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
338 currentLen = -1;
339 currentLines = currentChunk.length = 0;
340 }
341 for (let child of children)
342 add(child);
343 flush();
344 return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
345 }
346 }
347 Text.empty = /*@__PURE__*/new TextLeaf([""], 0);
348 function textLength(text) {
349 let length = -1;
350 for (let line of text)
351 length += line.length + 1;
352 return length;
353 }
354 function appendText(text, target, from = 0, to = 1e9) {
355 for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
356 let line = text[i], end = pos + line.length;
357 if (end >= from) {
358 if (end > to)
359 line = line.slice(0, to - pos);
360 if (pos < from)
361 line = line.slice(from - pos);
362 if (first) {
363 target[target.length - 1] += line;
364 first = false;
365 }
366 else
367 target.push(line);
368 }
369 pos = end + 1;
370 }
371 return target;
372 }
373 function sliceText(text, from, to) {
374 return appendText(text, [""], from, to);
375 }
376 class RawTextCursor {
377 constructor(text, dir = 1) {
378 this.dir = dir;
379 this.done = false;
380 this.lineBreak = false;
381 this.value = "";
382 this.nodes = [text];
383 this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
384 }
385 nextInner(skip, dir) {
386 this.done = this.lineBreak = false;
387 for (;;) {
388 let last = this.nodes.length - 1;
389 let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
390 let size = top instanceof TextLeaf ? top.text.length : top.children.length;
391 if (offset == (dir > 0 ? size : 0)) {
392 if (last == 0) {
393 this.done = true;
394 this.value = "";
395 return this;
396 }
397 if (dir > 0)
398 this.offsets[last - 1]++;
399 this.nodes.pop();
400 this.offsets.pop();
401 }
402 else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
403 this.offsets[last] += dir;
404 if (skip == 0) {
405 this.lineBreak = true;
406 this.value = "\n";
407 return this;
408 }
409 skip--;
410 }
411 else if (top instanceof TextLeaf) {
412 // Move to the next string
413 let next = top.text[offset + (dir < 0 ? -1 : 0)];
414 this.offsets[last] += dir;
415 if (next.length > Math.max(0, skip)) {
416 this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
417 return this;
418 }
419 skip -= next.length;
420 }
421 else {
422 let next = top.children[offset + (dir < 0 ? -1 : 0)];
423 if (skip > next.length) {
424 skip -= next.length;
425 this.offsets[last] += dir;
426 }
427 else {
428 if (dir < 0)
429 this.offsets[last]--;
430 this.nodes.push(next);
431 this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
432 }
433 }
434 }
435 }
436 next(skip = 0) {
437 if (skip < 0) {
438 this.nextInner(-skip, (-this.dir));
439 skip = this.value.length;
440 }
441 return this.nextInner(skip, this.dir);
442 }
443 }
444 class PartialTextCursor {
445 constructor(text, start, end) {
446 this.value = "";
447 this.done = false;
448 this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
449 this.pos = start > end ? text.length : 0;
450 this.from = Math.min(start, end);
451 this.to = Math.max(start, end);
452 }
453 nextInner(skip, dir) {
454 if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
455 this.value = "";
456 this.done = true;
457 return this;
458 }
459 skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
460 let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
461 if (skip > limit)
462 skip = limit;
463 limit -= skip;
464 let { value } = this.cursor.next(skip);
465 this.pos += (value.length + skip) * dir;
466 this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
467 this.done = !this.value;
468 return this;
469 }
470 next(skip = 0) {
471 if (skip < 0)
472 skip = Math.max(skip, this.from - this.pos);
473 else if (skip > 0)
474 skip = Math.min(skip, this.to - this.pos);
475 return this.nextInner(skip, this.cursor.dir);
476 }
477 get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
478 }
479 class LineCursor {
480 constructor(inner) {
481 this.inner = inner;
482 this.afterBreak = true;
483 this.value = "";
484 this.done = false;
485 }
486 next(skip = 0) {
487 let { done, lineBreak, value } = this.inner.next(skip);
488 if (done) {
489 this.done = true;
490 this.value = "";
491 }
492 else if (lineBreak) {
493 if (this.afterBreak) {
494 this.value = "";
495 }
496 else {
497 this.afterBreak = true;
498 this.next();
499 }
500 }
501 else {
502 this.value = value;
503 this.afterBreak = false;
504 }
505 return this;
506 }
507 get lineBreak() { return false; }
508 }
509 if (typeof Symbol != "undefined") {
510 Text.prototype[Symbol.iterator] = function () { return this.iter(); };
511 RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
512 LineCursor.prototype[Symbol.iterator] = function () { return this; };
513 }
514 /**
515 This type describes a line in the document. It is created
516 on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
517 */
518 class Line {
519 /**
520 @internal
521 */
522 constructor(
523 /**
524 The position of the start of the line.
525 */
526 from,
527 /**
528 The position at the end of the line (_before_ the line break,
529 or at the end of document for the last line).
530 */
531 to,
532 /**
533 This line's line number (1-based).
534 */
535 number,
536 /**
537 The line's content.
538 */
539 text) {
540 this.from = from;
541 this.to = to;
542 this.number = number;
543 this.text = text;
544 }
545 /**
546 The length of the line (not including any line break after it).
547 */
548 get length() { return this.to - this.from; }
549 }
550
551 // Compressed representation of the Grapheme_Cluster_Break=Extend
552 // information from
553 // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
554 // Each pair of elements represents a range, as an offet from the
555 // previous range and a length. Numbers are in base-36, with the empty
556 // string being a shorthand for 1.
557 let extend = /*@__PURE__*/"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1);
558 // Convert offsets into absolute values
559 for (let i = 1; i < extend.length; i++)
560 extend[i] += extend[i - 1];
561 function isExtendingChar(code) {
562 for (let i = 1; i < extend.length; i += 2)
563 if (extend[i] > code)
564 return extend[i - 1] <= code;
565 return false;
566 }
567 function isRegionalIndicator(code) {
568 return code >= 0x1F1E6 && code <= 0x1F1FF;
569 }
570 const ZWJ = 0x200d;
571 /**
572 Returns a next grapheme cluster break _after_ (not equal to)
573 `pos`, if `forward` is true, or before otherwise. Returns `pos`
574 itself if no further cluster break is available in the string.
575 Moves across surrogate pairs, extending characters (when
576 `includeExtending` is true), characters joined with zero-width
577 joiners, and flag emoji.
578 */
579 function findClusterBreak(str, pos, forward = true, includeExtending = true) {
580 return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
581 }
582 function nextClusterBreak(str, pos, includeExtending) {
583 if (pos == str.length)
584 return pos;
585 // If pos is in the middle of a surrogate pair, move to its start
586 if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
587 pos--;
588 let prev = codePointAt(str, pos);
589 pos += codePointSize(prev);
590 while (pos < str.length) {
591 let next = codePointAt(str, pos);
592 if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
593 pos += codePointSize(next);
594 prev = next;
595 }
596 else if (isRegionalIndicator(next)) {
597 let countBefore = 0, i = pos - 2;
598 while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
599 countBefore++;
600 i -= 2;
601 }
602 if (countBefore % 2 == 0)
603 break;
604 else
605 pos += 2;
606 }
607 else {
608 break;
609 }
610 }
611 return pos;
612 }
613 function prevClusterBreak(str, pos, includeExtending) {
614 while (pos > 0) {
615 let found = nextClusterBreak(str, pos - 2, includeExtending);
616 if (found < pos)
617 return found;
618 pos--;
619 }
620 return 0;
621 }
622 function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
623 function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
624 /**
625 Find the code point at the given position in a string (like the
626 [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
627 string method).
628 */
629 function codePointAt(str, pos) {
630 let code0 = str.charCodeAt(pos);
631 if (!surrogateHigh(code0) || pos + 1 == str.length)
632 return code0;
633 let code1 = str.charCodeAt(pos + 1);
634 if (!surrogateLow(code1))
635 return code0;
636 return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
637 }
638 /**
639 Given a Unicode codepoint, return the JavaScript string that
640 respresents it (like
641 [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
642 */
643 function fromCodePoint(code) {
644 if (code <= 0xffff)
645 return String.fromCharCode(code);
646 code -= 0x10000;
647 return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
648 }
649 /**
650 The amount of positions a character takes up a JavaScript string.
651 */
652 function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
653
654 const DefaultSplit = /\r\n?|\n/;
655 /**
656 Distinguishes different ways in which positions can be mapped.
657 */
658 exports.MapMode = /*@__PURE__*/(function (MapMode) {
659 /**
660 Map a position to a valid new position, even when its context
661 was deleted.
662 */
663 MapMode[MapMode["Simple"] = 0] = "Simple";
664 /**
665 Return null if deletion happens across the position.
666 */
667 MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
668 /**
669 Return null if the character _before_ the position is deleted.
670 */
671 MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
672 /**
673 Return null if the character _after_ the position is deleted.
674 */
675 MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
676 return MapMode})(exports.MapMode || (exports.MapMode = {}));
677 /**
678 A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
679 that doesn't store the inserted text. As such, it can't be
680 applied, but is cheaper to store and manipulate.
681 */
682 class ChangeDesc {
683 // Sections are encoded as pairs of integers. The first is the
684 // length in the current document, and the second is -1 for
685 // unaffected sections, and the length of the replacement content
686 // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
687 // 0), and a replacement two positive numbers.
688 /**
689 @internal
690 */
691 constructor(
692 /**
693 @internal
694 */
695 sections) {
696 this.sections = sections;
697 }
698 /**
699 The length of the document before the change.
700 */
701 get length() {
702 let result = 0;
703 for (let i = 0; i < this.sections.length; i += 2)
704 result += this.sections[i];
705 return result;
706 }
707 /**
708 The length of the document after the change.
709 */
710 get newLength() {
711 let result = 0;
712 for (let i = 0; i < this.sections.length; i += 2) {
713 let ins = this.sections[i + 1];
714 result += ins < 0 ? this.sections[i] : ins;
715 }
716 return result;
717 }
718 /**
719 False when there are actual changes in this set.
720 */
721 get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
722 /**
723 Iterate over the unchanged parts left by these changes. `posA`
724 provides the position of the range in the old document, `posB`
725 the new position in the changed document.
726 */
727 iterGaps(f) {
728 for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
729 let len = this.sections[i++], ins = this.sections[i++];
730 if (ins < 0) {
731 f(posA, posB, len);
732 posB += len;
733 }
734 else {
735 posB += ins;
736 }
737 posA += len;
738 }
739 }
740 /**
741 Iterate over the ranges changed by these changes. (See
742 [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
743 variant that also provides you with the inserted text.)
744 `fromA`/`toA` provides the extent of the change in the starting
745 document, `fromB`/`toB` the extent of the replacement in the
746 changed document.
747
748 When `individual` is true, adjacent changes (which are kept
749 separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
750 reported separately.
751 */
752 iterChangedRanges(f, individual = false) {
753 iterChanges(this, f, individual);
754 }
755 /**
756 Get a description of the inverted form of these changes.
757 */
758 get invertedDesc() {
759 let sections = [];
760 for (let i = 0; i < this.sections.length;) {
761 let len = this.sections[i++], ins = this.sections[i++];
762 if (ins < 0)
763 sections.push(len, ins);
764 else
765 sections.push(ins, len);
766 }
767 return new ChangeDesc(sections);
768 }
769 /**
770 Compute the combined effect of applying another set of changes
771 after this one. The length of the document after this set should
772 match the length before `other`.
773 */
774 composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
775 /**
776 Map this description, which should start with the same document
777 as `other`, over another set of changes, so that it can be
778 applied after it. When `before` is true, map as if the changes
779 in `other` happened before the ones in `this`.
780 */
781 mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
782 mapPos(pos, assoc = -1, mode = exports.MapMode.Simple) {
783 let posA = 0, posB = 0;
784 for (let i = 0; i < this.sections.length;) {
785 let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
786 if (ins < 0) {
787 if (endA > pos)
788 return posB + (pos - posA);
789 posB += len;
790 }
791 else {
792 if (mode != exports.MapMode.Simple && endA >= pos &&
793 (mode == exports.MapMode.TrackDel && posA < pos && endA > pos ||
794 mode == exports.MapMode.TrackBefore && posA < pos ||
795 mode == exports.MapMode.TrackAfter && endA > pos))
796 return null;
797 if (endA > pos || endA == pos && assoc < 0 && !len)
798 return pos == posA || assoc < 0 ? posB : posB + ins;
799 posB += ins;
800 }
801 posA = endA;
802 }
803 if (pos > posA)
804 throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
805 return posB;
806 }
807 /**
808 Check whether these changes touch a given range. When one of the
809 changes entirely covers the range, the string `"cover"` is
810 returned.
811 */
812 touchesRange(from, to = from) {
813 for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
814 let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
815 if (ins >= 0 && pos <= to && end >= from)
816 return pos < from && end > to ? "cover" : true;
817 pos = end;
818 }
819 return false;
820 }
821 /**
822 @internal
823 */
824 toString() {
825 let result = "";
826 for (let i = 0; i < this.sections.length;) {
827 let len = this.sections[i++], ins = this.sections[i++];
828 result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
829 }
830 return result;
831 }
832 /**
833 Serialize this change desc to a JSON-representable value.
834 */
835 toJSON() { return this.sections; }
836 /**
837 Create a change desc from its JSON representation (as produced
838 by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
839 */
840 static fromJSON(json) {
841 if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
842 throw new RangeError("Invalid JSON representation of ChangeDesc");
843 return new ChangeDesc(json);
844 }
845 /**
846 @internal
847 */
848 static create(sections) { return new ChangeDesc(sections); }
849 }
850 /**
851 A change set represents a group of modifications to a document. It
852 stores the document length, and can only be applied to documents
853 with exactly that length.
854 */
855 class ChangeSet extends ChangeDesc {
856 constructor(sections,
857 /**
858 @internal
859 */
860 inserted) {
861 super(sections);
862 this.inserted = inserted;
863 }
864 /**
865 Apply the changes to a document, returning the modified
866 document.
867 */
868 apply(doc) {
869 if (this.length != doc.length)
870 throw new RangeError("Applying change set to a document with the wrong length");
871 iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
872 return doc;
873 }
874 mapDesc(other, before = false) { return mapSet(this, other, before, true); }
875 /**
876 Given the document as it existed _before_ the changes, return a
877 change set that represents the inverse of this set, which could
878 be used to go from the document created by the changes back to
879 the document as it existed before the changes.
880 */
881 invert(doc) {
882 let sections = this.sections.slice(), inserted = [];
883 for (let i = 0, pos = 0; i < sections.length; i += 2) {
884 let len = sections[i], ins = sections[i + 1];
885 if (ins >= 0) {
886 sections[i] = ins;
887 sections[i + 1] = len;
888 let index = i >> 1;
889 while (inserted.length < index)
890 inserted.push(Text.empty);
891 inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
892 }
893 pos += len;
894 }
895 return new ChangeSet(sections, inserted);
896 }
897 /**
898 Combine two subsequent change sets into a single set. `other`
899 must start in the document produced by `this`. If `this` goes
900 `docA` → `docB` and `other` represents `docB` → `docC`, the
901 returned value will represent the change `docA` → `docC`.
902 */
903 compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
904 /**
905 Given another change set starting in the same document, maps this
906 change set over the other, producing a new change set that can be
907 applied to the document produced by applying `other`. When
908 `before` is `true`, order changes as if `this` comes before
909 `other`, otherwise (the default) treat `other` as coming first.
910
911 Given two changes `A` and `B`, `A.compose(B.map(A))` and
912 `B.compose(A.map(B, true))` will produce the same document. This
913 provides a basic form of [operational
914 transformation](https://en.wikipedia.org/wiki/Operational_transformation),
915 and can be used for collaborative editing.
916 */
917 map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
918 /**
919 Iterate over the changed ranges in the document, calling `f` for
920 each, with the range in the original document (`fromA`-`toA`)
921 and the range that replaces it in the new document
922 (`fromB`-`toB`).
923
924 When `individual` is true, adjacent changes are reported
925 separately.
926 */
927 iterChanges(f, individual = false) {
928 iterChanges(this, f, individual);
929 }
930 /**
931 Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
932 set.
933 */
934 get desc() { return ChangeDesc.create(this.sections); }
935 /**
936 @internal
937 */
938 filter(ranges) {
939 let resultSections = [], resultInserted = [], filteredSections = [];
940 let iter = new SectionIter(this);
941 done: for (let i = 0, pos = 0;;) {
942 let next = i == ranges.length ? 1e9 : ranges[i++];
943 while (pos < next || pos == next && iter.len == 0) {
944 if (iter.done)
945 break done;
946 let len = Math.min(iter.len, next - pos);
947 addSection(filteredSections, len, -1);
948 let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
949 addSection(resultSections, len, ins);
950 if (ins > 0)
951 addInsert(resultInserted, resultSections, iter.text);
952 iter.forward(len);
953 pos += len;
954 }
955 let end = ranges[i++];
956 while (pos < end) {
957 if (iter.done)
958 break done;
959 let len = Math.min(iter.len, end - pos);
960 addSection(resultSections, len, -1);
961 addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
962 iter.forward(len);
963 pos += len;
964 }
965 }
966 return { changes: new ChangeSet(resultSections, resultInserted),
967 filtered: ChangeDesc.create(filteredSections) };
968 }
969 /**
970 Serialize this change set to a JSON-representable value.
971 */
972 toJSON() {
973 let parts = [];
974 for (let i = 0; i < this.sections.length; i += 2) {
975 let len = this.sections[i], ins = this.sections[i + 1];
976 if (ins < 0)
977 parts.push(len);
978 else if (ins == 0)
979 parts.push([len]);
980 else
981 parts.push([len].concat(this.inserted[i >> 1].toJSON()));
982 }
983 return parts;
984 }
985 /**
986 Create a change set for the given changes, for a document of the
987 given length, using `lineSep` as line separator.
988 */
989 static of(changes, length, lineSep) {
990 let sections = [], inserted = [], pos = 0;
991 let total = null;
992 function flush(force = false) {
993 if (!force && !sections.length)
994 return;
995 if (pos < length)
996 addSection(sections, length - pos, -1);
997 let set = new ChangeSet(sections, inserted);
998 total = total ? total.compose(set.map(total)) : set;
999 sections = [];
1000 inserted = [];
1001 pos = 0;
1002 }
1003 function process(spec) {
1004 if (Array.isArray(spec)) {
1005 for (let sub of spec)
1006 process(sub);
1007 }
1008 else if (spec instanceof ChangeSet) {
1009 if (spec.length != length)
1010 throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
1011 flush();
1012 total = total ? total.compose(spec.map(total)) : spec;
1013 }
1014 else {
1015 let { from, to = from, insert } = spec;
1016 if (from > to || from < 0 || to > length)
1017 throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
1018 let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
1019 let insLen = insText.length;
1020 if (from == to && insLen == 0)
1021 return;
1022 if (from < pos)
1023 flush();
1024 if (from > pos)
1025 addSection(sections, from - pos, -1);
1026 addSection(sections, to - from, insLen);
1027 addInsert(inserted, sections, insText);
1028 pos = to;
1029 }
1030 }
1031 process(changes);
1032 flush(!total);
1033 return total;
1034 }
1035 /**
1036 Create an empty changeset of the given length.
1037 */
1038 static empty(length) {
1039 return new ChangeSet(length ? [length, -1] : [], []);
1040 }
1041 /**
1042 Create a changeset from its JSON representation (as produced by
1043 [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
1044 */
1045 static fromJSON(json) {
1046 if (!Array.isArray(json))
1047 throw new RangeError("Invalid JSON representation of ChangeSet");
1048 let sections = [], inserted = [];
1049 for (let i = 0; i < json.length; i++) {
1050 let part = json[i];
1051 if (typeof part == "number") {
1052 sections.push(part, -1);
1053 }
1054 else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
1055 throw new RangeError("Invalid JSON representation of ChangeSet");
1056 }
1057 else if (part.length == 1) {
1058 sections.push(part[0], 0);
1059 }
1060 else {
1061 while (inserted.length < i)
1062 inserted.push(Text.empty);
1063 inserted[i] = Text.of(part.slice(1));
1064 sections.push(part[0], inserted[i].length);
1065 }
1066 }
1067 return new ChangeSet(sections, inserted);
1068 }
1069 /**
1070 @internal
1071 */
1072 static createSet(sections, inserted) {
1073 return new ChangeSet(sections, inserted);
1074 }
1075 }
1076 function addSection(sections, len, ins, forceJoin = false) {
1077 if (len == 0 && ins <= 0)
1078 return;
1079 let last = sections.length - 2;
1080 if (last >= 0 && ins <= 0 && ins == sections[last + 1])
1081 sections[last] += len;
1082 else if (len == 0 && sections[last] == 0)
1083 sections[last + 1] += ins;
1084 else if (forceJoin) {
1085 sections[last] += len;
1086 sections[last + 1] += ins;
1087 }
1088 else
1089 sections.push(len, ins);
1090 }
1091 function addInsert(values, sections, value) {
1092 if (value.length == 0)
1093 return;
1094 let index = (sections.length - 2) >> 1;
1095 if (index < values.length) {
1096 values[values.length - 1] = values[values.length - 1].append(value);
1097 }
1098 else {
1099 while (values.length < index)
1100 values.push(Text.empty);
1101 values.push(value);
1102 }
1103 }
1104 function iterChanges(desc, f, individual) {
1105 let inserted = desc.inserted;
1106 for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
1107 let len = desc.sections[i++], ins = desc.sections[i++];
1108 if (ins < 0) {
1109 posA += len;
1110 posB += len;
1111 }
1112 else {
1113 let endA = posA, endB = posB, text = Text.empty;
1114 for (;;) {
1115 endA += len;
1116 endB += ins;
1117 if (ins && inserted)
1118 text = text.append(inserted[(i - 2) >> 1]);
1119 if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
1120 break;
1121 len = desc.sections[i++];
1122 ins = desc.sections[i++];
1123 }
1124 f(posA, endA, posB, endB, text);
1125 posA = endA;
1126 posB = endB;
1127 }
1128 }
1129 }
1130 function mapSet(setA, setB, before, mkSet = false) {
1131 // Produce a copy of setA that applies to the document after setB
1132 // has been applied (assuming both start at the same document).
1133 let sections = [], insert = mkSet ? [] : null;
1134 let a = new SectionIter(setA), b = new SectionIter(setB);
1135 // Iterate over both sets in parallel. inserted tracks, for changes
1136 // in A that have to be processed piece-by-piece, whether their
1137 // content has been inserted already, and refers to the section
1138 // index.
1139 for (let inserted = -1;;) {
1140 if (a.ins == -1 && b.ins == -1) {
1141 // Move across ranges skipped by both sets.
1142 let len = Math.min(a.len, b.len);
1143 addSection(sections, len, -1);
1144 a.forward(len);
1145 b.forward(len);
1146 }
1147 else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
1148 // If there's a change in B that comes before the next change in
1149 // A (ordered by start pos, then len, then before flag), skip
1150 // that (and process any changes in A it covers).
1151 let len = b.len;
1152 addSection(sections, b.ins, -1);
1153 while (len) {
1154 let piece = Math.min(a.len, len);
1155 if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
1156 addSection(sections, 0, a.ins);
1157 if (insert)
1158 addInsert(insert, sections, a.text);
1159 inserted = a.i;
1160 }
1161 a.forward(piece);
1162 len -= piece;
1163 }
1164 b.next();
1165 }
1166 else if (a.ins >= 0) {
1167 // Process the part of a change in A up to the start of the next
1168 // non-deletion change in B (if overlapping).
1169 let len = 0, left = a.len;
1170 while (left) {
1171 if (b.ins == -1) {
1172 let piece = Math.min(left, b.len);
1173 len += piece;
1174 left -= piece;
1175 b.forward(piece);
1176 }
1177 else if (b.ins == 0 && b.len < left) {
1178 left -= b.len;
1179 b.next();
1180 }
1181 else {
1182 break;
1183 }
1184 }
1185 addSection(sections, len, inserted < a.i ? a.ins : 0);
1186 if (insert && inserted < a.i)
1187 addInsert(insert, sections, a.text);
1188 inserted = a.i;
1189 a.forward(a.len - left);
1190 }
1191 else if (a.done && b.done) {
1192 return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1193 }
1194 else {
1195 throw new Error("Mismatched change set lengths");
1196 }
1197 }
1198 }
1199 function composeSets(setA, setB, mkSet = false) {
1200 let sections = [];
1201 let insert = mkSet ? [] : null;
1202 let a = new SectionIter(setA), b = new SectionIter(setB);
1203 for (let open = false;;) {
1204 if (a.done && b.done) {
1205 return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
1206 }
1207 else if (a.ins == 0) { // Deletion in A
1208 addSection(sections, a.len, 0, open);
1209 a.next();
1210 }
1211 else if (b.len == 0 && !b.done) { // Insertion in B
1212 addSection(sections, 0, b.ins, open);
1213 if (insert)
1214 addInsert(insert, sections, b.text);
1215 b.next();
1216 }
1217 else if (a.done || b.done) {
1218 throw new Error("Mismatched change set lengths");
1219 }
1220 else {
1221 let len = Math.min(a.len2, b.len), sectionLen = sections.length;
1222 if (a.ins == -1) {
1223 let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
1224 addSection(sections, len, insB, open);
1225 if (insert && insB)
1226 addInsert(insert, sections, b.text);
1227 }
1228 else if (b.ins == -1) {
1229 addSection(sections, a.off ? 0 : a.len, len, open);
1230 if (insert)
1231 addInsert(insert, sections, a.textBit(len));
1232 }
1233 else {
1234 addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
1235 if (insert && !b.off)
1236 addInsert(insert, sections, b.text);
1237 }
1238 open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
1239 a.forward2(len);
1240 b.forward(len);
1241 }
1242 }
1243 }
1244 class SectionIter {
1245 constructor(set) {
1246 this.set = set;
1247 this.i = 0;
1248 this.next();
1249 }
1250 next() {
1251 let { sections } = this.set;
1252 if (this.i < sections.length) {
1253 this.len = sections[this.i++];
1254 this.ins = sections[this.i++];
1255 }
1256 else {
1257 this.len = 0;
1258 this.ins = -2;
1259 }
1260 this.off = 0;
1261 }
1262 get done() { return this.ins == -2; }
1263 get len2() { return this.ins < 0 ? this.len : this.ins; }
1264 get text() {
1265 let { inserted } = this.set, index = (this.i - 2) >> 1;
1266 return index >= inserted.length ? Text.empty : inserted[index];
1267 }
1268 textBit(len) {
1269 let { inserted } = this.set, index = (this.i - 2) >> 1;
1270 return index >= inserted.length && !len ? Text.empty
1271 : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
1272 }
1273 forward(len) {
1274 if (len == this.len)
1275 this.next();
1276 else {
1277 this.len -= len;
1278 this.off += len;
1279 }
1280 }
1281 forward2(len) {
1282 if (this.ins == -1)
1283 this.forward(len);
1284 else if (len == this.ins)
1285 this.next();
1286 else {
1287 this.ins -= len;
1288 this.off += len;
1289 }
1290 }
1291 }
1292
1293 /**
1294 A single selection range. When
1295 [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
1296 is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
1297 multiple ranges. By default, selections hold exactly one range.
1298 */
1299 class SelectionRange {
1300 constructor(
1301 /**
1302 The lower boundary of the range.
1303 */
1304 from,
1305 /**
1306 The upper boundary of the range.
1307 */
1308 to, flags) {
1309 this.from = from;
1310 this.to = to;
1311 this.flags = flags;
1312 }
1313 /**
1314 The anchor of the range—the side that doesn't move when you
1315 extend it.
1316 */
1317 get anchor() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.to : this.from; }
1318 /**
1319 The head of the range, which is moved when the range is
1320 [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
1321 */
1322 get head() { return this.flags & 16 /* RangeFlag.Inverted */ ? this.from : this.to; }
1323 /**
1324 True when `anchor` and `head` are at the same position.
1325 */
1326 get empty() { return this.from == this.to; }
1327 /**
1328 If this is a cursor that is explicitly associated with the
1329 character on one of its sides, this returns the side. -1 means
1330 the character before its position, 1 the character after, and 0
1331 means no association.
1332 */
1333 get assoc() { return this.flags & 4 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 8 /* RangeFlag.AssocAfter */ ? 1 : 0; }
1334 /**
1335 The bidirectional text level associated with this cursor, if
1336 any.
1337 */
1338 get bidiLevel() {
1339 let level = this.flags & 3 /* RangeFlag.BidiLevelMask */;
1340 return level == 3 ? null : level;
1341 }
1342 /**
1343 The goal column (stored vertical offset) associated with a
1344 cursor. This is used to preserve the vertical position when
1345 [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
1346 lines of different length.
1347 */
1348 get goalColumn() {
1349 let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */;
1350 return value == 33554431 /* RangeFlag.NoGoalColumn */ ? undefined : value;
1351 }
1352 /**
1353 Map this range through a change, producing a valid range in the
1354 updated document.
1355 */
1356 map(change, assoc = -1) {
1357 let from, to;
1358 if (this.empty) {
1359 from = to = change.mapPos(this.from, assoc);
1360 }
1361 else {
1362 from = change.mapPos(this.from, 1);
1363 to = change.mapPos(this.to, -1);
1364 }
1365 return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
1366 }
1367 /**
1368 Extend this range to cover at least `from` to `to`.
1369 */
1370 extend(from, to = from) {
1371 if (from <= this.anchor && to >= this.anchor)
1372 return EditorSelection.range(from, to);
1373 let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
1374 return EditorSelection.range(this.anchor, head);
1375 }
1376 /**
1377 Compare this range to another range.
1378 */
1379 eq(other) {
1380 return this.anchor == other.anchor && this.head == other.head;
1381 }
1382 /**
1383 Return a JSON-serializable object representing the range.
1384 */
1385 toJSON() { return { anchor: this.anchor, head: this.head }; }
1386 /**
1387 Convert a JSON representation of a range to a `SelectionRange`
1388 instance.
1389 */
1390 static fromJSON(json) {
1391 if (!json || typeof json.anchor != "number" || typeof json.head != "number")
1392 throw new RangeError("Invalid JSON representation for SelectionRange");
1393 return EditorSelection.range(json.anchor, json.head);
1394 }
1395 /**
1396 @internal
1397 */
1398 static create(from, to, flags) {
1399 return new SelectionRange(from, to, flags);
1400 }
1401 }
1402 /**
1403 An editor selection holds one or more selection ranges.
1404 */
1405 class EditorSelection {
1406 constructor(
1407 /**
1408 The ranges in the selection, sorted by position. Ranges cannot
1409 overlap (but they may touch, if they aren't empty).
1410 */
1411 ranges,
1412 /**
1413 The index of the _main_ range in the selection (which is
1414 usually the range that was added last).
1415 */
1416 mainIndex) {
1417 this.ranges = ranges;
1418 this.mainIndex = mainIndex;
1419 }
1420 /**
1421 Map a selection through a change. Used to adjust the selection
1422 position for changes.
1423 */
1424 map(change, assoc = -1) {
1425 if (change.empty)
1426 return this;
1427 return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
1428 }
1429 /**
1430 Compare this selection to another selection.
1431 */
1432 eq(other) {
1433 if (this.ranges.length != other.ranges.length ||
1434 this.mainIndex != other.mainIndex)
1435 return false;
1436 for (let i = 0; i < this.ranges.length; i++)
1437 if (!this.ranges[i].eq(other.ranges[i]))
1438 return false;
1439 return true;
1440 }
1441 /**
1442 Get the primary selection range. Usually, you should make sure
1443 your code applies to _all_ ranges, by using methods like
1444 [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
1445 */
1446 get main() { return this.ranges[this.mainIndex]; }
1447 /**
1448 Make sure the selection only has one range. Returns a selection
1449 holding only the main range from this selection.
1450 */
1451 asSingle() {
1452 return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
1453 }
1454 /**
1455 Extend this selection with an extra range.
1456 */
1457 addRange(range, main = true) {
1458 return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
1459 }
1460 /**
1461 Replace a given range with another range, and then normalize the
1462 selection to merge and sort ranges if necessary.
1463 */
1464 replaceRange(range, which = this.mainIndex) {
1465 let ranges = this.ranges.slice();
1466 ranges[which] = range;
1467 return EditorSelection.create(ranges, this.mainIndex);
1468 }
1469 /**
1470 Convert this selection to an object that can be serialized to
1471 JSON.
1472 */
1473 toJSON() {
1474 return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
1475 }
1476 /**
1477 Create a selection from a JSON representation.
1478 */
1479 static fromJSON(json) {
1480 if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
1481 throw new RangeError("Invalid JSON representation for EditorSelection");
1482 return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
1483 }
1484 /**
1485 Create a selection holding a single range.
1486 */
1487 static single(anchor, head = anchor) {
1488 return new EditorSelection([EditorSelection.range(anchor, head)], 0);
1489 }
1490 /**
1491 Sort and merge the given set of ranges, creating a valid
1492 selection.
1493 */
1494 static create(ranges, mainIndex = 0) {
1495 if (ranges.length == 0)
1496 throw new RangeError("A selection needs at least one range");
1497 for (let pos = 0, i = 0; i < ranges.length; i++) {
1498 let range = ranges[i];
1499 if (range.empty ? range.from <= pos : range.from < pos)
1500 return EditorSelection.normalized(ranges.slice(), mainIndex);
1501 pos = range.to;
1502 }
1503 return new EditorSelection(ranges, mainIndex);
1504 }
1505 /**
1506 Create a cursor selection range at the given position. You can
1507 safely ignore the optional arguments in most situations.
1508 */
1509 static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
1510 return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* RangeFlag.AssocBefore */ : 8 /* RangeFlag.AssocAfter */) |
1511 (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) |
1512 ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */));
1513 }
1514 /**
1515 Create a selection range.
1516 */
1517 static range(anchor, head, goalColumn, bidiLevel) {
1518 let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* RangeFlag.NoGoalColumn */) << 5 /* RangeFlag.GoalColumnOffset */) |
1519 (bidiLevel == null ? 3 : Math.min(2, bidiLevel));
1520 return head < anchor ? SelectionRange.create(head, anchor, 16 /* RangeFlag.Inverted */ | 8 /* RangeFlag.AssocAfter */ | flags)
1521 : SelectionRange.create(anchor, head, (head > anchor ? 4 /* RangeFlag.AssocBefore */ : 0) | flags);
1522 }
1523 /**
1524 @internal
1525 */
1526 static normalized(ranges, mainIndex = 0) {
1527 let main = ranges[mainIndex];
1528 ranges.sort((a, b) => a.from - b.from);
1529 mainIndex = ranges.indexOf(main);
1530 for (let i = 1; i < ranges.length; i++) {
1531 let range = ranges[i], prev = ranges[i - 1];
1532 if (range.empty ? range.from <= prev.to : range.from < prev.to) {
1533 let from = prev.from, to = Math.max(range.to, prev.to);
1534 if (i <= mainIndex)
1535 mainIndex--;
1536 ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
1537 }
1538 }
1539 return new EditorSelection(ranges, mainIndex);
1540 }
1541 }
1542 function checkSelection(selection, docLength) {
1543 for (let range of selection.ranges)
1544 if (range.to > docLength)
1545 throw new RangeError("Selection points outside of document");
1546 }
1547
1548 let nextID = 0;
1549 /**
1550 A facet is a labeled value that is associated with an editor
1551 state. It takes inputs from any number of extensions, and combines
1552 those into a single output value.
1553
1554 Examples of uses of facets are the [tab
1555 size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
1556 attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
1557 listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
1558 */
1559 class Facet {
1560 constructor(
1561 /**
1562 @internal
1563 */
1564 combine,
1565 /**
1566 @internal
1567 */
1568 compareInput,
1569 /**
1570 @internal
1571 */
1572 compare, isStatic, enables) {
1573 this.combine = combine;
1574 this.compareInput = compareInput;
1575 this.compare = compare;
1576 this.isStatic = isStatic;
1577 /**
1578 @internal
1579 */
1580 this.id = nextID++;
1581 this.default = combine([]);
1582 this.extensions = typeof enables == "function" ? enables(this) : enables;
1583 }
1584 /**
1585 Define a new facet.
1586 */
1587 static define(config = {}) {
1588 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);
1589 }
1590 /**
1591 Returns an extension that adds the given value to this facet.
1592 */
1593 of(value) {
1594 return new FacetProvider([], this, 0 /* Provider.Static */, value);
1595 }
1596 /**
1597 Create an extension that computes a value for the facet from a
1598 state. You must take care to declare the parts of the state that
1599 this value depends on, since your function is only called again
1600 for a new state when one of those parts changed.
1601
1602 In cases where your value depends only on a single field, you'll
1603 want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
1604 */
1605 compute(deps, get) {
1606 if (this.isStatic)
1607 throw new Error("Can't compute a static facet");
1608 return new FacetProvider(deps, this, 1 /* Provider.Single */, get);
1609 }
1610 /**
1611 Create an extension that computes zero or more values for this
1612 facet from a state.
1613 */
1614 computeN(deps, get) {
1615 if (this.isStatic)
1616 throw new Error("Can't compute a static facet");
1617 return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);
1618 }
1619 from(field, get) {
1620 if (!get)
1621 get = x => x;
1622 return this.compute([field], state => get(state.field(field)));
1623 }
1624 }
1625 function sameArray$1(a, b) {
1626 return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
1627 }
1628 class FacetProvider {
1629 constructor(dependencies, facet, type, value) {
1630 this.dependencies = dependencies;
1631 this.facet = facet;
1632 this.type = type;
1633 this.value = value;
1634 this.id = nextID++;
1635 }
1636 dynamicSlot(addresses) {
1637 var _a;
1638 let getter = this.value;
1639 let compare = this.facet.compareInput;
1640 let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;
1641 let depDoc = false, depSel = false, depAddrs = [];
1642 for (let dep of this.dependencies) {
1643 if (dep == "doc")
1644 depDoc = true;
1645 else if (dep == "selection")
1646 depSel = true;
1647 else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
1648 depAddrs.push(addresses[dep.id]);
1649 }
1650 return {
1651 create(state) {
1652 state.values[idx] = getter(state);
1653 return 1 /* SlotStatus.Changed */;
1654 },
1655 update(state, tr) {
1656 if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
1657 let newVal = getter(state);
1658 if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
1659 state.values[idx] = newVal;
1660 return 1 /* SlotStatus.Changed */;
1661 }
1662 }
1663 return 0;
1664 },
1665 reconfigure: (state, oldState) => {
1666 let newVal, oldAddr = oldState.config.address[id];
1667 if (oldAddr != null) {
1668 let oldVal = getAddr(oldState, oldAddr);
1669 if (this.dependencies.every(dep => {
1670 return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
1671 dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
1672 }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {
1673 state.values[idx] = oldVal;
1674 return 0;
1675 }
1676 }
1677 else {
1678 newVal = getter(state);
1679 }
1680 state.values[idx] = newVal;
1681 return 1 /* SlotStatus.Changed */;
1682 }
1683 };
1684 }
1685 }
1686 function compareArray(a, b, compare) {
1687 if (a.length != b.length)
1688 return false;
1689 for (let i = 0; i < a.length; i++)
1690 if (!compare(a[i], b[i]))
1691 return false;
1692 return true;
1693 }
1694 function ensureAll(state, addrs) {
1695 let changed = false;
1696 for (let addr of addrs)
1697 if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)
1698 changed = true;
1699 return changed;
1700 }
1701 function dynamicFacetSlot(addresses, facet, providers) {
1702 let providerAddrs = providers.map(p => addresses[p.id]);
1703 let providerTypes = providers.map(p => p.type);
1704 let dynamic = providerAddrs.filter(p => !(p & 1));
1705 let idx = addresses[facet.id] >> 1;
1706 function get(state) {
1707 let values = [];
1708 for (let i = 0; i < providerAddrs.length; i++) {
1709 let value = getAddr(state, providerAddrs[i]);
1710 if (providerTypes[i] == 2 /* Provider.Multi */)
1711 for (let val of value)
1712 values.push(val);
1713 else
1714 values.push(value);
1715 }
1716 return facet.combine(values);
1717 }
1718 return {
1719 create(state) {
1720 for (let addr of providerAddrs)
1721 ensureAddr(state, addr);
1722 state.values[idx] = get(state);
1723 return 1 /* SlotStatus.Changed */;
1724 },
1725 update(state, tr) {
1726 if (!ensureAll(state, dynamic))
1727 return 0;
1728 let value = get(state);
1729 if (facet.compare(value, state.values[idx]))
1730 return 0;
1731 state.values[idx] = value;
1732 return 1 /* SlotStatus.Changed */;
1733 },
1734 reconfigure(state, oldState) {
1735 let depChanged = ensureAll(state, providerAddrs);
1736 let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
1737 if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {
1738 state.values[idx] = oldValue;
1739 return 0;
1740 }
1741 let value = get(state);
1742 if (facet.compare(value, oldValue)) {
1743 state.values[idx] = oldValue;
1744 return 0;
1745 }
1746 state.values[idx] = value;
1747 return 1 /* SlotStatus.Changed */;
1748 }
1749 };
1750 }
1751 const initField = /*@__PURE__*/Facet.define({ static: true });
1752 /**
1753 Fields can store additional information in an editor state, and
1754 keep it in sync with the rest of the state.
1755 */
1756 class StateField {
1757 constructor(
1758 /**
1759 @internal
1760 */
1761 id, createF, updateF, compareF,
1762 /**
1763 @internal
1764 */
1765 spec) {
1766 this.id = id;
1767 this.createF = createF;
1768 this.updateF = updateF;
1769 this.compareF = compareF;
1770 this.spec = spec;
1771 /**
1772 @internal
1773 */
1774 this.provides = undefined;
1775 }
1776 /**
1777 Define a state field.
1778 */
1779 static define(config) {
1780 let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
1781 if (config.provide)
1782 field.provides = config.provide(field);
1783 return field;
1784 }
1785 create(state) {
1786 let init = state.facet(initField).find(i => i.field == this);
1787 return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
1788 }
1789 /**
1790 @internal
1791 */
1792 slot(addresses) {
1793 let idx = addresses[this.id] >> 1;
1794 return {
1795 create: (state) => {
1796 state.values[idx] = this.create(state);
1797 return 1 /* SlotStatus.Changed */;
1798 },
1799 update: (state, tr) => {
1800 let oldVal = state.values[idx];
1801 let value = this.updateF(oldVal, tr);
1802 if (this.compareF(oldVal, value))
1803 return 0;
1804 state.values[idx] = value;
1805 return 1 /* SlotStatus.Changed */;
1806 },
1807 reconfigure: (state, oldState) => {
1808 if (oldState.config.address[this.id] != null) {
1809 state.values[idx] = oldState.field(this);
1810 return 0;
1811 }
1812 state.values[idx] = this.create(state);
1813 return 1 /* SlotStatus.Changed */;
1814 }
1815 };
1816 }
1817 /**
1818 Returns an extension that enables this field and overrides the
1819 way it is initialized. Can be useful when you need to provide a
1820 non-default starting value for the field.
1821 */
1822 init(create) {
1823 return [this, initField.of({ field: this, create })];
1824 }
1825 /**
1826 State field instances can be used as
1827 [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
1828 given state.
1829 */
1830 get extension() { return this; }
1831 }
1832 const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
1833 function prec(value) {
1834 return (ext) => new PrecExtension(ext, value);
1835 }
1836 /**
1837 By default extensions are registered in the order they are found
1838 in the flattened form of nested array that was provided.
1839 Individual extension values can be assigned a precedence to
1840 override this. Extensions that do not have a precedence set get
1841 the precedence of the nearest parent with a precedence, or
1842 [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
1843 final ordering of extensions is determined by first sorting by
1844 precedence and then by order within each precedence.
1845 */
1846 const Prec = {
1847 /**
1848 The highest precedence level, for extensions that should end up
1849 near the start of the precedence ordering.
1850 */
1851 highest: /*@__PURE__*/prec(Prec_.highest),
1852 /**
1853 A higher-than-default precedence, for extensions that should
1854 come before those with default precedence.
1855 */
1856 high: /*@__PURE__*/prec(Prec_.high),
1857 /**
1858 The default precedence, which is also used for extensions
1859 without an explicit precedence.
1860 */
1861 default: /*@__PURE__*/prec(Prec_.default),
1862 /**
1863 A lower-than-default precedence.
1864 */
1865 low: /*@__PURE__*/prec(Prec_.low),
1866 /**
1867 The lowest precedence level. Meant for things that should end up
1868 near the end of the extension order.
1869 */
1870 lowest: /*@__PURE__*/prec(Prec_.lowest)
1871 };
1872 class PrecExtension {
1873 constructor(inner, prec) {
1874 this.inner = inner;
1875 this.prec = prec;
1876 }
1877 }
1878 /**
1879 Extension compartments can be used to make a configuration
1880 dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
1881 configuration in a compartment, you can later
1882 [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
1883 transaction.
1884 */
1885 class Compartment {
1886 /**
1887 Create an instance of this compartment to add to your [state
1888 configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
1889 */
1890 of(ext) { return new CompartmentInstance(this, ext); }
1891 /**
1892 Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
1893 reconfigures this compartment.
1894 */
1895 reconfigure(content) {
1896 return Compartment.reconfigure.of({ compartment: this, extension: content });
1897 }
1898 /**
1899 Get the current content of the compartment in the state, or
1900 `undefined` if it isn't present.
1901 */
1902 get(state) {
1903 return state.config.compartments.get(this);
1904 }
1905 }
1906 class CompartmentInstance {
1907 constructor(compartment, inner) {
1908 this.compartment = compartment;
1909 this.inner = inner;
1910 }
1911 }
1912 class Configuration {
1913 constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
1914 this.base = base;
1915 this.compartments = compartments;
1916 this.dynamicSlots = dynamicSlots;
1917 this.address = address;
1918 this.staticValues = staticValues;
1919 this.facets = facets;
1920 this.statusTemplate = [];
1921 while (this.statusTemplate.length < dynamicSlots.length)
1922 this.statusTemplate.push(0 /* SlotStatus.Unresolved */);
1923 }
1924 staticFacet(facet) {
1925 let addr = this.address[facet.id];
1926 return addr == null ? facet.default : this.staticValues[addr >> 1];
1927 }
1928 static resolve(base, compartments, oldState) {
1929 let fields = [];
1930 let facets = Object.create(null);
1931 let newCompartments = new Map();
1932 for (let ext of flatten(base, compartments, newCompartments)) {
1933 if (ext instanceof StateField)
1934 fields.push(ext);
1935 else
1936 (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
1937 }
1938 let address = Object.create(null);
1939 let staticValues = [];
1940 let dynamicSlots = [];
1941 for (let field of fields) {
1942 address[field.id] = dynamicSlots.length << 1;
1943 dynamicSlots.push(a => field.slot(a));
1944 }
1945 let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
1946 for (let id in facets) {
1947 let providers = facets[id], facet = providers[0].facet;
1948 let oldProviders = oldFacets && oldFacets[id] || [];
1949 if (providers.every(p => p.type == 0 /* Provider.Static */)) {
1950 address[facet.id] = (staticValues.length << 1) | 1;
1951 if (sameArray$1(oldProviders, providers)) {
1952 staticValues.push(oldState.facet(facet));
1953 }
1954 else {
1955 let value = facet.combine(providers.map(p => p.value));
1956 staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
1957 }
1958 }
1959 else {
1960 for (let p of providers) {
1961 if (p.type == 0 /* Provider.Static */) {
1962 address[p.id] = (staticValues.length << 1) | 1;
1963 staticValues.push(p.value);
1964 }
1965 else {
1966 address[p.id] = dynamicSlots.length << 1;
1967 dynamicSlots.push(a => p.dynamicSlot(a));
1968 }
1969 }
1970 address[facet.id] = dynamicSlots.length << 1;
1971 dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
1972 }
1973 }
1974 let dynamic = dynamicSlots.map(f => f(address));
1975 return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
1976 }
1977 }
1978 function flatten(extension, compartments, newCompartments) {
1979 let result = [[], [], [], [], []];
1980 let seen = new Map();
1981 function inner(ext, prec) {
1982 let known = seen.get(ext);
1983 if (known != null) {
1984 if (known <= prec)
1985 return;
1986 let found = result[known].indexOf(ext);
1987 if (found > -1)
1988 result[known].splice(found, 1);
1989 if (ext instanceof CompartmentInstance)
1990 newCompartments.delete(ext.compartment);
1991 }
1992 seen.set(ext, prec);
1993 if (Array.isArray(ext)) {
1994 for (let e of ext)
1995 inner(e, prec);
1996 }
1997 else if (ext instanceof CompartmentInstance) {
1998 if (newCompartments.has(ext.compartment))
1999 throw new RangeError(`Duplicate use of compartment in extensions`);
2000 let content = compartments.get(ext.compartment) || ext.inner;
2001 newCompartments.set(ext.compartment, content);
2002 inner(content, prec);
2003 }
2004 else if (ext instanceof PrecExtension) {
2005 inner(ext.inner, ext.prec);
2006 }
2007 else if (ext instanceof StateField) {
2008 result[prec].push(ext);
2009 if (ext.provides)
2010 inner(ext.provides, prec);
2011 }
2012 else if (ext instanceof FacetProvider) {
2013 result[prec].push(ext);
2014 if (ext.facet.extensions)
2015 inner(ext.facet.extensions, Prec_.default);
2016 }
2017 else {
2018 let content = ext.extension;
2019 if (!content)
2020 throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
2021 inner(content, prec);
2022 }
2023 }
2024 inner(extension, Prec_.default);
2025 return result.reduce((a, b) => a.concat(b));
2026 }
2027 function ensureAddr(state, addr) {
2028 if (addr & 1)
2029 return 2 /* SlotStatus.Computed */;
2030 let idx = addr >> 1;
2031 let status = state.status[idx];
2032 if (status == 4 /* SlotStatus.Computing */)
2033 throw new Error("Cyclic dependency between fields and/or facets");
2034 if (status & 2 /* SlotStatus.Computed */)
2035 return status;
2036 state.status[idx] = 4 /* SlotStatus.Computing */;
2037 let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
2038 return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;
2039 }
2040 function getAddr(state, addr) {
2041 return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
2042 }
2043
2044 const languageData = /*@__PURE__*/Facet.define();
2045 const allowMultipleSelections = /*@__PURE__*/Facet.define({
2046 combine: values => values.some(v => v),
2047 static: true
2048 });
2049 const lineSeparator = /*@__PURE__*/Facet.define({
2050 combine: values => values.length ? values[0] : undefined,
2051 static: true
2052 });
2053 const changeFilter = /*@__PURE__*/Facet.define();
2054 const transactionFilter = /*@__PURE__*/Facet.define();
2055 const transactionExtender = /*@__PURE__*/Facet.define();
2056 const readOnly = /*@__PURE__*/Facet.define({
2057 combine: values => values.length ? values[0] : false
2058 });
2059
2060 /**
2061 Annotations are tagged values that are used to add metadata to
2062 transactions in an extensible way. They should be used to model
2063 things that effect the entire transaction (such as its [time
2064 stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
2065 [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
2066 _alongside_ the other changes made by the transaction, [state
2067 effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
2068 */
2069 class Annotation {
2070 /**
2071 @internal
2072 */
2073 constructor(
2074 /**
2075 The annotation type.
2076 */
2077 type,
2078 /**
2079 The value of this annotation.
2080 */
2081 value) {
2082 this.type = type;
2083 this.value = value;
2084 }
2085 /**
2086 Define a new type of annotation.
2087 */
2088 static define() { return new AnnotationType(); }
2089 }
2090 /**
2091 Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
2092 */
2093 class AnnotationType {
2094 /**
2095 Create an instance of this annotation.
2096 */
2097 of(value) { return new Annotation(this, value); }
2098 }
2099 /**
2100 Representation of a type of state effect. Defined with
2101 [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
2102 */
2103 class StateEffectType {
2104 /**
2105 @internal
2106 */
2107 constructor(
2108 // The `any` types in these function types are there to work
2109 // around TypeScript issue #37631, where the type guard on
2110 // `StateEffect.is` mysteriously stops working when these properly
2111 // have type `Value`.
2112 /**
2113 @internal
2114 */
2115 map) {
2116 this.map = map;
2117 }
2118 /**
2119 Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
2120 type.
2121 */
2122 of(value) { return new StateEffect(this, value); }
2123 }
2124 /**
2125 State effects can be used to represent additional effects
2126 associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
2127 are often useful to model changes to custom [state
2128 fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
2129 document or selection changes.
2130 */
2131 class StateEffect {
2132 /**
2133 @internal
2134 */
2135 constructor(
2136 /**
2137 @internal
2138 */
2139 type,
2140 /**
2141 The value of this effect.
2142 */
2143 value) {
2144 this.type = type;
2145 this.value = value;
2146 }
2147 /**
2148 Map this effect through a position mapping. Will return
2149 `undefined` when that ends up deleting the effect.
2150 */
2151 map(mapping) {
2152 let mapped = this.type.map(this.value, mapping);
2153 return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
2154 }
2155 /**
2156 Tells you whether this effect object is of a given
2157 [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
2158 */
2159 is(type) { return this.type == type; }
2160 /**
2161 Define a new effect type. The type parameter indicates the type
2162 of values that his effect holds. It should be a type that
2163 doesn't include `undefined`, since that is used in
2164 [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
2165 removed.
2166 */
2167 static define(spec = {}) {
2168 return new StateEffectType(spec.map || (v => v));
2169 }
2170 /**
2171 Map an array of effects through a change set.
2172 */
2173 static mapEffects(effects, mapping) {
2174 if (!effects.length)
2175 return effects;
2176 let result = [];
2177 for (let effect of effects) {
2178 let mapped = effect.map(mapping);
2179 if (mapped)
2180 result.push(mapped);
2181 }
2182 return result;
2183 }
2184 }
2185 /**
2186 This effect can be used to reconfigure the root extensions of
2187 the editor. Doing this will discard any extensions
2188 [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
2189 the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
2190 compartments.
2191 */
2192 StateEffect.reconfigure = /*@__PURE__*/StateEffect.define();
2193 /**
2194 Append extensions to the top-level configuration of the editor.
2195 */
2196 StateEffect.appendConfig = /*@__PURE__*/StateEffect.define();
2197 /**
2198 Changes to the editor state are grouped into transactions.
2199 Typically, a user action creates a single transaction, which may
2200 contain any number of document changes, may change the selection,
2201 or have other effects. Create a transaction by calling
2202 [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
2203 dispatch one by calling
2204 [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
2205 */
2206 class Transaction {
2207 constructor(
2208 /**
2209 The state from which the transaction starts.
2210 */
2211 startState,
2212 /**
2213 The document changes made by this transaction.
2214 */
2215 changes,
2216 /**
2217 The selection set by this transaction, or undefined if it
2218 doesn't explicitly set a selection.
2219 */
2220 selection,
2221 /**
2222 The effects added to the transaction.
2223 */
2224 effects,
2225 /**
2226 @internal
2227 */
2228 annotations,
2229 /**
2230 Whether the selection should be scrolled into view after this
2231 transaction is dispatched.
2232 */
2233 scrollIntoView) {
2234 this.startState = startState;
2235 this.changes = changes;
2236 this.selection = selection;
2237 this.effects = effects;
2238 this.annotations = annotations;
2239 this.scrollIntoView = scrollIntoView;
2240 /**
2241 @internal
2242 */
2243 this._doc = null;
2244 /**
2245 @internal
2246 */
2247 this._state = null;
2248 if (selection)
2249 checkSelection(selection, changes.newLength);
2250 if (!annotations.some((a) => a.type == Transaction.time))
2251 this.annotations = annotations.concat(Transaction.time.of(Date.now()));
2252 }
2253 /**
2254 @internal
2255 */
2256 static create(startState, changes, selection, effects, annotations, scrollIntoView) {
2257 return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
2258 }
2259 /**
2260 The new document produced by the transaction. Contrary to
2261 [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
2262 force the entire new state to be computed right away, so it is
2263 recommended that [transaction
2264 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
2265 when they need to look at the new document.
2266 */
2267 get newDoc() {
2268 return this._doc || (this._doc = this.changes.apply(this.startState.doc));
2269 }
2270 /**
2271 The new selection produced by the transaction. If
2272 [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
2273 this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
2274 current selection through the changes made by the transaction.
2275 */
2276 get newSelection() {
2277 return this.selection || this.startState.selection.map(this.changes);
2278 }
2279 /**
2280 The new state created by the transaction. Computed on demand
2281 (but retained for subsequent access), so it is recommended not to
2282 access it in [transaction
2283 filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
2284 */
2285 get state() {
2286 if (!this._state)
2287 this.startState.applyTransaction(this);
2288 return this._state;
2289 }
2290 /**
2291 Get the value of the given annotation type, if any.
2292 */
2293 annotation(type) {
2294 for (let ann of this.annotations)
2295 if (ann.type == type)
2296 return ann.value;
2297 return undefined;
2298 }
2299 /**
2300 Indicates whether the transaction changed the document.
2301 */
2302 get docChanged() { return !this.changes.empty; }
2303 /**
2304 Indicates whether this transaction reconfigures the state
2305 (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
2306 with a top-level configuration
2307 [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
2308 */
2309 get reconfigured() { return this.startState.config != this.state.config; }
2310 /**
2311 Returns true if the transaction has a [user
2312 event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
2313 or more specific than `event`. For example, if the transaction
2314 has `"select.pointer"` as user event, `"select"` and
2315 `"select.pointer"` will match it.
2316 */
2317 isUserEvent(event) {
2318 let e = this.annotation(Transaction.userEvent);
2319 return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
2320 }
2321 }
2322 /**
2323 Annotation used to store transaction timestamps. Automatically
2324 added to every transaction, holding `Date.now()`.
2325 */
2326 Transaction.time = /*@__PURE__*/Annotation.define();
2327 /**
2328 Annotation used to associate a transaction with a user interface
2329 event. Holds a string identifying the event, using a
2330 dot-separated format to support attaching more specific
2331 information. The events used by the core libraries are:
2332
2333 - `"input"` when content is entered
2334 - `"input.type"` for typed input
2335 - `"input.type.compose"` for composition
2336 - `"input.paste"` for pasted input
2337 - `"input.drop"` when adding content with drag-and-drop
2338 - `"input.complete"` when autocompleting
2339 - `"delete"` when the user deletes content
2340 - `"delete.selection"` when deleting the selection
2341 - `"delete.forward"` when deleting forward from the selection
2342 - `"delete.backward"` when deleting backward from the selection
2343 - `"delete.cut"` when cutting to the clipboard
2344 - `"move"` when content is moved
2345 - `"move.drop"` when content is moved within the editor through drag-and-drop
2346 - `"select"` when explicitly changing the selection
2347 - `"select.pointer"` when selecting with a mouse or other pointing device
2348 - `"undo"` and `"redo"` for history actions
2349
2350 Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
2351 whether the annotation matches a given event.
2352 */
2353 Transaction.userEvent = /*@__PURE__*/Annotation.define();
2354 /**
2355 Annotation indicating whether a transaction should be added to
2356 the undo history or not.
2357 */
2358 Transaction.addToHistory = /*@__PURE__*/Annotation.define();
2359 /**
2360 Annotation indicating (when present and true) that a transaction
2361 represents a change made by some other actor, not the user. This
2362 is used, for example, to tag other people's changes in
2363 collaborative editing.
2364 */
2365 Transaction.remote = /*@__PURE__*/Annotation.define();
2366 function joinRanges(a, b) {
2367 let result = [];
2368 for (let iA = 0, iB = 0;;) {
2369 let from, to;
2370 if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
2371 from = a[iA++];
2372 to = a[iA++];
2373 }
2374 else if (iB < b.length) {
2375 from = b[iB++];
2376 to = b[iB++];
2377 }
2378 else
2379 return result;
2380 if (!result.length || result[result.length - 1] < from)
2381 result.push(from, to);
2382 else if (result[result.length - 1] < to)
2383 result[result.length - 1] = to;
2384 }
2385 }
2386 function mergeTransaction(a, b, sequential) {
2387 var _a;
2388 let mapForA, mapForB, changes;
2389 if (sequential) {
2390 mapForA = b.changes;
2391 mapForB = ChangeSet.empty(b.changes.length);
2392 changes = a.changes.compose(b.changes);
2393 }
2394 else {
2395 mapForA = b.changes.map(a.changes);
2396 mapForB = a.changes.mapDesc(b.changes, true);
2397 changes = a.changes.compose(mapForA);
2398 }
2399 return {
2400 changes,
2401 selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
2402 effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
2403 annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
2404 scrollIntoView: a.scrollIntoView || b.scrollIntoView
2405 };
2406 }
2407 function resolveTransactionInner(state, spec, docSize) {
2408 let sel = spec.selection, annotations = asArray$1(spec.annotations);
2409 if (spec.userEvent)
2410 annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
2411 return {
2412 changes: spec.changes instanceof ChangeSet ? spec.changes
2413 : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
2414 selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
2415 effects: asArray$1(spec.effects),
2416 annotations,
2417 scrollIntoView: !!spec.scrollIntoView
2418 };
2419 }
2420 function resolveTransaction(state, specs, filter) {
2421 let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
2422 if (specs.length && specs[0].filter === false)
2423 filter = false;
2424 for (let i = 1; i < specs.length; i++) {
2425 if (specs[i].filter === false)
2426 filter = false;
2427 let seq = !!specs[i].sequential;
2428 s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
2429 }
2430 let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
2431 return extendTransaction(filter ? filterTransaction(tr) : tr);
2432 }
2433 // Finish a transaction by applying filters if necessary.
2434 function filterTransaction(tr) {
2435 let state = tr.startState;
2436 // Change filters
2437 let result = true;
2438 for (let filter of state.facet(changeFilter)) {
2439 let value = filter(tr);
2440 if (value === false) {
2441 result = false;
2442 break;
2443 }
2444 if (Array.isArray(value))
2445 result = result === true ? value : joinRanges(result, value);
2446 }
2447 if (result !== true) {
2448 let changes, back;
2449 if (result === false) {
2450 back = tr.changes.invertedDesc;
2451 changes = ChangeSet.empty(state.doc.length);
2452 }
2453 else {
2454 let filtered = tr.changes.filter(result);
2455 changes = filtered.changes;
2456 back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
2457 }
2458 tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
2459 }
2460 // Transaction filters
2461 let filters = state.facet(transactionFilter);
2462 for (let i = filters.length - 1; i >= 0; i--) {
2463 let filtered = filters[i](tr);
2464 if (filtered instanceof Transaction)
2465 tr = filtered;
2466 else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
2467 tr = filtered[0];
2468 else
2469 tr = resolveTransaction(state, asArray$1(filtered), false);
2470 }
2471 return tr;
2472 }
2473 function extendTransaction(tr) {
2474 let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
2475 for (let i = extenders.length - 1; i >= 0; i--) {
2476 let extension = extenders[i](tr);
2477 if (extension && Object.keys(extension).length)
2478 spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
2479 }
2480 return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
2481 }
2482 const none$1 = [];
2483 function asArray$1(value) {
2484 return value == null ? none$1 : Array.isArray(value) ? value : [value];
2485 }
2486
2487 /**
2488 The categories produced by a [character
2489 categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
2490 do things like selecting by word.
2491 */
2492 exports.CharCategory = /*@__PURE__*/(function (CharCategory) {
2493 /**
2494 Word characters.
2495 */
2496 CharCategory[CharCategory["Word"] = 0] = "Word";
2497 /**
2498 Whitespace.
2499 */
2500 CharCategory[CharCategory["Space"] = 1] = "Space";
2501 /**
2502 Anything else.
2503 */
2504 CharCategory[CharCategory["Other"] = 2] = "Other";
2505 return CharCategory})(exports.CharCategory || (exports.CharCategory = {}));
2506 const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
2507 let wordChar;
2508 try {
2509 wordChar = /*@__PURE__*/new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
2510 }
2511 catch (_) { }
2512 function hasWordChar(str) {
2513 if (wordChar)
2514 return wordChar.test(str);
2515 for (let i = 0; i < str.length; i++) {
2516 let ch = str[i];
2517 if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
2518 return true;
2519 }
2520 return false;
2521 }
2522 function makeCategorizer(wordChars) {
2523 return (char) => {
2524 if (!/\S/.test(char))
2525 return exports.CharCategory.Space;
2526 if (hasWordChar(char))
2527 return exports.CharCategory.Word;
2528 for (let i = 0; i < wordChars.length; i++)
2529 if (char.indexOf(wordChars[i]) > -1)
2530 return exports.CharCategory.Word;
2531 return exports.CharCategory.Other;
2532 };
2533 }
2534
2535 /**
2536 The editor state class is a persistent (immutable) data structure.
2537 To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
2538 [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
2539 instance, without modifying the original object.
2540
2541 As such, _never_ mutate properties of a state directly. That'll
2542 just break things.
2543 */
2544 class EditorState {
2545 constructor(
2546 /**
2547 @internal
2548 */
2549 config,
2550 /**
2551 The current document.
2552 */
2553 doc,
2554 /**
2555 The current selection.
2556 */
2557 selection,
2558 /**
2559 @internal
2560 */
2561 values, computeSlot, tr) {
2562 this.config = config;
2563 this.doc = doc;
2564 this.selection = selection;
2565 this.values = values;
2566 this.status = config.statusTemplate.slice();
2567 this.computeSlot = computeSlot;
2568 // Fill in the computed state immediately, so that further queries
2569 // for it made during the update return this state
2570 if (tr)
2571 tr._state = this;
2572 for (let i = 0; i < this.config.dynamicSlots.length; i++)
2573 ensureAddr(this, i << 1);
2574 this.computeSlot = null;
2575 }
2576 field(field, require = true) {
2577 let addr = this.config.address[field.id];
2578 if (addr == null) {
2579 if (require)
2580 throw new RangeError("Field is not present in this state");
2581 return undefined;
2582 }
2583 ensureAddr(this, addr);
2584 return getAddr(this, addr);
2585 }
2586 /**
2587 Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
2588 state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
2589 can be passed. Unless
2590 [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
2591 [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
2592 are assumed to start in the _current_ document (not the document
2593 produced by previous specs), and its
2594 [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
2595 [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
2596 to the document created by its _own_ changes. The resulting
2597 transaction contains the combined effect of all the different
2598 specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
2599 specs take precedence over earlier ones.
2600 */
2601 update(...specs) {
2602 return resolveTransaction(this, specs, true);
2603 }
2604 /**
2605 @internal
2606 */
2607 applyTransaction(tr) {
2608 let conf = this.config, { base, compartments } = conf;
2609 for (let effect of tr.effects) {
2610 if (effect.is(Compartment.reconfigure)) {
2611 if (conf) {
2612 compartments = new Map;
2613 conf.compartments.forEach((val, key) => compartments.set(key, val));
2614 conf = null;
2615 }
2616 compartments.set(effect.value.compartment, effect.value.extension);
2617 }
2618 else if (effect.is(StateEffect.reconfigure)) {
2619 conf = null;
2620 base = effect.value;
2621 }
2622 else if (effect.is(StateEffect.appendConfig)) {
2623 conf = null;
2624 base = asArray$1(base).concat(effect.value);
2625 }
2626 }
2627 let startValues;
2628 if (!conf) {
2629 conf = Configuration.resolve(base, compartments, this);
2630 let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
2631 startValues = intermediateState.values;
2632 }
2633 else {
2634 startValues = tr.startState.values.slice();
2635 }
2636 new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);
2637 }
2638 /**
2639 Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
2640 replaces every selection range with the given content.
2641 */
2642 replaceSelection(text) {
2643 if (typeof text == "string")
2644 text = this.toText(text);
2645 return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
2646 range: EditorSelection.cursor(range.from + text.length) }));
2647 }
2648 /**
2649 Create a set of changes and a new selection by running the given
2650 function for each range in the active selection. The function
2651 can return an optional set of changes (in the coordinate space
2652 of the start document), plus an updated range (in the coordinate
2653 space of the document produced by the call's own changes). This
2654 method will merge all the changes and ranges into a single
2655 changeset and selection, and return it as a [transaction
2656 spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
2657 [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
2658 */
2659 changeByRange(f) {
2660 let sel = this.selection;
2661 let result1 = f(sel.ranges[0]);
2662 let changes = this.changes(result1.changes), ranges = [result1.range];
2663 let effects = asArray$1(result1.effects);
2664 for (let i = 1; i < sel.ranges.length; i++) {
2665 let result = f(sel.ranges[i]);
2666 let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
2667 for (let j = 0; j < i; j++)
2668 ranges[j] = ranges[j].map(newMapped);
2669 let mapBy = changes.mapDesc(newChanges, true);
2670 ranges.push(result.range.map(mapBy));
2671 changes = changes.compose(newMapped);
2672 effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy));
2673 }
2674 return {
2675 changes,
2676 selection: EditorSelection.create(ranges, sel.mainIndex),
2677 effects
2678 };
2679 }
2680 /**
2681 Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
2682 description, taking the state's document length and line
2683 separator into account.
2684 */
2685 changes(spec = []) {
2686 if (spec instanceof ChangeSet)
2687 return spec;
2688 return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
2689 }
2690 /**
2691 Using the state's [line
2692 separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
2693 [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
2694 */
2695 toText(string) {
2696 return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
2697 }
2698 /**
2699 Return the given range of the document as a string.
2700 */
2701 sliceDoc(from = 0, to = this.doc.length) {
2702 return this.doc.sliceString(from, to, this.lineBreak);
2703 }
2704 /**
2705 Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
2706 */
2707 facet(facet) {
2708 let addr = this.config.address[facet.id];
2709 if (addr == null)
2710 return facet.default;
2711 ensureAddr(this, addr);
2712 return getAddr(this, addr);
2713 }
2714 /**
2715 Convert this state to a JSON-serializable object. When custom
2716 fields should be serialized, you can pass them in as an object
2717 mapping property names (in the resulting object, which should
2718 not use `doc` or `selection`) to fields.
2719 */
2720 toJSON(fields) {
2721 let result = {
2722 doc: this.sliceDoc(),
2723 selection: this.selection.toJSON()
2724 };
2725 if (fields)
2726 for (let prop in fields) {
2727 let value = fields[prop];
2728 if (value instanceof StateField && this.config.address[value.id] != null)
2729 result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
2730 }
2731 return result;
2732 }
2733 /**
2734 Deserialize a state from its JSON representation. When custom
2735 fields should be deserialized, pass the same object you passed
2736 to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
2737 third argument.
2738 */
2739 static fromJSON(json, config = {}, fields) {
2740 if (!json || typeof json.doc != "string")
2741 throw new RangeError("Invalid JSON representation for EditorState");
2742 let fieldInit = [];
2743 if (fields)
2744 for (let prop in fields) {
2745 if (Object.prototype.hasOwnProperty.call(json, prop)) {
2746 let field = fields[prop], value = json[prop];
2747 fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
2748 }
2749 }
2750 return EditorState.create({
2751 doc: json.doc,
2752 selection: EditorSelection.fromJSON(json.selection),
2753 extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
2754 });
2755 }
2756 /**
2757 Create a new state. You'll usually only need this when
2758 initializing an editor—updated states are created by applying
2759 transactions.
2760 */
2761 static create(config = {}) {
2762 let configuration = Configuration.resolve(config.extensions || [], new Map);
2763 let doc = config.doc instanceof Text ? config.doc
2764 : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
2765 let selection = !config.selection ? EditorSelection.single(0)
2766 : config.selection instanceof EditorSelection ? config.selection
2767 : EditorSelection.single(config.selection.anchor, config.selection.head);
2768 checkSelection(selection, doc.length);
2769 if (!configuration.staticFacet(allowMultipleSelections))
2770 selection = selection.asSingle();
2771 return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
2772 }
2773 /**
2774 The size (in columns) of a tab in the document, determined by
2775 the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
2776 */
2777 get tabSize() { return this.facet(EditorState.tabSize); }
2778 /**
2779 Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
2780 string for this state.
2781 */
2782 get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
2783 /**
2784 Returns true when the editor is
2785 [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
2786 */
2787 get readOnly() { return this.facet(readOnly); }
2788 /**
2789 Look up a translation for the given phrase (via the
2790 [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
2791 original string if no translation is found.
2792
2793 If additional arguments are passed, they will be inserted in
2794 place of markers like `$1` (for the first value) and `$2`, etc.
2795 A single `$` is equivalent to `$1`, and `$$` will produce a
2796 literal dollar sign.
2797 */
2798 phrase(phrase, ...insert) {
2799 for (let map of this.facet(EditorState.phrases))
2800 if (Object.prototype.hasOwnProperty.call(map, phrase)) {
2801 phrase = map[phrase];
2802 break;
2803 }
2804 if (insert.length)
2805 phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
2806 if (i == "$")
2807 return "$";
2808 let n = +(i || 1);
2809 return !n || n > insert.length ? m : insert[n - 1];
2810 });
2811 return phrase;
2812 }
2813 /**
2814 Find the values for a given language data field, provided by the
2815 the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
2816
2817 Examples of language data fields are...
2818
2819 - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
2820 comment syntax.
2821 - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
2822 for providing language-specific completion sources.
2823 - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
2824 characters that should be considered part of words in this
2825 language.
2826 - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
2827 bracket closing behavior.
2828 */
2829 languageDataAt(name, pos, side = -1) {
2830 let values = [];
2831 for (let provider of this.facet(languageData)) {
2832 for (let result of provider(this, pos, side)) {
2833 if (Object.prototype.hasOwnProperty.call(result, name))
2834 values.push(result[name]);
2835 }
2836 }
2837 return values;
2838 }
2839 /**
2840 Return a function that can categorize strings (expected to
2841 represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
2842 into one of:
2843
2844 - Word (contains an alphanumeric character or a character
2845 explicitly listed in the local language's `"wordChars"`
2846 language data, which should be a string)
2847 - Space (contains only whitespace)
2848 - Other (anything else)
2849 */
2850 charCategorizer(at) {
2851 return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
2852 }
2853 /**
2854 Find the word at the given position, meaning the range
2855 containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
2856 around it. If no word characters are adjacent to the position,
2857 this returns null.
2858 */
2859 wordAt(pos) {
2860 let { text, from, length } = this.doc.lineAt(pos);
2861 let cat = this.charCategorizer(pos);
2862 let start = pos - from, end = pos - from;
2863 while (start > 0) {
2864 let prev = findClusterBreak(text, start, false);
2865 if (cat(text.slice(prev, start)) != exports.CharCategory.Word)
2866 break;
2867 start = prev;
2868 }
2869 while (end < length) {
2870 let next = findClusterBreak(text, end);
2871 if (cat(text.slice(end, next)) != exports.CharCategory.Word)
2872 break;
2873 end = next;
2874 }
2875 return start == end ? null : EditorSelection.range(start + from, end + from);
2876 }
2877 }
2878 /**
2879 A facet that, when enabled, causes the editor to allow multiple
2880 ranges to be selected. Be careful though, because by default the
2881 editor relies on the native DOM selection, which cannot handle
2882 multiple selections. An extension like
2883 [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
2884 secondary selections visible to the user.
2885 */
2886 EditorState.allowMultipleSelections = allowMultipleSelections;
2887 /**
2888 Configures the tab size to use in this state. The first
2889 (highest-precedence) value of the facet is used. If no value is
2890 given, this defaults to 4.
2891 */
2892 EditorState.tabSize = /*@__PURE__*/Facet.define({
2893 combine: values => values.length ? values[0] : 4
2894 });
2895 /**
2896 The line separator to use. By default, any of `"\n"`, `"\r\n"`
2897 and `"\r"` is treated as a separator when splitting lines, and
2898 lines are joined with `"\n"`.
2899
2900 When you configure a value here, only that precise separator
2901 will be used, allowing you to round-trip documents through the
2902 editor without normalizing line separators.
2903 */
2904 EditorState.lineSeparator = lineSeparator;
2905 /**
2906 This facet controls the value of the
2907 [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
2908 consulted by commands and extensions that implement editing
2909 functionality to determine whether they should apply. It
2910 defaults to false, but when its highest-precedence value is
2911 `true`, such functionality disables itself.
2912
2913 Not to be confused with
2914 [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
2915 controls whether the editor's DOM is set to be editable (and
2916 thus focusable).
2917 */
2918 EditorState.readOnly = readOnly;
2919 /**
2920 Registers translation phrases. The
2921 [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
2922 all objects registered with this facet to find translations for
2923 its argument.
2924 */
2925 EditorState.phrases = /*@__PURE__*/Facet.define({
2926 compare(a, b) {
2927 let kA = Object.keys(a), kB = Object.keys(b);
2928 return kA.length == kB.length && kA.every(k => a[k] == b[k]);
2929 }
2930 });
2931 /**
2932 A facet used to register [language
2933 data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
2934 */
2935 EditorState.languageData = languageData;
2936 /**
2937 Facet used to register change filters, which are called for each
2938 transaction (unless explicitly
2939 [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
2940 part of the transaction's changes.
2941
2942 Such a function can return `true` to indicate that it doesn't
2943 want to do anything, `false` to completely stop the changes in
2944 the transaction, or a set of ranges in which changes should be
2945 suppressed. Such ranges are represented as an array of numbers,
2946 with each pair of two numbers indicating the start and end of a
2947 range. So for example `[10, 20, 100, 110]` suppresses changes
2948 between 10 and 20, and between 100 and 110.
2949 */
2950 EditorState.changeFilter = changeFilter;
2951 /**
2952 Facet used to register a hook that gets a chance to update or
2953 replace transaction specs before they are applied. This will
2954 only be applied for transactions that don't have
2955 [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
2956 can either return a single transaction spec (possibly the input
2957 transaction), or an array of specs (which will be combined in
2958 the same way as the arguments to
2959 [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
2960
2961 When possible, it is recommended to avoid accessing
2962 [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
2963 since it will force creation of a state that will then be
2964 discarded again, if the transaction is actually filtered.
2965
2966 (This functionality should be used with care. Indiscriminately
2967 modifying transaction is likely to break something or degrade
2968 the user experience.)
2969 */
2970 EditorState.transactionFilter = transactionFilter;
2971 /**
2972 This is a more limited form of
2973 [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
2974 which can only add
2975 [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
2976 [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
2977 of filter runs even if the transaction has disabled regular
2978 [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
2979 for effects that don't need to touch the changes or selection,
2980 but do want to process every transaction.
2981
2982 Extenders run _after_ filters, when both are present.
2983 */
2984 EditorState.transactionExtender = transactionExtender;
2985 Compartment.reconfigure = /*@__PURE__*/StateEffect.define();
2986
2987 /**
2988 Utility function for combining behaviors to fill in a config
2989 object from an array of provided configs. `defaults` should hold
2990 default values for all optional fields in `Config`.
2991
2992 The function will, by default, error
2993 when a field gets two values that aren't `===`-equal, but you can
2994 provide combine functions per field to do something else.
2995 */
2996 function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
2997 combine = {}) {
2998 let result = {};
2999 for (let config of configs)
3000 for (let key of Object.keys(config)) {
3001 let value = config[key], current = result[key];
3002 if (current === undefined)
3003 result[key] = value;
3004 else if (current === value || value === undefined) ; // No conflict
3005 else if (Object.hasOwnProperty.call(combine, key))
3006 result[key] = combine[key](current, value);
3007 else
3008 throw new Error("Config merge conflict for field " + key);
3009 }
3010 for (let key in defaults)
3011 if (result[key] === undefined)
3012 result[key] = defaults[key];
3013 return result;
3014 }
3015
3016 /**
3017 Each range is associated with a value, which must inherit from
3018 this class.
3019 */
3020 class RangeValue {
3021 /**
3022 Compare this value with another value. Used when comparing
3023 rangesets. The default implementation compares by identity.
3024 Unless you are only creating a fixed number of unique instances
3025 of your value type, it is a good idea to implement this
3026 properly.
3027 */
3028 eq(other) { return this == other; }
3029 /**
3030 Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
3031 */
3032 range(from, to = from) { return Range$1.create(from, to, this); }
3033 }
3034 RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
3035 RangeValue.prototype.point = false;
3036 RangeValue.prototype.mapMode = exports.MapMode.TrackDel;
3037 /**
3038 A range associates a value with a range of positions.
3039 */
3040 let Range$1 = class Range {
3041 constructor(
3042 /**
3043 The range's start position.
3044 */
3045 from,
3046 /**
3047 Its end position.
3048 */
3049 to,
3050 /**
3051 The value associated with this range.
3052 */
3053 value) {
3054 this.from = from;
3055 this.to = to;
3056 this.value = value;
3057 }
3058 /**
3059 @internal
3060 */
3061 static create(from, to, value) {
3062 return new Range(from, to, value);
3063 }
3064 };
3065 function cmpRange(a, b) {
3066 return a.from - b.from || a.value.startSide - b.value.startSide;
3067 }
3068 class Chunk {
3069 constructor(from, to, value,
3070 // Chunks are marked with the largest point that occurs
3071 // in them (or -1 for no points), so that scans that are
3072 // only interested in points (such as the
3073 // heightmap-related logic) can skip range-only chunks.
3074 maxPoint) {
3075 this.from = from;
3076 this.to = to;
3077 this.value = value;
3078 this.maxPoint = maxPoint;
3079 }
3080 get length() { return this.to[this.to.length - 1]; }
3081 // Find the index of the given position and side. Use the ranges'
3082 // `from` pos when `end == false`, `to` when `end == true`.
3083 findIndex(pos, side, end, startAt = 0) {
3084 let arr = end ? this.to : this.from;
3085 for (let lo = startAt, hi = arr.length;;) {
3086 if (lo == hi)
3087 return lo;
3088 let mid = (lo + hi) >> 1;
3089 let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
3090 if (mid == lo)
3091 return diff >= 0 ? lo : hi;
3092 if (diff >= 0)
3093 hi = mid;
3094 else
3095 lo = mid + 1;
3096 }
3097 }
3098 between(offset, from, to, f) {
3099 for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)
3100 if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
3101 return false;
3102 }
3103 map(offset, changes) {
3104 let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
3105 for (let i = 0; i < this.value.length; i++) {
3106 let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
3107 if (curFrom == curTo) {
3108 let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
3109 if (mapped == null)
3110 continue;
3111 newFrom = newTo = mapped;
3112 if (val.startSide != val.endSide) {
3113 newTo = changes.mapPos(curFrom, val.endSide);
3114 if (newTo < newFrom)
3115 continue;
3116 }
3117 }
3118 else {
3119 newFrom = changes.mapPos(curFrom, val.startSide);
3120 newTo = changes.mapPos(curTo, val.endSide);
3121 if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
3122 continue;
3123 }
3124 if ((newTo - newFrom || val.endSide - val.startSide) < 0)
3125 continue;
3126 if (newPos < 0)
3127 newPos = newFrom;
3128 if (val.point)
3129 maxPoint = Math.max(maxPoint, newTo - newFrom);
3130 value.push(val);
3131 from.push(newFrom - newPos);
3132 to.push(newTo - newPos);
3133 }
3134 return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
3135 }
3136 }
3137 /**
3138 A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
3139 way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
3140 [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
3141 structure.
3142 */
3143 class RangeSet {
3144 constructor(
3145 /**
3146 @internal
3147 */
3148 chunkPos,
3149 /**
3150 @internal
3151 */
3152 chunk,
3153 /**
3154 @internal
3155 */
3156 nextLayer,
3157 /**
3158 @internal
3159 */
3160 maxPoint) {
3161 this.chunkPos = chunkPos;
3162 this.chunk = chunk;
3163 this.nextLayer = nextLayer;
3164 this.maxPoint = maxPoint;
3165 }
3166 /**
3167 @internal
3168 */
3169 static create(chunkPos, chunk, nextLayer, maxPoint) {
3170 return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
3171 }
3172 /**
3173 @internal
3174 */
3175 get length() {
3176 let last = this.chunk.length - 1;
3177 return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
3178 }
3179 /**
3180 The number of ranges in the set.
3181 */
3182 get size() {
3183 if (this.isEmpty)
3184 return 0;
3185 let size = this.nextLayer.size;
3186 for (let chunk of this.chunk)
3187 size += chunk.value.length;
3188 return size;
3189 }
3190 /**
3191 @internal
3192 */
3193 chunkEnd(index) {
3194 return this.chunkPos[index] + this.chunk[index].length;
3195 }
3196 /**
3197 Update the range set, optionally adding new ranges or filtering
3198 out existing ones.
3199
3200 (Note: The type parameter is just there as a kludge to work
3201 around TypeScript variance issues that prevented `RangeSet<X>`
3202 from being a subtype of `RangeSet<Y>` when `X` is a subtype of
3203 `Y`.)
3204 */
3205 update(updateSpec) {
3206 let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
3207 let filter = updateSpec.filter;
3208 if (add.length == 0 && !filter)
3209 return this;
3210 if (sort)
3211 add = add.slice().sort(cmpRange);
3212 if (this.isEmpty)
3213 return add.length ? RangeSet.of(add) : this;
3214 let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
3215 let builder = new RangeSetBuilder();
3216 while (cur.value || i < add.length) {
3217 if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
3218 let range = add[i++];
3219 if (!builder.addInner(range.from, range.to, range.value))
3220 spill.push(range);
3221 }
3222 else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
3223 (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
3224 (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
3225 builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
3226 cur.nextChunk();
3227 }
3228 else {
3229 if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
3230 if (!builder.addInner(cur.from, cur.to, cur.value))
3231 spill.push(Range$1.create(cur.from, cur.to, cur.value));
3232 }
3233 cur.next();
3234 }
3235 }
3236 return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
3237 : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
3238 }
3239 /**
3240 Map this range set through a set of changes, return the new set.
3241 */
3242 map(changes) {
3243 if (changes.empty || this.isEmpty)
3244 return this;
3245 let chunks = [], chunkPos = [], maxPoint = -1;
3246 for (let i = 0; i < this.chunk.length; i++) {
3247 let start = this.chunkPos[i], chunk = this.chunk[i];
3248 let touch = changes.touchesRange(start, start + chunk.length);
3249 if (touch === false) {
3250 maxPoint = Math.max(maxPoint, chunk.maxPoint);
3251 chunks.push(chunk);
3252 chunkPos.push(changes.mapPos(start));
3253 }
3254 else if (touch === true) {
3255 let { mapped, pos } = chunk.map(start, changes);
3256 if (mapped) {
3257 maxPoint = Math.max(maxPoint, mapped.maxPoint);
3258 chunks.push(mapped);
3259 chunkPos.push(pos);
3260 }
3261 }
3262 }
3263 let next = this.nextLayer.map(changes);
3264 return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
3265 }
3266 /**
3267 Iterate over the ranges that touch the region `from` to `to`,
3268 calling `f` for each. There is no guarantee that the ranges will
3269 be reported in any specific order. When the callback returns
3270 `false`, iteration stops.
3271 */
3272 between(from, to, f) {
3273 if (this.isEmpty)
3274 return;
3275 for (let i = 0; i < this.chunk.length; i++) {
3276 let start = this.chunkPos[i], chunk = this.chunk[i];
3277 if (to >= start && from <= start + chunk.length &&
3278 chunk.between(start, from - start, to - start, f) === false)
3279 return;
3280 }
3281 this.nextLayer.between(from, to, f);
3282 }
3283 /**
3284 Iterate over the ranges in this set, in order, including all
3285 ranges that end at or after `from`.
3286 */
3287 iter(from = 0) {
3288 return HeapCursor.from([this]).goto(from);
3289 }
3290 /**
3291 @internal
3292 */
3293 get isEmpty() { return this.nextLayer == this; }
3294 /**
3295 Iterate over the ranges in a collection of sets, in order,
3296 starting from `from`.
3297 */
3298 static iter(sets, from = 0) {
3299 return HeapCursor.from(sets).goto(from);
3300 }
3301 /**
3302 Iterate over two groups of sets, calling methods on `comparator`
3303 to notify it of possible differences.
3304 */
3305 static compare(oldSets, newSets,
3306 /**
3307 This indicates how the underlying data changed between these
3308 ranges, and is needed to synchronize the iteration.
3309 */
3310 textDiff, comparator,
3311 /**
3312 Can be used to ignore all non-point ranges, and points below
3313 the given size. When -1, all ranges are compared.
3314 */
3315 minPointSize = -1) {
3316 let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3317 let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
3318 let sharedChunks = findSharedChunks(a, b, textDiff);
3319 let sideA = new SpanCursor(a, sharedChunks, minPointSize);
3320 let sideB = new SpanCursor(b, sharedChunks, minPointSize);
3321 textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
3322 if (textDiff.empty && textDiff.length == 0)
3323 compare(sideA, 0, sideB, 0, 0, comparator);
3324 }
3325 /**
3326 Compare the contents of two groups of range sets, returning true
3327 if they are equivalent in the given range.
3328 */
3329 static eq(oldSets, newSets, from = 0, to) {
3330 if (to == null)
3331 to = 1000000000 /* C.Far */ - 1;
3332 let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
3333 let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
3334 if (a.length != b.length)
3335 return false;
3336 if (!a.length)
3337 return true;
3338 let sharedChunks = findSharedChunks(a, b);
3339 let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
3340 for (;;) {
3341 if (sideA.to != sideB.to ||
3342 !sameValues(sideA.active, sideB.active) ||
3343 sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
3344 return false;
3345 if (sideA.to > to)
3346 return true;
3347 sideA.next();
3348 sideB.next();
3349 }
3350 }
3351 /**
3352 Iterate over a group of range sets at the same time, notifying
3353 the iterator about the ranges covering every given piece of
3354 content. Returns the open count (see
3355 [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
3356 of the iteration.
3357 */
3358 static spans(sets, from, to, iterator,
3359 /**
3360 When given and greater than -1, only points of at least this
3361 size are taken into account.
3362 */
3363 minPointSize = -1) {
3364 let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
3365 let openRanges = cursor.openStart;
3366 for (;;) {
3367 let curTo = Math.min(cursor.to, to);
3368 if (cursor.point) {
3369 let active = cursor.activeForPoint(cursor.to);
3370 let openCount = cursor.pointFrom < from ? active.length + 1 : Math.min(active.length, openRanges);
3371 iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
3372 openRanges = Math.min(cursor.openEnd(curTo), active.length);
3373 }
3374 else if (curTo > pos) {
3375 iterator.span(pos, curTo, cursor.active, openRanges);
3376 openRanges = cursor.openEnd(curTo);
3377 }
3378 if (cursor.to > to)
3379 return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
3380 pos = cursor.to;
3381 cursor.next();
3382 }
3383 }
3384 /**
3385 Create a range set for the given range or array of ranges. By
3386 default, this expects the ranges to be _sorted_ (by start
3387 position and, if two start at the same position,
3388 `value.startSide`). You can pass `true` as second argument to
3389 cause the method to sort them.
3390 */
3391 static of(ranges, sort = false) {
3392 let build = new RangeSetBuilder();
3393 for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)
3394 build.add(range.from, range.to, range.value);
3395 return build.finish();
3396 }
3397 }
3398 /**
3399 The empty set of ranges.
3400 */
3401 RangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);
3402 function lazySort(ranges) {
3403 if (ranges.length > 1)
3404 for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
3405 let cur = ranges[i];
3406 if (cmpRange(prev, cur) > 0)
3407 return ranges.slice().sort(cmpRange);
3408 prev = cur;
3409 }
3410 return ranges;
3411 }
3412 RangeSet.empty.nextLayer = RangeSet.empty;
3413 /**
3414 A range set builder is a data structure that helps build up a
3415 [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
3416 an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
3417 */
3418 class RangeSetBuilder {
3419 finishChunk(newArrays) {
3420 this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
3421 this.chunkPos.push(this.chunkStart);
3422 this.chunkStart = -1;
3423 this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
3424 this.maxPoint = -1;
3425 if (newArrays) {
3426 this.from = [];
3427 this.to = [];
3428 this.value = [];
3429 }
3430 }
3431 /**
3432 Create an empty builder.
3433 */
3434 constructor() {
3435 this.chunks = [];
3436 this.chunkPos = [];
3437 this.chunkStart = -1;
3438 this.last = null;
3439 this.lastFrom = -1000000000 /* C.Far */;
3440 this.lastTo = -1000000000 /* C.Far */;
3441 this.from = [];
3442 this.to = [];
3443 this.value = [];
3444 this.maxPoint = -1;
3445 this.setMaxPoint = -1;
3446 this.nextLayer = null;
3447 }
3448 /**
3449 Add a range. Ranges should be added in sorted (by `from` and
3450 `value.startSide`) order.
3451 */
3452 add(from, to, value) {
3453 if (!this.addInner(from, to, value))
3454 (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
3455 }
3456 /**
3457 @internal
3458 */
3459 addInner(from, to, value) {
3460 let diff = from - this.lastTo || value.startSide - this.last.endSide;
3461 if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
3462 throw new Error("Ranges must be added sorted by `from` position and `startSide`");
3463 if (diff < 0)
3464 return false;
3465 if (this.from.length == 250 /* C.ChunkSize */)
3466 this.finishChunk(true);
3467 if (this.chunkStart < 0)
3468 this.chunkStart = from;
3469 this.from.push(from - this.chunkStart);
3470 this.to.push(to - this.chunkStart);
3471 this.last = value;
3472 this.lastFrom = from;
3473 this.lastTo = to;
3474 this.value.push(value);
3475 if (value.point)
3476 this.maxPoint = Math.max(this.maxPoint, to - from);
3477 return true;
3478 }
3479 /**
3480 @internal
3481 */
3482 addChunk(from, chunk) {
3483 if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
3484 return false;
3485 if (this.from.length)
3486 this.finishChunk(true);
3487 this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
3488 this.chunks.push(chunk);
3489 this.chunkPos.push(from);
3490 let last = chunk.value.length - 1;
3491 this.last = chunk.value[last];
3492 this.lastFrom = chunk.from[last] + from;
3493 this.lastTo = chunk.to[last] + from;
3494 return true;
3495 }
3496 /**
3497 Finish the range set. Returns the new set. The builder can't be
3498 used anymore after this has been called.
3499 */
3500 finish() { return this.finishInner(RangeSet.empty); }
3501 /**
3502 @internal
3503 */
3504 finishInner(next) {
3505 if (this.from.length)
3506 this.finishChunk(false);
3507 if (this.chunks.length == 0)
3508 return next;
3509 let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
3510 this.from = null; // Make sure further `add` calls produce errors
3511 return result;
3512 }
3513 }
3514 function findSharedChunks(a, b, textDiff) {
3515 let inA = new Map();
3516 for (let set of a)
3517 for (let i = 0; i < set.chunk.length; i++)
3518 if (set.chunk[i].maxPoint <= 0)
3519 inA.set(set.chunk[i], set.chunkPos[i]);
3520 let shared = new Set();
3521 for (let set of b)
3522 for (let i = 0; i < set.chunk.length; i++) {
3523 let known = inA.get(set.chunk[i]);
3524 if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
3525 !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
3526 shared.add(set.chunk[i]);
3527 }
3528 return shared;
3529 }
3530 class LayerCursor {
3531 constructor(layer, skip, minPoint, rank = 0) {
3532 this.layer = layer;
3533 this.skip = skip;
3534 this.minPoint = minPoint;
3535 this.rank = rank;
3536 }
3537 get startSide() { return this.value ? this.value.startSide : 0; }
3538 get endSide() { return this.value ? this.value.endSide : 0; }
3539 goto(pos, side = -1000000000 /* C.Far */) {
3540 this.chunkIndex = this.rangeIndex = 0;
3541 this.gotoInner(pos, side, false);
3542 return this;
3543 }
3544 gotoInner(pos, side, forward) {
3545 while (this.chunkIndex < this.layer.chunk.length) {
3546 let next = this.layer.chunk[this.chunkIndex];
3547 if (!(this.skip && this.skip.has(next) ||
3548 this.layer.chunkEnd(this.chunkIndex) < pos ||
3549 next.maxPoint < this.minPoint))
3550 break;
3551 this.chunkIndex++;
3552 forward = false;
3553 }
3554 if (this.chunkIndex < this.layer.chunk.length) {
3555 let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
3556 if (!forward || this.rangeIndex < rangeIndex)
3557 this.setRangeIndex(rangeIndex);
3558 }
3559 this.next();
3560 }
3561 forward(pos, side) {
3562 if ((this.to - pos || this.endSide - side) < 0)
3563 this.gotoInner(pos, side, true);
3564 }
3565 next() {
3566 for (;;) {
3567 if (this.chunkIndex == this.layer.chunk.length) {
3568 this.from = this.to = 1000000000 /* C.Far */;
3569 this.value = null;
3570 break;
3571 }
3572 else {
3573 let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
3574 let from = chunkPos + chunk.from[this.rangeIndex];
3575 this.from = from;
3576 this.to = chunkPos + chunk.to[this.rangeIndex];
3577 this.value = chunk.value[this.rangeIndex];
3578 this.setRangeIndex(this.rangeIndex + 1);
3579 if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
3580 break;
3581 }
3582 }
3583 }
3584 setRangeIndex(index) {
3585 if (index == this.layer.chunk[this.chunkIndex].value.length) {
3586 this.chunkIndex++;
3587 if (this.skip) {
3588 while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
3589 this.chunkIndex++;
3590 }
3591 this.rangeIndex = 0;
3592 }
3593 else {
3594 this.rangeIndex = index;
3595 }
3596 }
3597 nextChunk() {
3598 this.chunkIndex++;
3599 this.rangeIndex = 0;
3600 this.next();
3601 }
3602 compare(other) {
3603 return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
3604 this.to - other.to || this.endSide - other.endSide;
3605 }
3606 }
3607 class HeapCursor {
3608 constructor(heap) {
3609 this.heap = heap;
3610 }
3611 static from(sets, skip = null, minPoint = -1) {
3612 let heap = [];
3613 for (let i = 0; i < sets.length; i++) {
3614 for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
3615 if (cur.maxPoint >= minPoint)
3616 heap.push(new LayerCursor(cur, skip, minPoint, i));
3617 }
3618 }
3619 return heap.length == 1 ? heap[0] : new HeapCursor(heap);
3620 }
3621 get startSide() { return this.value ? this.value.startSide : 0; }
3622 goto(pos, side = -1000000000 /* C.Far */) {
3623 for (let cur of this.heap)
3624 cur.goto(pos, side);
3625 for (let i = this.heap.length >> 1; i >= 0; i--)
3626 heapBubble(this.heap, i);
3627 this.next();
3628 return this;
3629 }
3630 forward(pos, side) {
3631 for (let cur of this.heap)
3632 cur.forward(pos, side);
3633 for (let i = this.heap.length >> 1; i >= 0; i--)
3634 heapBubble(this.heap, i);
3635 if ((this.to - pos || this.value.endSide - side) < 0)
3636 this.next();
3637 }
3638 next() {
3639 if (this.heap.length == 0) {
3640 this.from = this.to = 1000000000 /* C.Far */;
3641 this.value = null;
3642 this.rank = -1;
3643 }
3644 else {
3645 let top = this.heap[0];
3646 this.from = top.from;
3647 this.to = top.to;
3648 this.value = top.value;
3649 this.rank = top.rank;
3650 if (top.value)
3651 top.next();
3652 heapBubble(this.heap, 0);
3653 }
3654 }
3655 }
3656 function heapBubble(heap, index) {
3657 for (let cur = heap[index];;) {
3658 let childIndex = (index << 1) + 1;
3659 if (childIndex >= heap.length)
3660 break;
3661 let child = heap[childIndex];
3662 if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
3663 child = heap[childIndex + 1];
3664 childIndex++;
3665 }
3666 if (cur.compare(child) < 0)
3667 break;
3668 heap[childIndex] = cur;
3669 heap[index] = child;
3670 index = childIndex;
3671 }
3672 }
3673 class SpanCursor {
3674 constructor(sets, skip, minPoint) {
3675 this.minPoint = minPoint;
3676 this.active = [];
3677 this.activeTo = [];
3678 this.activeRank = [];
3679 this.minActive = -1;
3680 // A currently active point range, if any
3681 this.point = null;
3682 this.pointFrom = 0;
3683 this.pointRank = 0;
3684 this.to = -1000000000 /* C.Far */;
3685 this.endSide = 0;
3686 // The amount of open active ranges at the start of the iterator.
3687 // Not including points.
3688 this.openStart = -1;
3689 this.cursor = HeapCursor.from(sets, skip, minPoint);
3690 }
3691 goto(pos, side = -1000000000 /* C.Far */) {
3692 this.cursor.goto(pos, side);
3693 this.active.length = this.activeTo.length = this.activeRank.length = 0;
3694 this.minActive = -1;
3695 this.to = pos;
3696 this.endSide = side;
3697 this.openStart = -1;
3698 this.next();
3699 return this;
3700 }
3701 forward(pos, side) {
3702 while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
3703 this.removeActive(this.minActive);
3704 this.cursor.forward(pos, side);
3705 }
3706 removeActive(index) {
3707 remove(this.active, index);
3708 remove(this.activeTo, index);
3709 remove(this.activeRank, index);
3710 this.minActive = findMinIndex(this.active, this.activeTo);
3711 }
3712 addActive(trackOpen) {
3713 let i = 0, { value, to, rank } = this.cursor;
3714 while (i < this.activeRank.length && this.activeRank[i] <= rank)
3715 i++;
3716 insert(this.active, i, value);
3717 insert(this.activeTo, i, to);
3718 insert(this.activeRank, i, rank);
3719 if (trackOpen)
3720 insert(trackOpen, i, this.cursor.from);
3721 this.minActive = findMinIndex(this.active, this.activeTo);
3722 }
3723 // After calling this, if `this.point` != null, the next range is a
3724 // point. Otherwise, it's a regular range, covered by `this.active`.
3725 next() {
3726 let from = this.to, wasPoint = this.point;
3727 this.point = null;
3728 let trackOpen = this.openStart < 0 ? [] : null;
3729 for (;;) {
3730 let a = this.minActive;
3731 if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
3732 if (this.activeTo[a] > from) {
3733 this.to = this.activeTo[a];
3734 this.endSide = this.active[a].endSide;
3735 break;
3736 }
3737 this.removeActive(a);
3738 if (trackOpen)
3739 remove(trackOpen, a);
3740 }
3741 else if (!this.cursor.value) {
3742 this.to = this.endSide = 1000000000 /* C.Far */;
3743 break;
3744 }
3745 else if (this.cursor.from > from) {
3746 this.to = this.cursor.from;
3747 this.endSide = this.cursor.startSide;
3748 break;
3749 }
3750 else {
3751 let nextVal = this.cursor.value;
3752 if (!nextVal.point) { // Opening a range
3753 this.addActive(trackOpen);
3754 this.cursor.next();
3755 }
3756 else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
3757 // Ignore any non-empty points that end precisely at the end of the prev point
3758 this.cursor.next();
3759 }
3760 else { // New point
3761 this.point = nextVal;
3762 this.pointFrom = this.cursor.from;
3763 this.pointRank = this.cursor.rank;
3764 this.to = this.cursor.to;
3765 this.endSide = nextVal.endSide;
3766 this.cursor.next();
3767 this.forward(this.to, this.endSide);
3768 break;
3769 }
3770 }
3771 }
3772 if (trackOpen) {
3773 this.openStart = 0;
3774 for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)
3775 this.openStart++;
3776 }
3777 }
3778 activeForPoint(to) {
3779 if (!this.active.length)
3780 return this.active;
3781 let active = [];
3782 for (let i = this.active.length - 1; i >= 0; i--) {
3783 if (this.activeRank[i] < this.pointRank)
3784 break;
3785 if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
3786 active.push(this.active[i]);
3787 }
3788 return active.reverse();
3789 }
3790 openEnd(to) {
3791 let open = 0;
3792 for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
3793 open++;
3794 return open;
3795 }
3796 }
3797 function compare(a, startA, b, startB, length, comparator) {
3798 a.goto(startA);
3799 b.goto(startB);
3800 let endB = startB + length;
3801 let pos = startB, dPos = startB - startA;
3802 for (;;) {
3803 let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;
3804 let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
3805 if (a.point || b.point) {
3806 if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&
3807 sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))
3808 comparator.comparePoint(pos, clipEnd, a.point, b.point);
3809 }
3810 else {
3811 if (clipEnd > pos && !sameValues(a.active, b.active))
3812 comparator.compareRange(pos, clipEnd, a.active, b.active);
3813 }
3814 if (end > endB)
3815 break;
3816 pos = end;
3817 if (diff <= 0)
3818 a.next();
3819 if (diff >= 0)
3820 b.next();
3821 }
3822 }
3823 function sameValues(a, b) {
3824 if (a.length != b.length)
3825 return false;
3826 for (let i = 0; i < a.length; i++)
3827 if (a[i] != b[i] && !a[i].eq(b[i]))
3828 return false;
3829 return true;
3830 }
3831 function remove(array, index) {
3832 for (let i = index, e = array.length - 1; i < e; i++)
3833 array[i] = array[i + 1];
3834 array.pop();
3835 }
3836 function insert(array, index, value) {
3837 for (let i = array.length - 1; i >= index; i--)
3838 array[i + 1] = array[i];
3839 array[index] = value;
3840 }
3841 function findMinIndex(value, array) {
3842 let found = -1, foundPos = 1000000000 /* C.Far */;
3843 for (let i = 0; i < array.length; i++)
3844 if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
3845 found = i;
3846 foundPos = array[i];
3847 }
3848 return found;
3849 }
3850
3851 /**
3852 Count the column position at the given offset into the string,
3853 taking extending characters and tab size into account.
3854 */
3855 function countColumn(string, tabSize, to = string.length) {
3856 let n = 0;
3857 for (let i = 0; i < to;) {
3858 if (string.charCodeAt(i) == 9) {
3859 n += tabSize - (n % tabSize);
3860 i++;
3861 }
3862 else {
3863 n++;
3864 i = findClusterBreak(string, i);
3865 }
3866 }
3867 return n;
3868 }
3869 /**
3870 Find the offset that corresponds to the given column position in a
3871 string, taking extending characters and tab size into account. By
3872 default, the string length is returned when it is too short to
3873 reach the column. Pass `strict` true to make it return -1 in that
3874 situation.
3875 */
3876 function findColumn(string, col, tabSize, strict) {
3877 for (let i = 0, n = 0;;) {
3878 if (n >= col)
3879 return i;
3880 if (i == string.length)
3881 break;
3882 n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
3883 i = findClusterBreak(string, i);
3884 }
3885 return strict === true ? -1 : string.length;
3886 }
3887
3888 const C = "\u037c";
3889 const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
3890 const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
3891 const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
3892
3893 // :: - Style modules encapsulate a set of CSS rules defined from
3894 // JavaScript. Their definitions are only available in a given DOM
3895 // root after it has been _mounted_ there with `StyleModule.mount`.
3896 //
3897 // Style modules should be created once and stored somewhere, as
3898 // opposed to re-creating them every time you need them. The amount of
3899 // CSS rules generated for a given DOM root is bounded by the amount
3900 // of style modules that were used. So to avoid leaking rules, don't
3901 // create these dynamically, but treat them as one-time allocations.
3902 class StyleModule {
3903 // :: (Object<Style>, ?{finish: ?(string) → string})
3904 // Create a style module from the given spec.
3905 //
3906 // When `finish` is given, it is called on regular (non-`@`)
3907 // selectors (after `&` expansion) to compute the final selector.
3908 constructor(spec, options) {
3909 this.rules = [];
3910 let {finish} = options || {};
3911
3912 function splitSelector(selector) {
3913 return /^@/.test(selector) ? [selector] : selector.split(/,\s*/)
3914 }
3915
3916 function render(selectors, spec, target, isKeyframes) {
3917 let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes";
3918 if (isAt && spec == null) return target.push(selectors[0] + ";")
3919 for (let prop in spec) {
3920 let value = spec[prop];
3921 if (/&/.test(prop)) {
3922 render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)),
3923 value, target);
3924 } else if (value && typeof value == "object") {
3925 if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.")
3926 render(splitSelector(prop), value, local, keyframes);
3927 } else if (value != null) {
3928 local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";");
3929 }
3930 }
3931 if (local.length || keyframes) {
3932 target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") +
3933 " {" + local.join(" ") + "}");
3934 }
3935 }
3936
3937 for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules);
3938 }
3939
3940 // :: () → string
3941 // Returns a string containing the module's CSS rules.
3942 getRules() { return this.rules.join("\n") }
3943
3944 // :: () → string
3945 // Generate a new unique CSS class name.
3946 static newName() {
3947 let id = top[COUNT] || 1;
3948 top[COUNT] = id + 1;
3949 return C + id.toString(36)
3950 }
3951
3952 // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>, ?{nonce: ?string})
3953 //
3954 // Mount the given set of modules in the given DOM root, which ensures
3955 // that the CSS rules defined by the module are available in that
3956 // context.
3957 //
3958 // Rules are only added to the document once per root.
3959 //
3960 // Rule order will follow the order of the modules, so that rules from
3961 // modules later in the array take precedence of those from earlier
3962 // modules. If you call this function multiple times for the same root
3963 // in a way that changes the order of already mounted modules, the old
3964 // order will be changed.
3965 //
3966 // If a Content Security Policy nonce is provided, it is added to
3967 // the `<style>` tag generated by the library.
3968 static mount(root, modules, options) {
3969 let set = root[SET], nonce = options && options.nonce;
3970 if (!set) set = new StyleSet(root, nonce);
3971 else if (nonce) set.setNonce(nonce);
3972 set.mount(Array.isArray(modules) ? modules : [modules]);
3973 }
3974 }
3975
3976 let adoptedSet = new Map; //<Document, StyleSet>
3977
3978 class StyleSet {
3979 constructor(root, nonce) {
3980 let doc = root.ownerDocument || root, win = doc.defaultView;
3981 if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {
3982 let adopted = adoptedSet.get(doc);
3983 if (adopted) {
3984 root.adoptedStyleSheets = [adopted.sheet, ...root.adoptedStyleSheets];
3985 return root[SET] = adopted
3986 }
3987 this.sheet = new win.CSSStyleSheet;
3988 root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets];
3989 adoptedSet.set(doc, this);
3990 } else {
3991 this.styleTag = doc.createElement("style");
3992 if (nonce) this.styleTag.setAttribute("nonce", nonce);
3993 let target = root.head || root;
3994 target.insertBefore(this.styleTag, target.firstChild);
3995 }
3996 this.modules = [];
3997 root[SET] = this;
3998 }
3999
4000 mount(modules) {
4001 let sheet = this.sheet;
4002 let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */
4003 for (let i = 0; i < modules.length; i++) {
4004 let mod = modules[i], index = this.modules.indexOf(mod);
4005 if (index < j && index > -1) { // Ordering conflict
4006 this.modules.splice(index, 1);
4007 j--;
4008 index = -1;
4009 }
4010 if (index == -1) {
4011 this.modules.splice(j++, 0, mod);
4012 if (sheet) for (let k = 0; k < mod.rules.length; k++)
4013 sheet.insertRule(mod.rules[k], pos++);
4014 } else {
4015 while (j < index) pos += this.modules[j++].rules.length;
4016 pos += mod.rules.length;
4017 j++;
4018 }
4019 }
4020
4021 if (!sheet) {
4022 let text = "";
4023 for (let i = 0; i < this.modules.length; i++)
4024 text += this.modules[i].getRules() + "\n";
4025 this.styleTag.textContent = text;
4026 }
4027 }
4028
4029 setNonce(nonce) {
4030 if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce)
4031 this.styleTag.setAttribute("nonce", nonce);
4032 }
4033 }
4034
4035 // Style::Object<union<Style,string>>
4036 //
4037 // A style is an object that, in the simple case, maps CSS property
4038 // names to strings holding their values, as in `{color: "red",
4039 // fontWeight: "bold"}`. The property names can be given in
4040 // camel-case—the library will insert a dash before capital letters
4041 // when converting them to CSS.
4042 //
4043 // If you include an underscore in a property name, it and everything
4044 // after it will be removed from the output, which can be useful when
4045 // providing a property multiple times, for browser compatibility
4046 // reasons.
4047 //
4048 // A property in a style object can also be a sub-selector, which
4049 // extends the current context to add a pseudo-selector or a child
4050 // selector. Such a property should contain a `&` character, which
4051 // will be replaced by the current selector. For example `{"&:before":
4052 // {content: '"hi"'}}`. Sub-selectors and regular properties can
4053 // freely be mixed in a given object. Any property containing a `&` is
4054 // assumed to be a sub-selector.
4055 //
4056 // Finally, a property can specify an @-block to be wrapped around the
4057 // styles defined inside the object that's the property's value. For
4058 // example to create a media query you can do `{"@media screen and
4059 // (min-width: 400px)": {...}}`.
4060
4061 var base = {
4062 8: "Backspace",
4063 9: "Tab",
4064 10: "Enter",
4065 12: "NumLock",
4066 13: "Enter",
4067 16: "Shift",
4068 17: "Control",
4069 18: "Alt",
4070 20: "CapsLock",
4071 27: "Escape",
4072 32: " ",
4073 33: "PageUp",
4074 34: "PageDown",
4075 35: "End",
4076 36: "Home",
4077 37: "ArrowLeft",
4078 38: "ArrowUp",
4079 39: "ArrowRight",
4080 40: "ArrowDown",
4081 44: "PrintScreen",
4082 45: "Insert",
4083 46: "Delete",
4084 59: ";",
4085 61: "=",
4086 91: "Meta",
4087 92: "Meta",
4088 106: "*",
4089 107: "+",
4090 108: ",",
4091 109: "-",
4092 110: ".",
4093 111: "/",
4094 144: "NumLock",
4095 145: "ScrollLock",
4096 160: "Shift",
4097 161: "Shift",
4098 162: "Control",
4099 163: "Control",
4100 164: "Alt",
4101 165: "Alt",
4102 173: "-",
4103 186: ";",
4104 187: "=",
4105 188: ",",
4106 189: "-",
4107 190: ".",
4108 191: "/",
4109 192: "`",
4110 219: "[",
4111 220: "\\",
4112 221: "]",
4113 222: "'"
4114 };
4115
4116 var shift = {
4117 48: ")",
4118 49: "!",
4119 50: "@",
4120 51: "#",
4121 52: "$",
4122 53: "%",
4123 54: "^",
4124 55: "&",
4125 56: "*",
4126 57: "(",
4127 59: ":",
4128 61: "+",
4129 173: "_",
4130 186: ":",
4131 187: "+",
4132 188: "<",
4133 189: "_",
4134 190: ">",
4135 191: "?",
4136 192: "~",
4137 219: "{",
4138 220: "|",
4139 221: "}",
4140 222: "\""
4141 };
4142
4143 var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
4144 var ie$1 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
4145
4146 // Fill in the digit keys
4147 for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
4148
4149 // The function keys
4150 for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
4151
4152 // And the alphabetic keys
4153 for (var i = 65; i <= 90; i++) {
4154 base[i] = String.fromCharCode(i + 32);
4155 shift[i] = String.fromCharCode(i);
4156 }
4157
4158 // For each code that doesn't have a shift-equivalent, copy the base name
4159 for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
4160
4161 function keyName(event) {
4162 // On macOS, keys held with Shift and Cmd don't reflect the effect of Shift in `.key`.
4163 // On IE, shift effect is never included in `.key`.
4164 var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey ||
4165 ie$1 && event.shiftKey && event.key && event.key.length == 1 ||
4166 event.key == "Unidentified";
4167 var name = (!ignoreKey && event.key) ||
4168 (event.shiftKey ? shift : base)[event.keyCode] ||
4169 event.key || "Unidentified";
4170 // Edge sometimes produces wrong names (Issue #3)
4171 if (name == "Esc") name = "Escape";
4172 if (name == "Del") name = "Delete";
4173 // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
4174 if (name == "Left") name = "ArrowLeft";
4175 if (name == "Up") name = "ArrowUp";
4176 if (name == "Right") name = "ArrowRight";
4177 if (name == "Down") name = "ArrowDown";
4178 return name
4179 }
4180
4181 function getSelection(root) {
4182 let target;
4183 // Browsers differ on whether shadow roots have a getSelection
4184 // method. If it exists, use that, otherwise, call it on the
4185 // document.
4186 if (root.nodeType == 11) { // Shadow root
4187 target = root.getSelection ? root : root.ownerDocument;
4188 }
4189 else {
4190 target = root;
4191 }
4192 return target.getSelection();
4193 }
4194 function contains(dom, node) {
4195 return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
4196 }
4197 function deepActiveElement(doc) {
4198 let elt = doc.activeElement;
4199 while (elt && elt.shadowRoot)
4200 elt = elt.shadowRoot.activeElement;
4201 return elt;
4202 }
4203 function hasSelection(dom, selection) {
4204 if (!selection.anchorNode)
4205 return false;
4206 try {
4207 // Firefox will raise 'permission denied' errors when accessing
4208 // properties of `sel.anchorNode` when it's in a generated CSS
4209 // element.
4210 return contains(dom, selection.anchorNode);
4211 }
4212 catch (_) {
4213 return false;
4214 }
4215 }
4216 function clientRectsFor(dom) {
4217 if (dom.nodeType == 3)
4218 return textRange(dom, 0, dom.nodeValue.length).getClientRects();
4219 else if (dom.nodeType == 1)
4220 return dom.getClientRects();
4221 else
4222 return [];
4223 }
4224 // Scans forward and backward through DOM positions equivalent to the
4225 // given one to see if the two are in the same place (i.e. after a
4226 // text node vs at the end of that text node)
4227 function isEquivalentPosition(node, off, targetNode, targetOff) {
4228 return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||
4229 scanFor(node, off, targetNode, targetOff, 1)) : false;
4230 }
4231 function domIndex(node) {
4232 for (var index = 0;; index++) {
4233 node = node.previousSibling;
4234 if (!node)
4235 return index;
4236 }
4237 }
4238 function scanFor(node, off, targetNode, targetOff, dir) {
4239 for (;;) {
4240 if (node == targetNode && off == targetOff)
4241 return true;
4242 if (off == (dir < 0 ? 0 : maxOffset(node))) {
4243 if (node.nodeName == "DIV")
4244 return false;
4245 let parent = node.parentNode;
4246 if (!parent || parent.nodeType != 1)
4247 return false;
4248 off = domIndex(node) + (dir < 0 ? 0 : 1);
4249 node = parent;
4250 }
4251 else if (node.nodeType == 1) {
4252 node = node.childNodes[off + (dir < 0 ? -1 : 0)];
4253 if (node.nodeType == 1 && node.contentEditable == "false")
4254 return false;
4255 off = dir < 0 ? maxOffset(node) : 0;
4256 }
4257 else {
4258 return false;
4259 }
4260 }
4261 }
4262 function maxOffset(node) {
4263 return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
4264 }
4265 function flattenRect(rect, left) {
4266 let x = left ? rect.left : rect.right;
4267 return { left: x, right: x, top: rect.top, bottom: rect.bottom };
4268 }
4269 function windowRect(win) {
4270 return { left: 0, right: win.innerWidth,
4271 top: 0, bottom: win.innerHeight };
4272 }
4273 function getScale(elt, rect) {
4274 let scaleX = rect.width / elt.offsetWidth;
4275 let scaleY = rect.height / elt.offsetHeight;
4276 if (scaleX > 0.995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1)
4277 scaleX = 1;
4278 if (scaleY > 0.995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1)
4279 scaleY = 1;
4280 return { scaleX, scaleY };
4281 }
4282 function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
4283 let doc = dom.ownerDocument, win = doc.defaultView || window;
4284 for (let cur = dom, stop = false; cur && !stop;) {
4285 if (cur.nodeType == 1) { // Element
4286 let bounding, top = cur == doc.body;
4287 let scaleX = 1, scaleY = 1;
4288 if (top) {
4289 bounding = windowRect(win);
4290 }
4291 else {
4292 if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position))
4293 stop = true;
4294 if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {
4295 cur = cur.assignedSlot || cur.parentNode;
4296 continue;
4297 }
4298 let rect = cur.getBoundingClientRect();
4299 ({ scaleX, scaleY } = getScale(cur, rect));
4300 // Make sure scrollbar width isn't included in the rectangle
4301 bounding = { left: rect.left, right: rect.left + cur.clientWidth * scaleX,
4302 top: rect.top, bottom: rect.top + cur.clientHeight * scaleY };
4303 }
4304 let moveX = 0, moveY = 0;
4305 if (y == "nearest") {
4306 if (rect.top < bounding.top) {
4307 moveY = -(bounding.top - rect.top + yMargin);
4308 if (side > 0 && rect.bottom > bounding.bottom + moveY)
4309 moveY = rect.bottom - bounding.bottom + moveY + yMargin;
4310 }
4311 else if (rect.bottom > bounding.bottom) {
4312 moveY = rect.bottom - bounding.bottom + yMargin;
4313 if (side < 0 && (rect.top - moveY) < bounding.top)
4314 moveY = -(bounding.top + moveY - rect.top + yMargin);
4315 }
4316 }
4317 else {
4318 let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top;
4319 let targetTop = y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 :
4320 y == "start" || y == "center" && side < 0 ? rect.top - yMargin :
4321 rect.bottom - boundingHeight + yMargin;
4322 moveY = targetTop - bounding.top;
4323 }
4324 if (x == "nearest") {
4325 if (rect.left < bounding.left) {
4326 moveX = -(bounding.left - rect.left + xMargin);
4327 if (side > 0 && rect.right > bounding.right + moveX)
4328 moveX = rect.right - bounding.right + moveX + xMargin;
4329 }
4330 else if (rect.right > bounding.right) {
4331 moveX = rect.right - bounding.right + xMargin;
4332 if (side < 0 && rect.left < bounding.left + moveX)
4333 moveX = -(bounding.left + moveX - rect.left + xMargin);
4334 }
4335 }
4336 else {
4337 let targetLeft = x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 :
4338 (x == "start") == ltr ? rect.left - xMargin :
4339 rect.right - (bounding.right - bounding.left) + xMargin;
4340 moveX = targetLeft - bounding.left;
4341 }
4342 if (moveX || moveY) {
4343 if (top) {
4344 win.scrollBy(moveX, moveY);
4345 }
4346 else {
4347 let movedX = 0, movedY = 0;
4348 if (moveY) {
4349 let start = cur.scrollTop;
4350 cur.scrollTop += moveY / scaleY;
4351 movedY = (cur.scrollTop - start) * scaleY;
4352 }
4353 if (moveX) {
4354 let start = cur.scrollLeft;
4355 cur.scrollLeft += moveX / scaleX;
4356 movedX = (cur.scrollLeft - start) * scaleX;
4357 }
4358 rect = { left: rect.left - movedX, top: rect.top - movedY,
4359 right: rect.right - movedX, bottom: rect.bottom - movedY };
4360 if (movedX && Math.abs(movedX - moveX) < 1)
4361 x = "nearest";
4362 if (movedY && Math.abs(movedY - moveY) < 1)
4363 y = "nearest";
4364 }
4365 }
4366 if (top)
4367 break;
4368 cur = cur.assignedSlot || cur.parentNode;
4369 }
4370 else if (cur.nodeType == 11) { // A shadow root
4371 cur = cur.host;
4372 }
4373 else {
4374 break;
4375 }
4376 }
4377 }
4378 function scrollableParent(dom) {
4379 let doc = dom.ownerDocument;
4380 for (let cur = dom.parentNode; cur;) {
4381 if (cur == doc.body) {
4382 break;
4383 }
4384 else if (cur.nodeType == 1) {
4385 if (cur.scrollHeight > cur.clientHeight || cur.scrollWidth > cur.clientWidth)
4386 return cur;
4387 cur = cur.assignedSlot || cur.parentNode;
4388 }
4389 else if (cur.nodeType == 11) {
4390 cur = cur.host;
4391 }
4392 else {
4393 break;
4394 }
4395 }
4396 return null;
4397 }
4398 class DOMSelectionState {
4399 constructor() {
4400 this.anchorNode = null;
4401 this.anchorOffset = 0;
4402 this.focusNode = null;
4403 this.focusOffset = 0;
4404 }
4405 eq(domSel) {
4406 return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&
4407 this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
4408 }
4409 setRange(range) {
4410 let { anchorNode, focusNode } = range;
4411 // Clip offsets to node size to avoid crashes when Safari reports bogus offsets (#1152)
4412 this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
4413 }
4414 set(anchorNode, anchorOffset, focusNode, focusOffset) {
4415 this.anchorNode = anchorNode;
4416 this.anchorOffset = anchorOffset;
4417 this.focusNode = focusNode;
4418 this.focusOffset = focusOffset;
4419 }
4420 }
4421 let preventScrollSupported = null;
4422 // Feature-detects support for .focus({preventScroll: true}), and uses
4423 // a fallback kludge when not supported.
4424 function focusPreventScroll(dom) {
4425 if (dom.setActive)
4426 return dom.setActive(); // in IE
4427 if (preventScrollSupported)
4428 return dom.focus(preventScrollSupported);
4429 let stack = [];
4430 for (let cur = dom; cur; cur = cur.parentNode) {
4431 stack.push(cur, cur.scrollTop, cur.scrollLeft);
4432 if (cur == cur.ownerDocument)
4433 break;
4434 }
4435 dom.focus(preventScrollSupported == null ? {
4436 get preventScroll() {
4437 preventScrollSupported = { preventScroll: true };
4438 return true;
4439 }
4440 } : undefined);
4441 if (!preventScrollSupported) {
4442 preventScrollSupported = false;
4443 for (let i = 0; i < stack.length;) {
4444 let elt = stack[i++], top = stack[i++], left = stack[i++];
4445 if (elt.scrollTop != top)
4446 elt.scrollTop = top;
4447 if (elt.scrollLeft != left)
4448 elt.scrollLeft = left;
4449 }
4450 }
4451 }
4452 let scratchRange;
4453 function textRange(node, from, to = from) {
4454 let range = scratchRange || (scratchRange = document.createRange());
4455 range.setEnd(node, to);
4456 range.setStart(node, from);
4457 return range;
4458 }
4459 function dispatchKey(elt, name, code) {
4460 let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };
4461 let down = new KeyboardEvent("keydown", options);
4462 down.synthetic = true;
4463 elt.dispatchEvent(down);
4464 let up = new KeyboardEvent("keyup", options);
4465 up.synthetic = true;
4466 elt.dispatchEvent(up);
4467 return down.defaultPrevented || up.defaultPrevented;
4468 }
4469 function getRoot(node) {
4470 while (node) {
4471 if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host))
4472 return node;
4473 node = node.assignedSlot || node.parentNode;
4474 }
4475 return null;
4476 }
4477 function clearAttributes(node) {
4478 while (node.attributes.length)
4479 node.removeAttributeNode(node.attributes[0]);
4480 }
4481 function atElementStart(doc, selection) {
4482 let node = selection.focusNode, offset = selection.focusOffset;
4483 if (!node || selection.anchorNode != node || selection.anchorOffset != offset)
4484 return false;
4485 // Safari can report bogus offsets (#1152)
4486 offset = Math.min(offset, maxOffset(node));
4487 for (;;) {
4488 if (offset) {
4489 if (node.nodeType != 1)
4490 return false;
4491 let prev = node.childNodes[offset - 1];
4492 if (prev.contentEditable == "false")
4493 offset--;
4494 else {
4495 node = prev;
4496 offset = maxOffset(node);
4497 }
4498 }
4499 else if (node == doc) {
4500 return true;
4501 }
4502 else {
4503 offset = domIndex(node);
4504 node = node.parentNode;
4505 }
4506 }
4507 }
4508 function isScrolledToBottom(elt) {
4509 return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
4510 }
4511
4512 class DOMPos {
4513 constructor(node, offset, precise = true) {
4514 this.node = node;
4515 this.offset = offset;
4516 this.precise = precise;
4517 }
4518 static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }
4519 static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }
4520 }
4521 const noChildren = [];
4522 class ContentView {
4523 constructor() {
4524 this.parent = null;
4525 this.dom = null;
4526 this.flags = 2 /* ViewFlag.NodeDirty */;
4527 }
4528 get overrideDOMText() { return null; }
4529 get posAtStart() {
4530 return this.parent ? this.parent.posBefore(this) : 0;
4531 }
4532 get posAtEnd() {
4533 return this.posAtStart + this.length;
4534 }
4535 posBefore(view) {
4536 let pos = this.posAtStart;
4537 for (let child of this.children) {
4538 if (child == view)
4539 return pos;
4540 pos += child.length + child.breakAfter;
4541 }
4542 throw new RangeError("Invalid child in posBefore");
4543 }
4544 posAfter(view) {
4545 return this.posBefore(view) + view.length;
4546 }
4547 sync(view, track) {
4548 if (this.flags & 2 /* ViewFlag.NodeDirty */) {
4549 let parent = this.dom;
4550 let prev = null, next;
4551 for (let child of this.children) {
4552 if (child.flags & 7 /* ViewFlag.Dirty */) {
4553 if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
4554 let contentView = ContentView.get(next);
4555 if (!contentView || !contentView.parent && contentView.canReuseDOM(child))
4556 child.reuseDOM(next);
4557 }
4558 child.sync(view, track);
4559 child.flags &= ~7 /* ViewFlag.Dirty */;
4560 }
4561 next = prev ? prev.nextSibling : parent.firstChild;
4562 if (track && !track.written && track.node == parent && next != child.dom)
4563 track.written = true;
4564 if (child.dom.parentNode == parent) {
4565 while (next && next != child.dom)
4566 next = rm$1(next);
4567 }
4568 else {
4569 parent.insertBefore(child.dom, next);
4570 }
4571 prev = child.dom;
4572 }
4573 next = prev ? prev.nextSibling : parent.firstChild;
4574 if (next && track && track.node == parent)
4575 track.written = true;
4576 while (next)
4577 next = rm$1(next);
4578 }
4579 else if (this.flags & 1 /* ViewFlag.ChildDirty */) {
4580 for (let child of this.children)
4581 if (child.flags & 7 /* ViewFlag.Dirty */) {
4582 child.sync(view, track);
4583 child.flags &= ~7 /* ViewFlag.Dirty */;
4584 }
4585 }
4586 }
4587 reuseDOM(_dom) { }
4588 localPosFromDOM(node, offset) {
4589 let after;
4590 if (node == this.dom) {
4591 after = this.dom.childNodes[offset];
4592 }
4593 else {
4594 let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
4595 for (;;) {
4596 let parent = node.parentNode;
4597 if (parent == this.dom)
4598 break;
4599 if (bias == 0 && parent.firstChild != parent.lastChild) {
4600 if (node == parent.firstChild)
4601 bias = -1;
4602 else
4603 bias = 1;
4604 }
4605 node = parent;
4606 }
4607 if (bias < 0)
4608 after = node;
4609 else
4610 after = node.nextSibling;
4611 }
4612 if (after == this.dom.firstChild)
4613 return 0;
4614 while (after && !ContentView.get(after))
4615 after = after.nextSibling;
4616 if (!after)
4617 return this.length;
4618 for (let i = 0, pos = 0;; i++) {
4619 let child = this.children[i];
4620 if (child.dom == after)
4621 return pos;
4622 pos += child.length + child.breakAfter;
4623 }
4624 }
4625 domBoundsAround(from, to, offset = 0) {
4626 let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
4627 for (let i = 0, pos = offset, prevEnd = offset; i < this.children.length; i++) {
4628 let child = this.children[i], end = pos + child.length;
4629 if (pos < from && end > to)
4630 return child.domBoundsAround(from, to, pos);
4631 if (end >= from && fromI == -1) {
4632 fromI = i;
4633 fromStart = pos;
4634 }
4635 if (pos > to && child.dom.parentNode == this.dom) {
4636 toI = i;
4637 toEnd = prevEnd;
4638 break;
4639 }
4640 prevEnd = end;
4641 pos = end + child.breakAfter;
4642 }
4643 return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd,
4644 startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
4645 endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null };
4646 }
4647 markDirty(andParent = false) {
4648 this.flags |= 2 /* ViewFlag.NodeDirty */;
4649 this.markParentsDirty(andParent);
4650 }
4651 markParentsDirty(childList) {
4652 for (let parent = this.parent; parent; parent = parent.parent) {
4653 if (childList)
4654 parent.flags |= 2 /* ViewFlag.NodeDirty */;
4655 if (parent.flags & 1 /* ViewFlag.ChildDirty */)
4656 return;
4657 parent.flags |= 1 /* ViewFlag.ChildDirty */;
4658 childList = false;
4659 }
4660 }
4661 setParent(parent) {
4662 if (this.parent != parent) {
4663 this.parent = parent;
4664 if (this.flags & 7 /* ViewFlag.Dirty */)
4665 this.markParentsDirty(true);
4666 }
4667 }
4668 setDOM(dom) {
4669 if (this.dom == dom)
4670 return;
4671 if (this.dom)
4672 this.dom.cmView = null;
4673 this.dom = dom;
4674 dom.cmView = this;
4675 }
4676 get rootView() {
4677 for (let v = this;;) {
4678 let parent = v.parent;
4679 if (!parent)
4680 return v;
4681 v = parent;
4682 }
4683 }
4684 replaceChildren(from, to, children = noChildren) {
4685 this.markDirty();
4686 for (let i = from; i < to; i++) {
4687 let child = this.children[i];
4688 if (child.parent == this && children.indexOf(child) < 0)
4689 child.destroy();
4690 }
4691 this.children.splice(from, to - from, ...children);
4692 for (let i = 0; i < children.length; i++)
4693 children[i].setParent(this);
4694 }
4695 ignoreMutation(_rec) { return false; }
4696 ignoreEvent(_event) { return false; }
4697 childCursor(pos = this.length) {
4698 return new ChildCursor(this.children, pos, this.children.length);
4699 }
4700 childPos(pos, bias = 1) {
4701 return this.childCursor().findPos(pos, bias);
4702 }
4703 toString() {
4704 let name = this.constructor.name.replace("View", "");
4705 return name + (this.children.length ? "(" + this.children.join() + ")" :
4706 this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") +
4707 (this.breakAfter ? "#" : "");
4708 }
4709 static get(node) { return node.cmView; }
4710 get isEditable() { return true; }
4711 get isWidget() { return false; }
4712 get isHidden() { return false; }
4713 merge(from, to, source, hasStart, openStart, openEnd) {
4714 return false;
4715 }
4716 become(other) { return false; }
4717 canReuseDOM(other) {
4718 return other.constructor == this.constructor && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
4719 }
4720 // When this is a zero-length view with a side, this should return a
4721 // number <= 0 to indicate it is before its position, or a
4722 // number > 0 when after its position.
4723 getSide() { return 0; }
4724 destroy() {
4725 for (let child of this.children)
4726 if (child.parent == this)
4727 child.destroy();
4728 this.parent = null;
4729 }
4730 }
4731 ContentView.prototype.breakAfter = 0;
4732 // Remove a DOM node and return its next sibling.
4733 function rm$1(dom) {
4734 let next = dom.nextSibling;
4735 dom.parentNode.removeChild(dom);
4736 return next;
4737 }
4738 class ChildCursor {
4739 constructor(children, pos, i) {
4740 this.children = children;
4741 this.pos = pos;
4742 this.i = i;
4743 this.off = 0;
4744 }
4745 findPos(pos, bias = 1) {
4746 for (;;) {
4747 if (pos > this.pos || pos == this.pos &&
4748 (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
4749 this.off = pos - this.pos;
4750 return this;
4751 }
4752 let next = this.children[--this.i];
4753 this.pos -= next.length + next.breakAfter;
4754 }
4755 }
4756 }
4757 function replaceRange(parent, fromI, fromOff, toI, toOff, insert, breakAtStart, openStart, openEnd) {
4758 let { children } = parent;
4759 let before = children.length ? children[fromI] : null;
4760 let last = insert.length ? insert[insert.length - 1] : null;
4761 let breakAtEnd = last ? last.breakAfter : breakAtStart;
4762 // Change within a single child
4763 if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert.length < 2 &&
4764 before.merge(fromOff, toOff, insert.length ? last : null, fromOff == 0, openStart, openEnd))
4765 return;
4766 if (toI < children.length) {
4767 let after = children[toI];
4768 // Make sure the end of the child after the update is preserved in `after`
4769 if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
4770 // If we're splitting a child, separate part of it to avoid that
4771 // being mangled when updating the child before the update.
4772 if (fromI == toI) {
4773 after = after.split(toOff);
4774 toOff = 0;
4775 }
4776 // If the element after the replacement should be merged with
4777 // the last replacing element, update `content`
4778 if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
4779 insert[insert.length - 1] = after;
4780 }
4781 else {
4782 // Remove the start of the after element, if necessary, and
4783 // add it to `content`.
4784 if (toOff || after.children.length && !after.children[0].length)
4785 after.merge(0, toOff, null, false, 0, openEnd);
4786 insert.push(after);
4787 }
4788 }
4789 else if (after === null || after === void 0 ? void 0 : after.breakAfter) {
4790 // The element at `toI` is entirely covered by this range.
4791 // Preserve its line break, if any.
4792 if (last)
4793 last.breakAfter = 1;
4794 else
4795 breakAtStart = 1;
4796 }
4797 // Since we've handled the next element from the current elements
4798 // now, make sure `toI` points after that.
4799 toI++;
4800 }
4801 if (before) {
4802 before.breakAfter = breakAtStart;
4803 if (fromOff > 0) {
4804 if (!breakAtStart && insert.length && before.merge(fromOff, before.length, insert[0], false, openStart, 0)) {
4805 before.breakAfter = insert.shift().breakAfter;
4806 }
4807 else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
4808 before.merge(fromOff, before.length, null, false, openStart, 0);
4809 }
4810 fromI++;
4811 }
4812 }
4813 // Try to merge widgets on the boundaries of the replacement
4814 while (fromI < toI && insert.length) {
4815 if (children[toI - 1].become(insert[insert.length - 1])) {
4816 toI--;
4817 insert.pop();
4818 openEnd = insert.length ? 0 : openStart;
4819 }
4820 else if (children[fromI].become(insert[0])) {
4821 fromI++;
4822 insert.shift();
4823 openStart = insert.length ? 0 : openEnd;
4824 }
4825 else {
4826 break;
4827 }
4828 }
4829 if (!insert.length && fromI && toI < children.length && !children[fromI - 1].breakAfter &&
4830 children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd))
4831 fromI--;
4832 if (fromI < toI || insert.length)
4833 parent.replaceChildren(fromI, toI, insert);
4834 }
4835 function mergeChildrenInto(parent, from, to, insert, openStart, openEnd) {
4836 let cur = parent.childCursor();
4837 let { i: toI, off: toOff } = cur.findPos(to, 1);
4838 let { i: fromI, off: fromOff } = cur.findPos(from, -1);
4839 let dLen = from - to;
4840 for (let view of insert)
4841 dLen += view.length;
4842 parent.length += dLen;
4843 replaceRange(parent, fromI, fromOff, toI, toOff, insert, 0, openStart, openEnd);
4844 }
4845
4846 let nav = typeof navigator != "undefined" ? navigator : { userAgent: "", vendor: "", platform: "" };
4847 let doc = typeof document != "undefined" ? document : { documentElement: { style: {} } };
4848 const ie_edge = /*@__PURE__*//Edge\/(\d+)/.exec(nav.userAgent);
4849 const ie_upto10 = /*@__PURE__*//MSIE \d/.test(nav.userAgent);
4850 const ie_11up = /*@__PURE__*//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
4851 const ie = !!(ie_upto10 || ie_11up || ie_edge);
4852 const gecko = !ie && /*@__PURE__*//gecko\/(\d+)/i.test(nav.userAgent);
4853 const chrome = !ie && /*@__PURE__*//Chrome\/(\d+)/.exec(nav.userAgent);
4854 const webkit = "webkitFontSmoothing" in doc.documentElement.style;
4855 const safari = !ie && /*@__PURE__*//Apple Computer/.test(nav.vendor);
4856 const ios = safari && (/*@__PURE__*//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
4857 var browser = {
4858 mac: ios || /*@__PURE__*//Mac/.test(nav.platform),
4859 windows: /*@__PURE__*//Win/.test(nav.platform),
4860 linux: /*@__PURE__*//Linux|X11/.test(nav.platform),
4861 ie,
4862 ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
4863 gecko,
4864 gecko_version: gecko ? +(/*@__PURE__*//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
4865 chrome: !!chrome,
4866 chrome_version: chrome ? +chrome[1] : 0,
4867 ios,
4868 android: /*@__PURE__*//Android\b/.test(nav.userAgent),
4869 webkit,
4870 safari,
4871 webkit_version: webkit ? +(/*@__PURE__*//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
4872 tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
4873 };
4874
4875 const MaxJoinLen = 256;
4876 class TextView extends ContentView {
4877 constructor(text) {
4878 super();
4879 this.text = text;
4880 }
4881 get length() { return this.text.length; }
4882 createDOM(textDOM) {
4883 this.setDOM(textDOM || document.createTextNode(this.text));
4884 }
4885 sync(view, track) {
4886 if (!this.dom)
4887 this.createDOM();
4888 if (this.dom.nodeValue != this.text) {
4889 if (track && track.node == this.dom)
4890 track.written = true;
4891 this.dom.nodeValue = this.text;
4892 }
4893 }
4894 reuseDOM(dom) {
4895 if (dom.nodeType == 3)
4896 this.createDOM(dom);
4897 }
4898 merge(from, to, source) {
4899 if ((this.flags & 8 /* ViewFlag.Composition */) ||
4900 source && (!(source instanceof TextView) ||
4901 this.length - (to - from) + source.length > MaxJoinLen ||
4902 (source.flags & 8 /* ViewFlag.Composition */)))
4903 return false;
4904 this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
4905 this.markDirty();
4906 return true;
4907 }
4908 split(from) {
4909 let result = new TextView(this.text.slice(from));
4910 this.text = this.text.slice(0, from);
4911 this.markDirty();
4912 result.flags |= this.flags & 8 /* ViewFlag.Composition */;
4913 return result;
4914 }
4915 localPosFromDOM(node, offset) {
4916 return node == this.dom ? offset : offset ? this.text.length : 0;
4917 }
4918 domAtPos(pos) { return new DOMPos(this.dom, pos); }
4919 domBoundsAround(_from, _to, offset) {
4920 return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
4921 }
4922 coordsAt(pos, side) {
4923 return textCoords(this.dom, pos, side);
4924 }
4925 }
4926 class MarkView extends ContentView {
4927 constructor(mark, children = [], length = 0) {
4928 super();
4929 this.mark = mark;
4930 this.children = children;
4931 this.length = length;
4932 for (let ch of children)
4933 ch.setParent(this);
4934 }
4935 setAttrs(dom) {
4936 clearAttributes(dom);
4937 if (this.mark.class)
4938 dom.className = this.mark.class;
4939 if (this.mark.attrs)
4940 for (let name in this.mark.attrs)
4941 dom.setAttribute(name, this.mark.attrs[name]);
4942 return dom;
4943 }
4944 canReuseDOM(other) {
4945 return super.canReuseDOM(other) && !((this.flags | other.flags) & 8 /* ViewFlag.Composition */);
4946 }
4947 reuseDOM(node) {
4948 if (node.nodeName == this.mark.tagName.toUpperCase()) {
4949 this.setDOM(node);
4950 this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
4951 }
4952 }
4953 sync(view, track) {
4954 if (!this.dom)
4955 this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));
4956 else if (this.flags & 4 /* ViewFlag.AttrsDirty */)
4957 this.setAttrs(this.dom);
4958 super.sync(view, track);
4959 }
4960 merge(from, to, source, _hasStart, openStart, openEnd) {
4961 if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||
4962 (from && openStart <= 0) || (to < this.length && openEnd <= 0)))
4963 return false;
4964 mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);
4965 this.markDirty();
4966 return true;
4967 }
4968 split(from) {
4969 let result = [], off = 0, detachFrom = -1, i = 0;
4970 for (let elt of this.children) {
4971 let end = off + elt.length;
4972 if (end > from)
4973 result.push(off < from ? elt.split(from - off) : elt);
4974 if (detachFrom < 0 && off >= from)
4975 detachFrom = i;
4976 off = end;
4977 i++;
4978 }
4979 let length = this.length - from;
4980 this.length = from;
4981 if (detachFrom > -1) {
4982 this.children.length = detachFrom;
4983 this.markDirty();
4984 }
4985 return new MarkView(this.mark, result, length);
4986 }
4987 domAtPos(pos) {
4988 return inlineDOMAtPos(this, pos);
4989 }
4990 coordsAt(pos, side) {
4991 return coordsInChildren(this, pos, side);
4992 }
4993 }
4994 function textCoords(text, pos, side) {
4995 let length = text.nodeValue.length;
4996 if (pos > length)
4997 pos = length;
4998 let from = pos, to = pos, flatten = 0;
4999 if (pos == 0 && side < 0 || pos == length && side >= 0) {
5000 if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges
5001 if (pos) {
5002 from--;
5003 flatten = 1;
5004 } // FIXME this is wrong in RTL text
5005 else if (to < length) {
5006 to++;
5007 flatten = -1;
5008 }
5009 }
5010 }
5011 else {
5012 if (side < 0)
5013 from--;
5014 else if (to < length)
5015 to++;
5016 }
5017 let rects = textRange(text, from, to).getClientRects();
5018 if (!rects.length)
5019 return null;
5020 let rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
5021 if (browser.safari && !flatten && rect.width == 0)
5022 rect = Array.prototype.find.call(rects, r => r.width) || rect;
5023 return flatten ? flattenRect(rect, flatten < 0) : rect || null;
5024 }
5025 // Also used for collapsed ranges that don't have a placeholder widget!
5026 class WidgetView extends ContentView {
5027 static create(widget, length, side) {
5028 return new WidgetView(widget, length, side);
5029 }
5030 constructor(widget, length, side) {
5031 super();
5032 this.widget = widget;
5033 this.length = length;
5034 this.side = side;
5035 this.prevWidget = null;
5036 }
5037 split(from) {
5038 let result = WidgetView.create(this.widget, this.length - from, this.side);
5039 this.length -= from;
5040 return result;
5041 }
5042 sync(view) {
5043 if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5044 if (this.dom && this.prevWidget)
5045 this.prevWidget.destroy(this.dom);
5046 this.prevWidget = null;
5047 this.setDOM(this.widget.toDOM(view));
5048 this.dom.contentEditable = "false";
5049 }
5050 }
5051 getSide() { return this.side; }
5052 merge(from, to, source, hasStart, openStart, openEnd) {
5053 if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||
5054 from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5055 return false;
5056 this.length = from + (source ? source.length : 0) + (this.length - to);
5057 return true;
5058 }
5059 become(other) {
5060 if (other instanceof WidgetView && other.side == this.side &&
5061 this.widget.constructor == other.widget.constructor) {
5062 if (!this.widget.compare(other.widget))
5063 this.markDirty(true);
5064 if (this.dom && !this.prevWidget)
5065 this.prevWidget = this.widget;
5066 this.widget = other.widget;
5067 this.length = other.length;
5068 return true;
5069 }
5070 return false;
5071 }
5072 ignoreMutation() { return true; }
5073 ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5074 get overrideDOMText() {
5075 if (this.length == 0)
5076 return Text.empty;
5077 let top = this;
5078 while (top.parent)
5079 top = top.parent;
5080 let { view } = top, text = view && view.state.doc, start = this.posAtStart;
5081 return text ? text.slice(start, start + this.length) : Text.empty;
5082 }
5083 domAtPos(pos) {
5084 return (this.length ? pos == 0 : this.side > 0)
5085 ? DOMPos.before(this.dom)
5086 : DOMPos.after(this.dom, pos == this.length);
5087 }
5088 domBoundsAround() { return null; }
5089 coordsAt(pos, side) {
5090 let custom = this.widget.coordsAt(this.dom, pos, side);
5091 if (custom)
5092 return custom;
5093 let rects = this.dom.getClientRects(), rect = null;
5094 if (!rects.length)
5095 return null;
5096 let fromBack = this.side ? this.side < 0 : pos > 0;
5097 for (let i = fromBack ? rects.length - 1 : 0;; i += (fromBack ? -1 : 1)) {
5098 rect = rects[i];
5099 if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
5100 break;
5101 }
5102 return flattenRect(rect, !fromBack);
5103 }
5104 get isEditable() { return false; }
5105 get isWidget() { return true; }
5106 get isHidden() { return this.widget.isHidden; }
5107 destroy() {
5108 super.destroy();
5109 if (this.dom)
5110 this.widget.destroy(this.dom);
5111 }
5112 }
5113 // These are drawn around uneditable widgets to avoid a number of
5114 // browser bugs that show up when the cursor is directly next to
5115 // uneditable inline content.
5116 class WidgetBufferView extends ContentView {
5117 constructor(side) {
5118 super();
5119 this.side = side;
5120 }
5121 get length() { return 0; }
5122 merge() { return false; }
5123 become(other) {
5124 return other instanceof WidgetBufferView && other.side == this.side;
5125 }
5126 split() { return new WidgetBufferView(this.side); }
5127 sync() {
5128 if (!this.dom) {
5129 let dom = document.createElement("img");
5130 dom.className = "cm-widgetBuffer";
5131 dom.setAttribute("aria-hidden", "true");
5132 this.setDOM(dom);
5133 }
5134 }
5135 getSide() { return this.side; }
5136 domAtPos(pos) { return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom); }
5137 localPosFromDOM() { return 0; }
5138 domBoundsAround() { return null; }
5139 coordsAt(pos) {
5140 return this.dom.getBoundingClientRect();
5141 }
5142 get overrideDOMText() {
5143 return Text.empty;
5144 }
5145 get isHidden() { return true; }
5146 }
5147 TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
5148 function inlineDOMAtPos(parent, pos) {
5149 let dom = parent.dom, { children } = parent, i = 0;
5150 for (let off = 0; i < children.length; i++) {
5151 let child = children[i], end = off + child.length;
5152 if (end == off && child.getSide() <= 0)
5153 continue;
5154 if (pos > off && pos < end && child.dom.parentNode == dom)
5155 return child.domAtPos(pos - off);
5156 if (pos <= off)
5157 break;
5158 off = end;
5159 }
5160 for (let j = i; j > 0; j--) {
5161 let prev = children[j - 1];
5162 if (prev.dom.parentNode == dom)
5163 return prev.domAtPos(prev.length);
5164 }
5165 for (let j = i; j < children.length; j++) {
5166 let next = children[j];
5167 if (next.dom.parentNode == dom)
5168 return next.domAtPos(0);
5169 }
5170 return new DOMPos(dom, 0);
5171 }
5172 // Assumes `view`, if a mark view, has precisely 1 child.
5173 function joinInlineInto(parent, view, open) {
5174 let last, { children } = parent;
5175 if (open > 0 && view instanceof MarkView && children.length &&
5176 (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
5177 joinInlineInto(last, view.children[0], open - 1);
5178 }
5179 else {
5180 children.push(view);
5181 view.setParent(parent);
5182 }
5183 parent.length += view.length;
5184 }
5185 function coordsInChildren(view, pos, side) {
5186 let before = null, beforePos = -1, after = null, afterPos = -1;
5187 function scan(view, pos) {
5188 for (let i = 0, off = 0; i < view.children.length && off <= pos; i++) {
5189 let child = view.children[i], end = off + child.length;
5190 if (end >= pos) {
5191 if (child.children.length) {
5192 scan(child, pos - off);
5193 }
5194 else if ((!after || after.isHidden && side > 0) &&
5195 (end > pos || off == end && child.getSide() > 0)) {
5196 after = child;
5197 afterPos = pos - off;
5198 }
5199 else if (off < pos || (off == end && child.getSide() < 0) && !child.isHidden) {
5200 before = child;
5201 beforePos = pos - off;
5202 }
5203 }
5204 off = end;
5205 }
5206 }
5207 scan(view, pos);
5208 let target = (side < 0 ? before : after) || before || after;
5209 if (target)
5210 return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
5211 return fallbackRect(view);
5212 }
5213 function fallbackRect(view) {
5214 let last = view.dom.lastChild;
5215 if (!last)
5216 return view.dom.getBoundingClientRect();
5217 let rects = clientRectsFor(last);
5218 return rects[rects.length - 1] || null;
5219 }
5220
5221 function combineAttrs(source, target) {
5222 for (let name in source) {
5223 if (name == "class" && target.class)
5224 target.class += " " + source.class;
5225 else if (name == "style" && target.style)
5226 target.style += ";" + source.style;
5227 else
5228 target[name] = source[name];
5229 }
5230 return target;
5231 }
5232 const noAttrs = /*@__PURE__*/Object.create(null);
5233 function attrsEq(a, b, ignore) {
5234 if (a == b)
5235 return true;
5236 if (!a)
5237 a = noAttrs;
5238 if (!b)
5239 b = noAttrs;
5240 let keysA = Object.keys(a), keysB = Object.keys(b);
5241 if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) !=
5242 keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0))
5243 return false;
5244 for (let key of keysA) {
5245 if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key]))
5246 return false;
5247 }
5248 return true;
5249 }
5250 function updateAttrs(dom, prev, attrs) {
5251 let changed = false;
5252 if (prev)
5253 for (let name in prev)
5254 if (!(attrs && name in attrs)) {
5255 changed = true;
5256 if (name == "style")
5257 dom.style.cssText = "";
5258 else
5259 dom.removeAttribute(name);
5260 }
5261 if (attrs)
5262 for (let name in attrs)
5263 if (!(prev && prev[name] == attrs[name])) {
5264 changed = true;
5265 if (name == "style")
5266 dom.style.cssText = attrs[name];
5267 else
5268 dom.setAttribute(name, attrs[name]);
5269 }
5270 return changed;
5271 }
5272 function getAttrs(dom) {
5273 let attrs = Object.create(null);
5274 for (let i = 0; i < dom.attributes.length; i++) {
5275 let attr = dom.attributes[i];
5276 attrs[attr.name] = attr.value;
5277 }
5278 return attrs;
5279 }
5280
5281 class LineView extends ContentView {
5282 constructor() {
5283 super(...arguments);
5284 this.children = [];
5285 this.length = 0;
5286 this.prevAttrs = undefined;
5287 this.attrs = null;
5288 this.breakAfter = 0;
5289 }
5290 // Consumes source
5291 merge(from, to, source, hasStart, openStart, openEnd) {
5292 if (source) {
5293 if (!(source instanceof LineView))
5294 return false;
5295 if (!this.dom)
5296 source.transferDOM(this); // Reuse source.dom when appropriate
5297 }
5298 if (hasStart)
5299 this.setDeco(source ? source.attrs : null);
5300 mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart, openEnd);
5301 return true;
5302 }
5303 split(at) {
5304 let end = new LineView;
5305 end.breakAfter = this.breakAfter;
5306 if (this.length == 0)
5307 return end;
5308 let { i, off } = this.childPos(at);
5309 if (off) {
5310 end.append(this.children[i].split(off), 0);
5311 this.children[i].merge(off, this.children[i].length, null, false, 0, 0);
5312 i++;
5313 }
5314 for (let j = i; j < this.children.length; j++)
5315 end.append(this.children[j], 0);
5316 while (i > 0 && this.children[i - 1].length == 0)
5317 this.children[--i].destroy();
5318 this.children.length = i;
5319 this.markDirty();
5320 this.length = at;
5321 return end;
5322 }
5323 transferDOM(other) {
5324 if (!this.dom)
5325 return;
5326 this.markDirty();
5327 other.setDOM(this.dom);
5328 other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;
5329 this.prevAttrs = undefined;
5330 this.dom = null;
5331 }
5332 setDeco(attrs) {
5333 if (!attrsEq(this.attrs, attrs)) {
5334 if (this.dom) {
5335 this.prevAttrs = this.attrs;
5336 this.markDirty();
5337 }
5338 this.attrs = attrs;
5339 }
5340 }
5341 append(child, openStart) {
5342 joinInlineInto(this, child, openStart);
5343 }
5344 // Only called when building a line view in ContentBuilder
5345 addLineDeco(deco) {
5346 let attrs = deco.spec.attributes, cls = deco.spec.class;
5347 if (attrs)
5348 this.attrs = combineAttrs(attrs, this.attrs || {});
5349 if (cls)
5350 this.attrs = combineAttrs({ class: cls }, this.attrs || {});
5351 }
5352 domAtPos(pos) {
5353 return inlineDOMAtPos(this, pos);
5354 }
5355 reuseDOM(node) {
5356 if (node.nodeName == "DIV") {
5357 this.setDOM(node);
5358 this.flags |= 4 /* ViewFlag.AttrsDirty */ | 2 /* ViewFlag.NodeDirty */;
5359 }
5360 }
5361 sync(view, track) {
5362 var _a;
5363 if (!this.dom) {
5364 this.setDOM(document.createElement("div"));
5365 this.dom.className = "cm-line";
5366 this.prevAttrs = this.attrs ? null : undefined;
5367 }
5368 else if (this.flags & 4 /* ViewFlag.AttrsDirty */) {
5369 clearAttributes(this.dom);
5370 this.dom.className = "cm-line";
5371 this.prevAttrs = this.attrs ? null : undefined;
5372 }
5373 if (this.prevAttrs !== undefined) {
5374 updateAttrs(this.dom, this.prevAttrs, this.attrs);
5375 this.dom.classList.add("cm-line");
5376 this.prevAttrs = undefined;
5377 }
5378 super.sync(view, track);
5379 let last = this.dom.lastChild;
5380 while (last && ContentView.get(last) instanceof MarkView)
5381 last = last.lastChild;
5382 if (!last || !this.length ||
5383 last.nodeName != "BR" && ((_a = ContentView.get(last)) === null || _a === void 0 ? void 0 : _a.isEditable) == false &&
5384 (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {
5385 let hack = document.createElement("BR");
5386 hack.cmIgnore = true;
5387 this.dom.appendChild(hack);
5388 }
5389 }
5390 measureTextSize() {
5391 if (this.children.length == 0 || this.length > 20)
5392 return null;
5393 let totalWidth = 0, textHeight;
5394 for (let child of this.children) {
5395 if (!(child instanceof TextView) || /[^ -~]/.test(child.text))
5396 return null;
5397 let rects = clientRectsFor(child.dom);
5398 if (rects.length != 1)
5399 return null;
5400 totalWidth += rects[0].width;
5401 textHeight = rects[0].height;
5402 }
5403 return !totalWidth ? null : {
5404 lineHeight: this.dom.getBoundingClientRect().height,
5405 charWidth: totalWidth / this.length,
5406 textHeight
5407 };
5408 }
5409 coordsAt(pos, side) {
5410 let rect = coordsInChildren(this, pos, side);
5411 // Correct rectangle height for empty lines when the returned
5412 // height is larger than the text height.
5413 if (!this.children.length && rect && this.parent) {
5414 let { heightOracle } = this.parent.view.viewState, height = rect.bottom - rect.top;
5415 if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
5416 let dist = (height - heightOracle.textHeight) / 2;
5417 return { top: rect.top + dist, bottom: rect.bottom - dist, left: rect.left, right: rect.left };
5418 }
5419 }
5420 return rect;
5421 }
5422 become(_other) { return false; }
5423 covers() { return true; }
5424 static find(docView, pos) {
5425 for (let i = 0, off = 0; i < docView.children.length; i++) {
5426 let block = docView.children[i], end = off + block.length;
5427 if (end >= pos) {
5428 if (block instanceof LineView)
5429 return block;
5430 if (end > pos)
5431 break;
5432 }
5433 off = end + block.breakAfter;
5434 }
5435 return null;
5436 }
5437 }
5438 class BlockWidgetView extends ContentView {
5439 constructor(widget, length, deco) {
5440 super();
5441 this.widget = widget;
5442 this.length = length;
5443 this.deco = deco;
5444 this.breakAfter = 0;
5445 this.prevWidget = null;
5446 }
5447 merge(from, to, source, _takeDeco, openStart, openEnd) {
5448 if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||
5449 from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
5450 return false;
5451 this.length = from + (source ? source.length : 0) + (this.length - to);
5452 return true;
5453 }
5454 domAtPos(pos) {
5455 return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
5456 }
5457 split(at) {
5458 let len = this.length - at;
5459 this.length = at;
5460 let end = new BlockWidgetView(this.widget, len, this.deco);
5461 end.breakAfter = this.breakAfter;
5462 return end;
5463 }
5464 get children() { return noChildren; }
5465 sync(view) {
5466 if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
5467 if (this.dom && this.prevWidget)
5468 this.prevWidget.destroy(this.dom);
5469 this.prevWidget = null;
5470 this.setDOM(this.widget.toDOM(view));
5471 this.dom.contentEditable = "false";
5472 }
5473 }
5474 get overrideDOMText() {
5475 return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
5476 }
5477 domBoundsAround() { return null; }
5478 become(other) {
5479 if (other instanceof BlockWidgetView &&
5480 other.widget.constructor == this.widget.constructor) {
5481 if (!other.widget.compare(this.widget))
5482 this.markDirty(true);
5483 if (this.dom && !this.prevWidget)
5484 this.prevWidget = this.widget;
5485 this.widget = other.widget;
5486 this.length = other.length;
5487 this.deco = other.deco;
5488 this.breakAfter = other.breakAfter;
5489 return true;
5490 }
5491 return false;
5492 }
5493 ignoreMutation() { return true; }
5494 ignoreEvent(event) { return this.widget.ignoreEvent(event); }
5495 get isEditable() { return false; }
5496 get isWidget() { return true; }
5497 coordsAt(pos, side) {
5498 return this.widget.coordsAt(this.dom, pos, side);
5499 }
5500 destroy() {
5501 super.destroy();
5502 if (this.dom)
5503 this.widget.destroy(this.dom);
5504 }
5505 covers(side) {
5506 let { startSide, endSide } = this.deco;
5507 return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
5508 }
5509 }
5510
5511 /**
5512 Widgets added to the content are described by subclasses of this
5513 class. Using a description object like that makes it possible to
5514 delay creating of the DOM structure for a widget until it is
5515 needed, and to avoid redrawing widgets even if the decorations
5516 that define them are recreated.
5517 */
5518 class WidgetType {
5519 /**
5520 Compare this instance to another instance of the same type.
5521 (TypeScript can't express this, but only instances of the same
5522 specific class will be passed to this method.) This is used to
5523 avoid redrawing widgets when they are replaced by a new
5524 decoration of the same type. The default implementation just
5525 returns `false`, which will cause new instances of the widget to
5526 always be redrawn.
5527 */
5528 eq(widget) { return false; }
5529 /**
5530 Update a DOM element created by a widget of the same type (but
5531 different, non-`eq` content) to reflect this widget. May return
5532 true to indicate that it could update, false to indicate it
5533 couldn't (in which case the widget will be redrawn). The default
5534 implementation just returns false.
5535 */
5536 updateDOM(dom, view) { return false; }
5537 /**
5538 @internal
5539 */
5540 compare(other) {
5541 return this == other || this.constructor == other.constructor && this.eq(other);
5542 }
5543 /**
5544 The estimated height this widget will have, to be used when
5545 estimating the height of content that hasn't been drawn. May
5546 return -1 to indicate you don't know. The default implementation
5547 returns -1.
5548 */
5549 get estimatedHeight() { return -1; }
5550 /**
5551 For inline widgets that are displayed inline (as opposed to
5552 `inline-block`) and introduce line breaks (through `<br>` tags
5553 or textual newlines), this must indicate the amount of line
5554 breaks they introduce. Defaults to 0.
5555 */
5556 get lineBreaks() { return 0; }
5557 /**
5558 Can be used to configure which kinds of events inside the widget
5559 should be ignored by the editor. The default is to ignore all
5560 events.
5561 */
5562 ignoreEvent(event) { return true; }
5563 /**
5564 Override the way screen coordinates for positions at/in the
5565 widget are found. `pos` will be the offset into the widget, and
5566 `side` the side of the position that is being queried—less than
5567 zero for before, greater than zero for after, and zero for
5568 directly at that position.
5569 */
5570 coordsAt(dom, pos, side) { return null; }
5571 /**
5572 @internal
5573 */
5574 get isHidden() { return false; }
5575 /**
5576 This is called when the an instance of the widget is removed
5577 from the editor view.
5578 */
5579 destroy(dom) { }
5580 }
5581 /**
5582 The different types of blocks that can occur in an editor view.
5583 */
5584 exports.BlockType = /*@__PURE__*/(function (BlockType) {
5585 /**
5586 A line of text.
5587 */
5588 BlockType[BlockType["Text"] = 0] = "Text";
5589 /**
5590 A block widget associated with the position after it.
5591 */
5592 BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore";
5593 /**
5594 A block widget associated with the position before it.
5595 */
5596 BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter";
5597 /**
5598 A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
5599 */
5600 BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange";
5601 return BlockType})(exports.BlockType || (exports.BlockType = {}));
5602 /**
5603 A decoration provides information on how to draw or style a piece
5604 of content. You'll usually use it wrapped in a
5605 [`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
5606 @nonabstract
5607 */
5608 class Decoration extends RangeValue {
5609 constructor(
5610 /**
5611 @internal
5612 */
5613 startSide,
5614 /**
5615 @internal
5616 */
5617 endSide,
5618 /**
5619 @internal
5620 */
5621 widget,
5622 /**
5623 The config object used to create this decoration. You can
5624 include additional properties in there to store metadata about
5625 your decoration.
5626 */
5627 spec) {
5628 super();
5629 this.startSide = startSide;
5630 this.endSide = endSide;
5631 this.widget = widget;
5632 this.spec = spec;
5633 }
5634 /**
5635 @internal
5636 */
5637 get heightRelevant() { return false; }
5638 /**
5639 Create a mark decoration, which influences the styling of the
5640 content in its range. Nested mark decorations will cause nested
5641 DOM elements to be created. Nesting order is determined by
5642 precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
5643 the higher-precedence decorations creating the inner DOM nodes.
5644 Such elements are split on line boundaries and on the boundaries
5645 of lower-precedence decorations.
5646 */
5647 static mark(spec) {
5648 return new MarkDecoration(spec);
5649 }
5650 /**
5651 Create a widget decoration, which displays a DOM element at the
5652 given position.
5653 */
5654 static widget(spec) {
5655 let side = Math.max(-10000, Math.min(10000, spec.side || 0)), block = !!spec.block;
5656 side += (block && !spec.inlineOrder)
5657 ? (side > 0 ? 300000000 /* Side.BlockAfter */ : -400000000 /* Side.BlockBefore */)
5658 : (side > 0 ? 100000000 /* Side.InlineAfter */ : -100000000 /* Side.InlineBefore */);
5659 return new PointDecoration(spec, side, side, block, spec.widget || null, false);
5660 }
5661 /**
5662 Create a replace decoration which replaces the given range with
5663 a widget, or simply hides it.
5664 */
5665 static replace(spec) {
5666 let block = !!spec.block, startSide, endSide;
5667 if (spec.isBlockGap) {
5668 startSide = -500000000 /* Side.GapStart */;
5669 endSide = 400000000 /* Side.GapEnd */;
5670 }
5671 else {
5672 let { start, end } = getInclusive(spec, block);
5673 startSide = (start ? (block ? -300000000 /* Side.BlockIncStart */ : -1 /* Side.InlineIncStart */) : 500000000 /* Side.NonIncStart */) - 1;
5674 endSide = (end ? (block ? 200000000 /* Side.BlockIncEnd */ : 1 /* Side.InlineIncEnd */) : -600000000 /* Side.NonIncEnd */) + 1;
5675 }
5676 return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
5677 }
5678 /**
5679 Create a line decoration, which can add DOM attributes to the
5680 line starting at the given position.
5681 */
5682 static line(spec) {
5683 return new LineDecoration(spec);
5684 }
5685 /**
5686 Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
5687 decorated range or ranges. If the ranges aren't already sorted,
5688 pass `true` for `sort` to make the library sort them for you.
5689 */
5690 static set(of, sort = false) {
5691 return RangeSet.of(of, sort);
5692 }
5693 /**
5694 @internal
5695 */
5696 hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }
5697 }
5698 /**
5699 The empty set of decorations.
5700 */
5701 Decoration.none = RangeSet.empty;
5702 class MarkDecoration extends Decoration {
5703 constructor(spec) {
5704 let { start, end } = getInclusive(spec);
5705 super(start ? -1 /* Side.InlineIncStart */ : 500000000 /* Side.NonIncStart */, end ? 1 /* Side.InlineIncEnd */ : -600000000 /* Side.NonIncEnd */, null, spec);
5706 this.tagName = spec.tagName || "span";
5707 this.class = spec.class || "";
5708 this.attrs = spec.attributes || null;
5709 }
5710 eq(other) {
5711 var _a, _b;
5712 return this == other ||
5713 other instanceof MarkDecoration &&
5714 this.tagName == other.tagName &&
5715 (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)) &&
5716 attrsEq(this.attrs, other.attrs, "class");
5717 }
5718 range(from, to = from) {
5719 if (from >= to)
5720 throw new RangeError("Mark decorations may not be empty");
5721 return super.range(from, to);
5722 }
5723 }
5724 MarkDecoration.prototype.point = false;
5725 class LineDecoration extends Decoration {
5726 constructor(spec) {
5727 super(-200000000 /* Side.Line */, -200000000 /* Side.Line */, null, spec);
5728 }
5729 eq(other) {
5730 return other instanceof LineDecoration &&
5731 this.spec.class == other.spec.class &&
5732 attrsEq(this.spec.attributes, other.spec.attributes);
5733 }
5734 range(from, to = from) {
5735 if (to != from)
5736 throw new RangeError("Line decoration ranges must be zero-length");
5737 return super.range(from, to);
5738 }
5739 }
5740 LineDecoration.prototype.mapMode = exports.MapMode.TrackBefore;
5741 LineDecoration.prototype.point = true;
5742 class PointDecoration extends Decoration {
5743 constructor(spec, startSide, endSide, block, widget, isReplace) {
5744 super(startSide, endSide, widget, spec);
5745 this.block = block;
5746 this.isReplace = isReplace;
5747 this.mapMode = !block ? exports.MapMode.TrackDel : startSide <= 0 ? exports.MapMode.TrackBefore : exports.MapMode.TrackAfter;
5748 }
5749 // Only relevant when this.block == true
5750 get type() {
5751 return this.startSide != this.endSide ? exports.BlockType.WidgetRange
5752 : this.startSide <= 0 ? exports.BlockType.WidgetBefore : exports.BlockType.WidgetAfter;
5753 }
5754 get heightRelevant() {
5755 return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
5756 }
5757 eq(other) {
5758 return other instanceof PointDecoration &&
5759 widgetsEq(this.widget, other.widget) &&
5760 this.block == other.block &&
5761 this.startSide == other.startSide && this.endSide == other.endSide;
5762 }
5763 range(from, to = from) {
5764 if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide <= 0)))
5765 throw new RangeError("Invalid range for replacement decoration");
5766 if (!this.isReplace && to != from)
5767 throw new RangeError("Widget decorations can only have zero-length ranges");
5768 return super.range(from, to);
5769 }
5770 }
5771 PointDecoration.prototype.point = true;
5772 function getInclusive(spec, block = false) {
5773 let { inclusiveStart: start, inclusiveEnd: end } = spec;
5774 if (start == null)
5775 start = spec.inclusive;
5776 if (end == null)
5777 end = spec.inclusive;
5778 return { start: start !== null && start !== void 0 ? start : block, end: end !== null && end !== void 0 ? end : block };
5779 }
5780 function widgetsEq(a, b) {
5781 return a == b || !!(a && b && a.compare(b));
5782 }
5783 function addRange(from, to, ranges, margin = 0) {
5784 let last = ranges.length - 1;
5785 if (last >= 0 && ranges[last] + margin >= from)
5786 ranges[last] = Math.max(ranges[last], to);
5787 else
5788 ranges.push(from, to);
5789 }
5790
5791 class ContentBuilder {
5792 constructor(doc, pos, end, disallowBlockEffectsFor) {
5793 this.doc = doc;
5794 this.pos = pos;
5795 this.end = end;
5796 this.disallowBlockEffectsFor = disallowBlockEffectsFor;
5797 this.content = [];
5798 this.curLine = null;
5799 this.breakAtStart = 0;
5800 this.pendingBuffer = 0 /* Buf.No */;
5801 this.bufferMarks = [];
5802 // Set to false directly after a widget that covers the position after it
5803 this.atCursorPos = true;
5804 this.openStart = -1;
5805 this.openEnd = -1;
5806 this.text = "";
5807 this.textOff = 0;
5808 this.cursor = doc.iter();
5809 this.skip = pos;
5810 }
5811 posCovered() {
5812 if (this.content.length == 0)
5813 return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
5814 let last = this.content[this.content.length - 1];
5815 return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);
5816 }
5817 getLine() {
5818 if (!this.curLine) {
5819 this.content.push(this.curLine = new LineView);
5820 this.atCursorPos = true;
5821 }
5822 return this.curLine;
5823 }
5824 flushBuffer(active = this.bufferMarks) {
5825 if (this.pendingBuffer) {
5826 this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);
5827 this.pendingBuffer = 0 /* Buf.No */;
5828 }
5829 }
5830 addBlockWidget(view) {
5831 this.flushBuffer();
5832 this.curLine = null;
5833 this.content.push(view);
5834 }
5835 finish(openEnd) {
5836 if (this.pendingBuffer && openEnd <= this.bufferMarks.length)
5837 this.flushBuffer();
5838 else
5839 this.pendingBuffer = 0 /* Buf.No */;
5840 if (!this.posCovered() &&
5841 !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView))
5842 this.getLine();
5843 }
5844 buildText(length, active, openStart) {
5845 while (length > 0) {
5846 if (this.textOff == this.text.length) {
5847 let { value, lineBreak, done } = this.cursor.next(this.skip);
5848 this.skip = 0;
5849 if (done)
5850 throw new Error("Ran out of text content when drawing inline views");
5851 if (lineBreak) {
5852 if (!this.posCovered())
5853 this.getLine();
5854 if (this.content.length)
5855 this.content[this.content.length - 1].breakAfter = 1;
5856 else
5857 this.breakAtStart = 1;
5858 this.flushBuffer();
5859 this.curLine = null;
5860 this.atCursorPos = true;
5861 length--;
5862 continue;
5863 }
5864 else {
5865 this.text = value;
5866 this.textOff = 0;
5867 }
5868 }
5869 let take = Math.min(this.text.length - this.textOff, length, 512 /* T.Chunk */);
5870 this.flushBuffer(active.slice(active.length - openStart));
5871 this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
5872 this.atCursorPos = true;
5873 this.textOff += take;
5874 length -= take;
5875 openStart = 0;
5876 }
5877 }
5878 span(from, to, active, openStart) {
5879 this.buildText(to - from, active, openStart);
5880 this.pos = to;
5881 if (this.openStart < 0)
5882 this.openStart = openStart;
5883 }
5884 point(from, to, deco, active, openStart, index) {
5885 if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {
5886 if (deco.block)
5887 throw new RangeError("Block decorations may not be specified via plugins");
5888 if (to > this.doc.lineAt(this.pos).to)
5889 throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
5890 }
5891 let len = to - from;
5892 if (deco instanceof PointDecoration) {
5893 if (deco.block) {
5894 if (deco.startSide > 0 && !this.posCovered())
5895 this.getLine();
5896 this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, deco));
5897 }
5898 else {
5899 let view = WidgetView.create(deco.widget || new NullWidget("span"), len, len ? 0 : deco.startSide);
5900 let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length &&
5901 (from < to || deco.startSide > 0);
5902 let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
5903 let line = this.getLine();
5904 if (this.pendingBuffer == 2 /* Buf.IfCursor */ && !cursorBefore && !view.isEditable)
5905 this.pendingBuffer = 0 /* Buf.No */;
5906 this.flushBuffer(active);
5907 if (cursorBefore) {
5908 line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
5909 openStart = active.length + Math.max(0, openStart - active.length);
5910 }
5911 line.append(wrapMarks(view, active), openStart);
5912 this.atCursorPos = cursorAfter;
5913 this.pendingBuffer = !cursorAfter ? 0 /* Buf.No */ : from < to || openStart > active.length ? 1 /* Buf.Yes */ : 2 /* Buf.IfCursor */;
5914 if (this.pendingBuffer)
5915 this.bufferMarks = active.slice();
5916 }
5917 }
5918 else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration
5919 this.getLine().addLineDeco(deco);
5920 }
5921 if (len) {
5922 // Advance the iterator past the replaced content
5923 if (this.textOff + len <= this.text.length) {
5924 this.textOff += len;
5925 }
5926 else {
5927 this.skip += len - (this.text.length - this.textOff);
5928 this.text = "";
5929 this.textOff = 0;
5930 }
5931 this.pos = to;
5932 }
5933 if (this.openStart < 0)
5934 this.openStart = openStart;
5935 }
5936 static build(text, from, to, decorations, dynamicDecorationMap) {
5937 let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);
5938 builder.openEnd = RangeSet.spans(decorations, from, to, builder);
5939 if (builder.openStart < 0)
5940 builder.openStart = builder.openEnd;
5941 builder.finish(builder.openEnd);
5942 return builder;
5943 }
5944 }
5945 function wrapMarks(view, active) {
5946 for (let mark of active)
5947 view = new MarkView(mark, [view], view.length);
5948 return view;
5949 }
5950 class NullWidget extends WidgetType {
5951 constructor(tag) {
5952 super();
5953 this.tag = tag;
5954 }
5955 eq(other) { return other.tag == this.tag; }
5956 toDOM() { return document.createElement(this.tag); }
5957 updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }
5958 get isHidden() { return true; }
5959 }
5960
5961 const clickAddsSelectionRange = /*@__PURE__*/Facet.define();
5962 const dragMovesSelection$1 = /*@__PURE__*/Facet.define();
5963 const mouseSelectionStyle = /*@__PURE__*/Facet.define();
5964 const exceptionSink = /*@__PURE__*/Facet.define();
5965 const updateListener = /*@__PURE__*/Facet.define();
5966 const inputHandler = /*@__PURE__*/Facet.define();
5967 const focusChangeEffect = /*@__PURE__*/Facet.define();
5968 const perLineTextDirection = /*@__PURE__*/Facet.define({
5969 combine: values => values.some(x => x)
5970 });
5971 const nativeSelectionHidden = /*@__PURE__*/Facet.define({
5972 combine: values => values.some(x => x)
5973 });
5974 class ScrollTarget {
5975 constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5,
5976 // This data structure is abused to also store precise scroll
5977 // snapshots, instead of a `scrollIntoView` request. When this
5978 // flag is `true`, `range` points at a position in the reference
5979 // line, `yMargin` holds the difference between the top of that
5980 // line and the top of the editor, and `xMargin` holds the
5981 // editor's `scrollLeft`.
5982 isSnapshot = false) {
5983 this.range = range;
5984 this.y = y;
5985 this.x = x;
5986 this.yMargin = yMargin;
5987 this.xMargin = xMargin;
5988 this.isSnapshot = isSnapshot;
5989 }
5990 map(changes) {
5991 return changes.empty ? this :
5992 new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
5993 }
5994 clip(state) {
5995 return this.range.to <= state.doc.length ? this :
5996 new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
5997 }
5998 }
5999 const scrollIntoView = /*@__PURE__*/StateEffect.define({ map: (t, ch) => t.map(ch) });
6000 /**
6001 Log or report an unhandled exception in client code. Should
6002 probably only be used by extension code that allows client code to
6003 provide functions, and calls those functions in a context where an
6004 exception can't be propagated to calling code in a reasonable way
6005 (for example when in an event handler).
6006
6007 Either calls a handler registered with
6008 [`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
6009 `window.onerror`, if defined, or `console.error` (in which case
6010 it'll pass `context`, when given, as first argument).
6011 */
6012 function logException(state, exception, context) {
6013 let handler = state.facet(exceptionSink);
6014 if (handler.length)
6015 handler[0](exception);
6016 else if (window.onerror)
6017 window.onerror(String(exception), context, undefined, undefined, exception);
6018 else if (context)
6019 console.error(context + ":", exception);
6020 else
6021 console.error(exception);
6022 }
6023 const editable = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : true });
6024 let nextPluginID = 0;
6025 const viewPlugin = /*@__PURE__*/Facet.define();
6026 /**
6027 View plugins associate stateful values with a view. They can
6028 influence the way the content is drawn, and are notified of things
6029 that happen in the view.
6030 */
6031 class ViewPlugin {
6032 constructor(
6033 /**
6034 @internal
6035 */
6036 id,
6037 /**
6038 @internal
6039 */
6040 create,
6041 /**
6042 @internal
6043 */
6044 domEventHandlers,
6045 /**
6046 @internal
6047 */
6048 domEventObservers, buildExtensions) {
6049 this.id = id;
6050 this.create = create;
6051 this.domEventHandlers = domEventHandlers;
6052 this.domEventObservers = domEventObservers;
6053 this.extension = buildExtensions(this);
6054 }
6055 /**
6056 Define a plugin from a constructor function that creates the
6057 plugin's value, given an editor view.
6058 */
6059 static define(create, spec) {
6060 const { eventHandlers, eventObservers, provide, decorations: deco } = spec || {};
6061 return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {
6062 let ext = [viewPlugin.of(plugin)];
6063 if (deco)
6064 ext.push(decorations.of(view => {
6065 let pluginInst = view.plugin(plugin);
6066 return pluginInst ? deco(pluginInst) : Decoration.none;
6067 }));
6068 if (provide)
6069 ext.push(provide(plugin));
6070 return ext;
6071 });
6072 }
6073 /**
6074 Create a plugin for a class whose constructor takes a single
6075 editor view as argument.
6076 */
6077 static fromClass(cls, spec) {
6078 return ViewPlugin.define(view => new cls(view), spec);
6079 }
6080 }
6081 class PluginInstance {
6082 constructor(spec) {
6083 this.spec = spec;
6084 // When starting an update, all plugins have this field set to the
6085 // update object, indicating they need to be updated. When finished
6086 // updating, it is set to `false`. Retrieving a plugin that needs to
6087 // be updated with `view.plugin` forces an eager update.
6088 this.mustUpdate = null;
6089 // This is null when the plugin is initially created, but
6090 // initialized on the first update.
6091 this.value = null;
6092 }
6093 update(view) {
6094 if (!this.value) {
6095 if (this.spec) {
6096 try {
6097 this.value = this.spec.create(view);
6098 }
6099 catch (e) {
6100 logException(view.state, e, "CodeMirror plugin crashed");
6101 this.deactivate();
6102 }
6103 }
6104 }
6105 else if (this.mustUpdate) {
6106 let update = this.mustUpdate;
6107 this.mustUpdate = null;
6108 if (this.value.update) {
6109 try {
6110 this.value.update(update);
6111 }
6112 catch (e) {
6113 logException(update.state, e, "CodeMirror plugin crashed");
6114 if (this.value.destroy)
6115 try {
6116 this.value.destroy();
6117 }
6118 catch (_) { }
6119 this.deactivate();
6120 }
6121 }
6122 }
6123 return this;
6124 }
6125 destroy(view) {
6126 var _a;
6127 if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {
6128 try {
6129 this.value.destroy();
6130 }
6131 catch (e) {
6132 logException(view.state, e, "CodeMirror plugin crashed");
6133 }
6134 }
6135 }
6136 deactivate() {
6137 this.spec = this.value = null;
6138 }
6139 }
6140 const editorAttributes = /*@__PURE__*/Facet.define();
6141 const contentAttributes = /*@__PURE__*/Facet.define();
6142 // Provide decorations
6143 const decorations = /*@__PURE__*/Facet.define();
6144 const atomicRanges = /*@__PURE__*/Facet.define();
6145 const bidiIsolatedRanges = /*@__PURE__*/Facet.define();
6146 function getIsolatedRanges(view, from, to) {
6147 let isolates = view.state.facet(bidiIsolatedRanges);
6148 if (!isolates.length)
6149 return isolates;
6150 let sets = isolates.map(i => i instanceof Function ? i(view) : i);
6151 let result = [];
6152 RangeSet.spans(sets, from, to, {
6153 point() { },
6154 span(from, to, active, open) {
6155 let level = result;
6156 for (let i = active.length - 1; i >= 0; i--, open--) {
6157 let iso = active[i].spec.bidiIsolate, update;
6158 if (iso == null)
6159 continue;
6160 if (open > 0 && level.length &&
6161 (update = level[level.length - 1]).to == from && update.direction == iso) {
6162 update.to = to;
6163 level = update.inner;
6164 }
6165 else {
6166 let add = { from, to, direction: iso, inner: [] };
6167 level.push(add);
6168 level = add.inner;
6169 }
6170 }
6171 }
6172 });
6173 return result;
6174 }
6175 const scrollMargins = /*@__PURE__*/Facet.define();
6176 function getScrollMargins(view) {
6177 let left = 0, right = 0, top = 0, bottom = 0;
6178 for (let source of view.state.facet(scrollMargins)) {
6179 let m = source(view);
6180 if (m) {
6181 if (m.left != null)
6182 left = Math.max(left, m.left);
6183 if (m.right != null)
6184 right = Math.max(right, m.right);
6185 if (m.top != null)
6186 top = Math.max(top, m.top);
6187 if (m.bottom != null)
6188 bottom = Math.max(bottom, m.bottom);
6189 }
6190 }
6191 return { left, right, top, bottom };
6192 }
6193 const styleModule = /*@__PURE__*/Facet.define();
6194 class ChangedRange {
6195 constructor(fromA, toA, fromB, toB) {
6196 this.fromA = fromA;
6197 this.toA = toA;
6198 this.fromB = fromB;
6199 this.toB = toB;
6200 }
6201 join(other) {
6202 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));
6203 }
6204 addToSet(set) {
6205 let i = set.length, me = this;
6206 for (; i > 0; i--) {
6207 let range = set[i - 1];
6208 if (range.fromA > me.toA)
6209 continue;
6210 if (range.toA < me.fromA)
6211 break;
6212 me = me.join(range);
6213 set.splice(i - 1, 1);
6214 }
6215 set.splice(i, 0, me);
6216 return set;
6217 }
6218 static extendWithRanges(diff, ranges) {
6219 if (ranges.length == 0)
6220 return diff;
6221 let result = [];
6222 for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
6223 let next = dI == diff.length ? null : diff[dI], off = posA - posB;
6224 let end = next ? next.fromB : 1e9;
6225 while (rI < ranges.length && ranges[rI] < end) {
6226 let from = ranges[rI], to = ranges[rI + 1];
6227 let fromB = Math.max(posB, from), toB = Math.min(end, to);
6228 if (fromB <= toB)
6229 new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
6230 if (to > end)
6231 break;
6232 else
6233 rI += 2;
6234 }
6235 if (!next)
6236 return result;
6237 new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
6238 posA = next.toA;
6239 posB = next.toB;
6240 }
6241 }
6242 }
6243 /**
6244 View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
6245 class, which describe what happened, whenever the view is updated.
6246 */
6247 class ViewUpdate {
6248 constructor(
6249 /**
6250 The editor view that the update is associated with.
6251 */
6252 view,
6253 /**
6254 The new editor state.
6255 */
6256 state,
6257 /**
6258 The transactions involved in the update. May be empty.
6259 */
6260 transactions) {
6261 this.view = view;
6262 this.state = state;
6263 this.transactions = transactions;
6264 /**
6265 @internal
6266 */
6267 this.flags = 0;
6268 this.startState = view.state;
6269 this.changes = ChangeSet.empty(this.startState.doc.length);
6270 for (let tr of transactions)
6271 this.changes = this.changes.compose(tr.changes);
6272 let changedRanges = [];
6273 this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
6274 this.changedRanges = changedRanges;
6275 }
6276 /**
6277 @internal
6278 */
6279 static create(view, state, transactions) {
6280 return new ViewUpdate(view, state, transactions);
6281 }
6282 /**
6283 Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
6284 [visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
6285 update.
6286 */
6287 get viewportChanged() {
6288 return (this.flags & 4 /* UpdateFlag.Viewport */) > 0;
6289 }
6290 /**
6291 Indicates whether the height of a block element in the editor
6292 changed in this update.
6293 */
6294 get heightChanged() {
6295 return (this.flags & 2 /* UpdateFlag.Height */) > 0;
6296 }
6297 /**
6298 Returns true when the document was modified or the size of the
6299 editor, or elements within the editor, changed.
6300 */
6301 get geometryChanged() {
6302 return this.docChanged || (this.flags & (8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */)) > 0;
6303 }
6304 /**
6305 True when this update indicates a focus change.
6306 */
6307 get focusChanged() {
6308 return (this.flags & 1 /* UpdateFlag.Focus */) > 0;
6309 }
6310 /**
6311 Whether the document changed in this update.
6312 */
6313 get docChanged() {
6314 return !this.changes.empty;
6315 }
6316 /**
6317 Whether the selection was explicitly set in this update.
6318 */
6319 get selectionSet() {
6320 return this.transactions.some(tr => tr.selection);
6321 }
6322 /**
6323 @internal
6324 */
6325 get empty() { return this.flags == 0 && this.transactions.length == 0; }
6326 }
6327
6328 /**
6329 Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
6330 */
6331 exports.Direction = /*@__PURE__*/(function (Direction) {
6332 // (These are chosen to match the base levels, in bidi algorithm
6333 // terms, of spans in that direction.)
6334 /**
6335 Left-to-right.
6336 */
6337 Direction[Direction["LTR"] = 0] = "LTR";
6338 /**
6339 Right-to-left.
6340 */
6341 Direction[Direction["RTL"] = 1] = "RTL";
6342 return Direction})(exports.Direction || (exports.Direction = {}));
6343 const LTR = exports.Direction.LTR, RTL = exports.Direction.RTL;
6344 // Decode a string with each type encoded as log2(type)
6345 function dec(str) {
6346 let result = [];
6347 for (let i = 0; i < str.length; i++)
6348 result.push(1 << +str[i]);
6349 return result;
6350 }
6351 // Character types for codepoints 0 to 0xf8
6352 const LowTypes = /*@__PURE__*/dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
6353 // Character types for codepoints 0x600 to 0x6f9
6354 const ArabicTypes = /*@__PURE__*/dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
6355 const Brackets = /*@__PURE__*/Object.create(null), BracketStack = [];
6356 // There's a lot more in
6357 // https://www.unicode.org/Public/UCD/latest/ucd/BidiBrackets.txt,
6358 // which are left out to keep code size down.
6359 for (let p of ["()", "[]", "{}"]) {
6360 let l = /*@__PURE__*/p.charCodeAt(0), r = /*@__PURE__*/p.charCodeAt(1);
6361 Brackets[l] = r;
6362 Brackets[r] = -l;
6363 }
6364 function charType(ch) {
6365 return ch <= 0xf7 ? LowTypes[ch] :
6366 0x590 <= ch && ch <= 0x5f4 ? 2 /* T.R */ :
6367 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
6368 0x6ee <= ch && ch <= 0x8ac ? 4 /* T.AL */ :
6369 0x2000 <= ch && ch <= 0x200c ? 256 /* T.NI */ :
6370 0xfb50 <= ch && ch <= 0xfdff ? 4 /* T.AL */ : 1 /* T.L */;
6371 }
6372 const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
6373 /**
6374 Represents a contiguous range of text that has a single direction
6375 (as in left-to-right or right-to-left).
6376 */
6377 class BidiSpan {
6378 /**
6379 The direction of this span.
6380 */
6381 get dir() { return this.level % 2 ? RTL : LTR; }
6382 /**
6383 @internal
6384 */
6385 constructor(
6386 /**
6387 The start of the span (relative to the start of the line).
6388 */
6389 from,
6390 /**
6391 The end of the span.
6392 */
6393 to,
6394 /**
6395 The ["bidi
6396 level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)
6397 of the span (in this context, 0 means
6398 left-to-right, 1 means right-to-left, 2 means left-to-right
6399 number inside right-to-left text).
6400 */
6401 level) {
6402 this.from = from;
6403 this.to = to;
6404 this.level = level;
6405 }
6406 /**
6407 @internal
6408 */
6409 side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }
6410 /**
6411 @internal
6412 */
6413 static find(order, index, level, assoc) {
6414 let maybe = -1;
6415 for (let i = 0; i < order.length; i++) {
6416 let span = order[i];
6417 if (span.from <= index && span.to >= index) {
6418 if (span.level == level)
6419 return i;
6420 // When multiple spans match, if assoc != 0, take the one that
6421 // covers that side, otherwise take the one with the minimum
6422 // level.
6423 if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))
6424 maybe = i;
6425 }
6426 }
6427 if (maybe < 0)
6428 throw new RangeError("Index out of range");
6429 return maybe;
6430 }
6431 }
6432 function isolatesEq(a, b) {
6433 if (a.length != b.length)
6434 return false;
6435 for (let i = 0; i < a.length; i++) {
6436 let iA = a[i], iB = b[i];
6437 if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner))
6438 return false;
6439 }
6440 return true;
6441 }
6442 // Reused array of character types
6443 const types = [];
6444 // Fill in the character types (in `types`) from `from` to `to` and
6445 // apply W normalization rules.
6446 function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
6447 for (let iI = 0; iI <= isolates.length; iI++) {
6448 let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6449 let prevType = iI ? 256 /* T.NI */ : outerType;
6450 // W1. Examine each non-spacing mark (NSM) in the level run, and
6451 // change the type of the NSM to the type of the previous
6452 // character. If the NSM is at the start of the level run, it will
6453 // get the type of sor.
6454 // W2. Search backwards from each instance of a European number
6455 // until the first strong type (R, L, AL, or sor) is found. If an
6456 // AL is found, change the type of the European number to Arabic
6457 // number.
6458 // W3. Change all ALs to R.
6459 // (Left after this: L, R, EN, AN, ET, CS, NI)
6460 for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6461 let type = charType(line.charCodeAt(i));
6462 if (type == 512 /* T.NSM */)
6463 type = prev;
6464 else if (type == 8 /* T.EN */ && prevStrong == 4 /* T.AL */)
6465 type = 16 /* T.AN */;
6466 types[i] = type == 4 /* T.AL */ ? 2 /* T.R */ : type;
6467 if (type & 7 /* T.Strong */)
6468 prevStrong = type;
6469 prev = type;
6470 }
6471 // W5. A sequence of European terminators adjacent to European
6472 // numbers changes to all European numbers.
6473 // W6. Otherwise, separators and terminators change to Other
6474 // Neutral.
6475 // W7. Search backwards from each instance of a European number
6476 // until the first strong type (R, L, or sor) is found. If an L is
6477 // found, then change the type of the European number to L.
6478 // (Left after this: L, R, EN+AN, NI)
6479 for (let i = from, prev = prevType, prevStrong = prevType; i < to; i++) {
6480 let type = types[i];
6481 if (type == 128 /* T.CS */) {
6482 if (i < to - 1 && prev == types[i + 1] && (prev & 24 /* T.Num */))
6483 type = types[i] = prev;
6484 else
6485 types[i] = 256 /* T.NI */;
6486 }
6487 else if (type == 64 /* T.ET */) {
6488 let end = i + 1;
6489 while (end < to && types[end] == 64 /* T.ET */)
6490 end++;
6491 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 */;
6492 for (let j = i; j < end; j++)
6493 types[j] = replace;
6494 i = end - 1;
6495 }
6496 else if (type == 8 /* T.EN */ && prevStrong == 1 /* T.L */) {
6497 types[i] = 1 /* T.L */;
6498 }
6499 prev = type;
6500 if (type & 7 /* T.Strong */)
6501 prevStrong = type;
6502 }
6503 }
6504 }
6505 // Process brackets throughout a run sequence.
6506 function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
6507 let oppositeType = outerType == 1 /* T.L */ ? 2 /* T.R */ : 1 /* T.L */;
6508 for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
6509 let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6510 // N0. Process bracket pairs in an isolating run sequence
6511 // sequentially in the logical order of the text positions of the
6512 // opening paired brackets using the logic given below. Within this
6513 // scope, bidirectional types EN and AN are treated as R.
6514 for (let i = from, ch, br, type; i < to; i++) {
6515 // Keeps [startIndex, type, strongSeen] triples for each open
6516 // bracket on BracketStack.
6517 if (br = Brackets[ch = line.charCodeAt(i)]) {
6518 if (br < 0) { // Closing bracket
6519 for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6520 if (BracketStack[sJ + 1] == -br) {
6521 let flags = BracketStack[sJ + 2];
6522 let type = (flags & 2 /* Bracketed.EmbedInside */) ? outerType :
6523 !(flags & 4 /* Bracketed.OppositeInside */) ? 0 :
6524 (flags & 1 /* Bracketed.OppositeBefore */) ? oppositeType : outerType;
6525 if (type)
6526 types[i] = types[BracketStack[sJ]] = type;
6527 sI = sJ;
6528 break;
6529 }
6530 }
6531 }
6532 else if (BracketStack.length == 189 /* Bracketed.MaxDepth */) {
6533 break;
6534 }
6535 else {
6536 BracketStack[sI++] = i;
6537 BracketStack[sI++] = ch;
6538 BracketStack[sI++] = context;
6539 }
6540 }
6541 else if ((type = types[i]) == 2 /* T.R */ || type == 1 /* T.L */) {
6542 let embed = type == outerType;
6543 context = embed ? 0 : 1 /* Bracketed.OppositeBefore */;
6544 for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
6545 let cur = BracketStack[sJ + 2];
6546 if (cur & 2 /* Bracketed.EmbedInside */)
6547 break;
6548 if (embed) {
6549 BracketStack[sJ + 2] |= 2 /* Bracketed.EmbedInside */;
6550 }
6551 else {
6552 if (cur & 4 /* Bracketed.OppositeInside */)
6553 break;
6554 BracketStack[sJ + 2] |= 4 /* Bracketed.OppositeInside */;
6555 }
6556 }
6557 }
6558 }
6559 }
6560 }
6561 function processNeutrals(rFrom, rTo, isolates, outerType) {
6562 for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
6563 let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo;
6564 // N1. A sequence of neutrals takes the direction of the
6565 // surrounding strong text if the text on both sides has the same
6566 // direction. European and Arabic numbers act as if they were R in
6567 // terms of their influence on neutrals. Start-of-level-run (sor)
6568 // and end-of-level-run (eor) are used at level run boundaries.
6569 // N2. Any remaining neutrals take the embedding direction.
6570 // (Left after this: L, R, EN+AN)
6571 for (let i = from; i < to;) {
6572 let type = types[i];
6573 if (type == 256 /* T.NI */) {
6574 let end = i + 1;
6575 for (;;) {
6576 if (end == to) {
6577 if (iI == isolates.length)
6578 break;
6579 end = isolates[iI++].to;
6580 to = iI < isolates.length ? isolates[iI].from : rTo;
6581 }
6582 else if (types[end] == 256 /* T.NI */) {
6583 end++;
6584 }
6585 else {
6586 break;
6587 }
6588 }
6589 let beforeL = prev == 1 /* T.L */;
6590 let afterL = (end < rTo ? types[end] : outerType) == 1 /* T.L */;
6591 let replace = beforeL == afterL ? (beforeL ? 1 /* T.L */ : 2 /* T.R */) : outerType;
6592 for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i;) {
6593 if (j == fromJ) {
6594 j = isolates[--jI].from;
6595 fromJ = jI ? isolates[jI - 1].to : rFrom;
6596 }
6597 types[--j] = replace;
6598 }
6599 i = end;
6600 }
6601 else {
6602 prev = type;
6603 i++;
6604 }
6605 }
6606 }
6607 }
6608 // Find the contiguous ranges of character types in a given range, and
6609 // emit spans for them. Flip the order of the spans as appropriate
6610 // based on the level, and call through to compute the spans for
6611 // isolates at the proper point.
6612 function emitSpans(line, from, to, level, baseLevel, isolates, order) {
6613 let ourType = level % 2 ? 2 /* T.R */ : 1 /* T.L */;
6614 if ((level % 2) == (baseLevel % 2)) { // Same dir as base direction, don't flip
6615 for (let iCh = from, iI = 0; iCh < to;) {
6616 // Scan a section of characters in direction ourType, unless
6617 // there's another type of char right after iCh, in which case
6618 // we scan a section of other characters (which, if ourType ==
6619 // T.L, may contain both T.R and T.AN chars).
6620 let sameDir = true, isNum = false;
6621 if (iI == isolates.length || iCh < isolates[iI].from) {
6622 let next = types[iCh];
6623 if (next != ourType) {
6624 sameDir = false;
6625 isNum = next == 16 /* T.AN */;
6626 }
6627 }
6628 // Holds an array of isolates to pass to a recursive call if we
6629 // must recurse (to distinguish T.AN inside an RTL section in
6630 // LTR text), null if we can emit directly
6631 let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6632 let localLevel = sameDir ? level : level + 1;
6633 let iScan = iCh;
6634 run: for (;;) {
6635 if (iI < isolates.length && iScan == isolates[iI].from) {
6636 if (isNum)
6637 break run;
6638 let iso = isolates[iI];
6639 // Scan ahead to verify that there is another char in this dir after the isolate(s)
6640 if (!sameDir)
6641 for (let upto = iso.to, jI = iI + 1;;) {
6642 if (upto == to)
6643 break run;
6644 if (jI < isolates.length && isolates[jI].from == upto)
6645 upto = isolates[jI++].to;
6646 else if (types[upto] == ourType)
6647 break run;
6648 else
6649 break;
6650 }
6651 iI++;
6652 if (recurse) {
6653 recurse.push(iso);
6654 }
6655 else {
6656 if (iso.from > iCh)
6657 order.push(new BidiSpan(iCh, iso.from, localLevel));
6658 let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6659 computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6660 iCh = iso.to;
6661 }
6662 iScan = iso.to;
6663 }
6664 else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) {
6665 break;
6666 }
6667 else {
6668 iScan++;
6669 }
6670 }
6671 if (recurse)
6672 emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);
6673 else if (iCh < iScan)
6674 order.push(new BidiSpan(iCh, iScan, localLevel));
6675 iCh = iScan;
6676 }
6677 }
6678 else {
6679 // Iterate in reverse to flip the span order. Same code again, but
6680 // going from the back of the section to the front
6681 for (let iCh = to, iI = isolates.length; iCh > from;) {
6682 let sameDir = true, isNum = false;
6683 if (!iI || iCh > isolates[iI - 1].to) {
6684 let next = types[iCh - 1];
6685 if (next != ourType) {
6686 sameDir = false;
6687 isNum = next == 16 /* T.AN */;
6688 }
6689 }
6690 let recurse = !sameDir && ourType == 1 /* T.L */ ? [] : null;
6691 let localLevel = sameDir ? level : level + 1;
6692 let iScan = iCh;
6693 run: for (;;) {
6694 if (iI && iScan == isolates[iI - 1].to) {
6695 if (isNum)
6696 break run;
6697 let iso = isolates[--iI];
6698 // Scan ahead to verify that there is another char in this dir after the isolate(s)
6699 if (!sameDir)
6700 for (let upto = iso.from, jI = iI;;) {
6701 if (upto == from)
6702 break run;
6703 if (jI && isolates[jI - 1].to == upto)
6704 upto = isolates[--jI].from;
6705 else if (types[upto - 1] == ourType)
6706 break run;
6707 else
6708 break;
6709 }
6710 if (recurse) {
6711 recurse.push(iso);
6712 }
6713 else {
6714 if (iso.to < iCh)
6715 order.push(new BidiSpan(iso.to, iCh, localLevel));
6716 let dirSwap = (iso.direction == LTR) != !(localLevel % 2);
6717 computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
6718 iCh = iso.from;
6719 }
6720 iScan = iso.from;
6721 }
6722 else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) {
6723 break;
6724 }
6725 else {
6726 iScan--;
6727 }
6728 }
6729 if (recurse)
6730 emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);
6731 else if (iScan < iCh)
6732 order.push(new BidiSpan(iScan, iCh, localLevel));
6733 iCh = iScan;
6734 }
6735 }
6736 }
6737 function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
6738 let outerType = (level % 2 ? 2 /* T.R */ : 1 /* T.L */);
6739 computeCharTypes(line, from, to, isolates, outerType);
6740 processBracketPairs(line, from, to, isolates, outerType);
6741 processNeutrals(from, to, isolates, outerType);
6742 emitSpans(line, from, to, level, baseLevel, isolates, order);
6743 }
6744 function computeOrder(line, direction, isolates) {
6745 if (!line)
6746 return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
6747 if (direction == LTR && !isolates.length && !BidiRE.test(line))
6748 return trivialOrder(line.length);
6749 if (isolates.length)
6750 while (line.length > types.length)
6751 types[types.length] = 256 /* T.NI */; // Make sure types array has no gaps
6752 let order = [], level = direction == LTR ? 0 : 1;
6753 computeSectionOrder(line, level, level, isolates, 0, line.length, order);
6754 return order;
6755 }
6756 function trivialOrder(length) {
6757 return [new BidiSpan(0, length, 0)];
6758 }
6759 let movedOver = "";
6760 function moveVisually(line, order, dir, start, forward) {
6761 var _a;
6762 let startIndex = start.head - line.from, spanI = -1;
6763 if (startIndex == 0) {
6764 if (!forward || !line.length)
6765 return null;
6766 if (order[0].level != dir) {
6767 startIndex = order[0].side(false, dir);
6768 spanI = 0;
6769 }
6770 }
6771 else if (startIndex == line.length) {
6772 if (forward)
6773 return null;
6774 let last = order[order.length - 1];
6775 if (last.level != dir) {
6776 startIndex = last.side(true, dir);
6777 spanI = order.length - 1;
6778 }
6779 }
6780 if (spanI < 0)
6781 spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);
6782 let span = order[spanI];
6783 // End of span. (But not end of line--that was checked for above.)
6784 if (startIndex == span.side(forward, dir)) {
6785 span = order[spanI += forward ? 1 : -1];
6786 startIndex = span.side(!forward, dir);
6787 }
6788 let indexForward = forward == (span.dir == dir);
6789 let nextIndex = findClusterBreak(line.text, startIndex, indexForward);
6790 movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
6791 if (nextIndex > span.from && nextIndex < span.to)
6792 return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level);
6793 let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
6794 if (!nextSpan && span.level != dir)
6795 return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir);
6796 if (nextSpan && nextSpan.level < span.level)
6797 return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level);
6798 return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level);
6799 }
6800
6801 class DocView extends ContentView {
6802 get length() { return this.view.state.doc.length; }
6803 constructor(view) {
6804 super();
6805 this.view = view;
6806 this.decorations = [];
6807 this.dynamicDecorationMap = [];
6808 this.domChanged = null;
6809 this.hasComposition = null;
6810 this.markedForComposition = new Set;
6811 // Track a minimum width for the editor. When measuring sizes in
6812 // measureVisibleLineHeights, this is updated to point at the width
6813 // of a given element and its extent in the document. When a change
6814 // happens in that range, these are reset. That way, once we've seen
6815 // a line/element of a given length, we keep the editor wide enough
6816 // to fit at least that element, until it is changed, at which point
6817 // we forget it again.
6818 this.minWidth = 0;
6819 this.minWidthFrom = 0;
6820 this.minWidthTo = 0;
6821 // Track whether the DOM selection was set in a lossy way, so that
6822 // we don't mess it up when reading it back it
6823 this.impreciseAnchor = null;
6824 this.impreciseHead = null;
6825 this.forceSelection = false;
6826 // Used by the resize observer to ignore resizes that we caused
6827 // ourselves
6828 this.lastUpdate = Date.now();
6829 this.setDOM(view.contentDOM);
6830 this.children = [new LineView];
6831 this.children[0].setParent(this);
6832 this.updateDeco();
6833 this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);
6834 }
6835 // Update the document view to a given state.
6836 update(update) {
6837 var _a;
6838 let changedRanges = update.changedRanges;
6839 if (this.minWidth > 0 && changedRanges.length) {
6840 if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
6841 this.minWidth = this.minWidthFrom = this.minWidthTo = 0;
6842 }
6843 else {
6844 this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
6845 this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
6846 }
6847 }
6848 let readCompositionAt = -1;
6849 if (this.view.inputState.composing >= 0) {
6850 if ((_a = this.domChanged) === null || _a === void 0 ? void 0 : _a.newSel)
6851 readCompositionAt = this.domChanged.newSel.head;
6852 else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet)
6853 readCompositionAt = update.state.selection.main.head;
6854 }
6855 let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
6856 this.domChanged = null;
6857 if (this.hasComposition) {
6858 this.markedForComposition.clear();
6859 let { from, to } = this.hasComposition;
6860 changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1))
6861 .addToSet(changedRanges.slice());
6862 }
6863 this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null;
6864 // When the DOM nodes around the selection are moved to another
6865 // parent, Chrome sometimes reports a different selection through
6866 // getSelection than the one that it actually shows to the user.
6867 // This forces a selection update when lines are joined to work
6868 // around that. Issue #54
6869 if ((browser.ie || browser.chrome) && !composition && update &&
6870 update.state.doc.lines != update.startState.doc.lines)
6871 this.forceSelection = true;
6872 let prevDeco = this.decorations, deco = this.updateDeco();
6873 let decoDiff = findChangedDeco(prevDeco, deco, update.changes);
6874 changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
6875 if (!(this.flags & 7 /* ViewFlag.Dirty */) && changedRanges.length == 0) {
6876 return false;
6877 }
6878 else {
6879 this.updateInner(changedRanges, update.startState.doc.length, composition);
6880 if (update.transactions.length)
6881 this.lastUpdate = Date.now();
6882 return true;
6883 }
6884 }
6885 // Used by update and the constructor do perform the actual DOM
6886 // update
6887 updateInner(changes, oldLength, composition) {
6888 this.view.viewState.mustMeasureContent = true;
6889 this.updateChildren(changes, oldLength, composition);
6890 let { observer } = this.view;
6891 observer.ignore(() => {
6892 // Lock the height during redrawing, since Chrome sometimes
6893 // messes with the scroll position during DOM mutation (though
6894 // no relayout is triggered and I cannot imagine how it can
6895 // recompute the scroll position without a layout)
6896 this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
6897 this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
6898 // Chrome will sometimes, when DOM mutations occur directly
6899 // around the selection, get confused and report a different
6900 // selection from the one it displays (issue #218). This tries
6901 // to detect that situation.
6902 let track = browser.chrome || browser.ios ? { node: observer.selectionRange.focusNode, written: false } : undefined;
6903 this.sync(this.view, track);
6904 this.flags &= ~7 /* ViewFlag.Dirty */;
6905 if (track && (track.written || observer.selectionRange.focusNode != track.node))
6906 this.forceSelection = true;
6907 this.dom.style.height = "";
6908 });
6909 this.markedForComposition.forEach(cView => cView.flags &= ~8 /* ViewFlag.Composition */);
6910 let gaps = [];
6911 if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length)
6912 for (let child of this.children)
6913 if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget)
6914 gaps.push(child.dom);
6915 observer.updateGaps(gaps);
6916 }
6917 updateChildren(changes, oldLength, composition) {
6918 let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
6919 let cursor = this.childCursor(oldLength);
6920 for (let i = ranges.length - 1;; i--) {
6921 let next = i >= 0 ? ranges[i] : null;
6922 if (!next)
6923 break;
6924 let { fromA, toA, fromB, toB } = next, content, breakAtStart, openStart, openEnd;
6925 if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
6926 let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
6927 let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
6928 breakAtStart = before.breakAtStart;
6929 openStart = before.openStart;
6930 openEnd = after.openEnd;
6931 let compLine = this.compositionView(composition);
6932 if (after.breakAtStart) {
6933 compLine.breakAfter = 1;
6934 }
6935 else if (after.content.length &&
6936 compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
6937 compLine.breakAfter = after.content[0].breakAfter;
6938 after.content.shift();
6939 }
6940 if (before.content.length &&
6941 compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) {
6942 before.content.pop();
6943 }
6944 content = before.content.concat(compLine).concat(after.content);
6945 }
6946 else {
6947 ({ content, breakAtStart, openStart, openEnd } =
6948 ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
6949 }
6950 let { i: toI, off: toOff } = cursor.findPos(toA, 1);
6951 let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
6952 replaceRange(this, fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);
6953 }
6954 if (composition)
6955 this.fixCompositionDOM(composition);
6956 }
6957 compositionView(composition) {
6958 let cur = new TextView(composition.text.nodeValue);
6959 cur.flags |= 8 /* ViewFlag.Composition */;
6960 for (let { deco } of composition.marks)
6961 cur = new MarkView(deco, [cur], cur.length);
6962 let line = new LineView;
6963 line.append(cur, 0);
6964 return line;
6965 }
6966 fixCompositionDOM(composition) {
6967 let fix = (dom, cView) => {
6968 cView.flags |= 8 /* ViewFlag.Composition */ | (cView.children.some(c => c.flags & 7 /* ViewFlag.Dirty */) ? 1 /* ViewFlag.ChildDirty */ : 0);
6969 this.markedForComposition.add(cView);
6970 let prev = ContentView.get(dom);
6971 if (prev && prev != cView)
6972 prev.dom = null;
6973 cView.setDOM(dom);
6974 };
6975 let pos = this.childPos(composition.range.fromB, 1);
6976 let cView = this.children[pos.i];
6977 fix(composition.line, cView);
6978 for (let i = composition.marks.length - 1; i >= -1; i--) {
6979 pos = cView.childPos(pos.off, 1);
6980 cView = cView.children[pos.i];
6981 fix(i >= 0 ? composition.marks[i].node : composition.text, cView);
6982 }
6983 }
6984 // Sync the DOM selection to this.state.selection
6985 updateSelection(mustRead = false, fromPointer = false) {
6986 if (mustRead || !this.view.observer.selectionRange.focusNode)
6987 this.view.observer.readSelectionRange();
6988 let activeElt = this.view.root.activeElement, focused = activeElt == this.dom;
6989 let selectionNotFocus = !focused &&
6990 hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
6991 if (!(focused || fromPointer || selectionNotFocus))
6992 return;
6993 let force = this.forceSelection;
6994 this.forceSelection = false;
6995 let main = this.view.state.selection.main;
6996 let anchor = this.moveToLine(this.domAtPos(main.anchor));
6997 let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
6998 // Always reset on Firefox when next to an uneditable node to
6999 // avoid invisible cursor bugs (#111)
7000 if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
7001 let dummy = document.createTextNode("");
7002 this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
7003 anchor = head = new DOMPos(dummy, 0);
7004 force = true;
7005 }
7006 let domSel = this.view.observer.selectionRange;
7007 // If the selection is already here, or in an equivalent position, don't touch it
7008 if (force || !domSel.focusNode ||
7009 !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||
7010 !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {
7011 this.view.observer.ignore(() => {
7012 // Chrome Android will hide the virtual keyboard when tapping
7013 // inside an uneditable node, and not bring it back when we
7014 // move the cursor to its proper position. This tries to
7015 // restore the keyboard by cycling focus.
7016 if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) &&
7017 inUneditable(domSel.focusNode, this.dom)) {
7018 this.dom.blur();
7019 this.dom.focus({ preventScroll: true });
7020 }
7021 let rawSel = getSelection(this.view.root);
7022 if (!rawSel) ;
7023 else if (main.empty) {
7024 // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076
7025 if (browser.gecko) {
7026 let nextTo = nextToUneditable(anchor.node, anchor.offset);
7027 if (nextTo && nextTo != (1 /* NextTo.Before */ | 2 /* NextTo.After */)) {
7028 let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* NextTo.Before */ ? 1 : -1);
7029 if (text)
7030 anchor = new DOMPos(text.node, text.offset);
7031 }
7032 }
7033 rawSel.collapse(anchor.node, anchor.offset);
7034 if (main.bidiLevel != null && rawSel.caretBidiLevel !== undefined)
7035 rawSel.caretBidiLevel = main.bidiLevel;
7036 }
7037 else if (rawSel.extend) {
7038 // Selection.extend can be used to create an 'inverted' selection
7039 // (one where the focus is before the anchor), but not all
7040 // browsers support it yet.
7041 rawSel.collapse(anchor.node, anchor.offset);
7042 // Safari will ignore the call above when the editor is
7043 // hidden, and then raise an error on the call to extend
7044 // (#940).
7045 try {
7046 rawSel.extend(head.node, head.offset);
7047 }
7048 catch (_) { }
7049 }
7050 else {
7051 // Primitive (IE) way
7052 let range = document.createRange();
7053 if (main.anchor > main.head)
7054 [anchor, head] = [head, anchor];
7055 range.setEnd(head.node, head.offset);
7056 range.setStart(anchor.node, anchor.offset);
7057 rawSel.removeAllRanges();
7058 rawSel.addRange(range);
7059 }
7060 if (selectionNotFocus && this.view.root.activeElement == this.dom) {
7061 this.dom.blur();
7062 if (activeElt)
7063 activeElt.focus();
7064 }
7065 });
7066 this.view.observer.setSelectionRange(anchor, head);
7067 }
7068 this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
7069 this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
7070 }
7071 enforceCursorAssoc() {
7072 if (this.hasComposition)
7073 return;
7074 let { view } = this, cursor = view.state.selection.main;
7075 let sel = getSelection(view.root);
7076 let { anchorNode, anchorOffset } = view.observer.selectionRange;
7077 if (!sel || !cursor.empty || !cursor.assoc || !sel.modify)
7078 return;
7079 let line = LineView.find(this, cursor.head);
7080 if (!line)
7081 return;
7082 let lineStart = line.posAtStart;
7083 if (cursor.head == lineStart || cursor.head == lineStart + line.length)
7084 return;
7085 let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
7086 if (!before || !after || before.bottom > after.top)
7087 return;
7088 let dom = this.domAtPos(cursor.head + cursor.assoc);
7089 sel.collapse(dom.node, dom.offset);
7090 sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
7091 // This can go wrong in corner cases like single-character lines,
7092 // so check and reset if necessary.
7093 view.observer.readSelectionRange();
7094 let newRange = view.observer.selectionRange;
7095 if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from)
7096 sel.collapse(anchorNode, anchorOffset);
7097 }
7098 // If a position is in/near a block widget, move it to a nearby text
7099 // line, since we don't want the cursor inside a block widget.
7100 moveToLine(pos) {
7101 // Block widgets will return positions before/after them, which
7102 // are thus directly in the document DOM element.
7103 let dom = this.dom, newPos;
7104 if (pos.node != dom)
7105 return pos;
7106 for (let i = pos.offset; !newPos && i < dom.childNodes.length; i++) {
7107 let view = ContentView.get(dom.childNodes[i]);
7108 if (view instanceof LineView)
7109 newPos = view.domAtPos(0);
7110 }
7111 for (let i = pos.offset - 1; !newPos && i >= 0; i--) {
7112 let view = ContentView.get(dom.childNodes[i]);
7113 if (view instanceof LineView)
7114 newPos = view.domAtPos(view.length);
7115 }
7116 return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;
7117 }
7118 nearest(dom) {
7119 for (let cur = dom; cur;) {
7120 let domView = ContentView.get(cur);
7121 if (domView && domView.rootView == this)
7122 return domView;
7123 cur = cur.parentNode;
7124 }
7125 return null;
7126 }
7127 posFromDOM(node, offset) {
7128 let view = this.nearest(node);
7129 if (!view)
7130 throw new RangeError("Trying to find position for a DOM position outside of the document");
7131 return view.localPosFromDOM(node, offset) + view.posAtStart;
7132 }
7133 domAtPos(pos) {
7134 let { i, off } = this.childCursor().findPos(pos, -1);
7135 for (; i < this.children.length - 1;) {
7136 let child = this.children[i];
7137 if (off < child.length || child instanceof LineView)
7138 break;
7139 i++;
7140 off = 0;
7141 }
7142 return this.children[i].domAtPos(off);
7143 }
7144 coordsAt(pos, side) {
7145 let best = null, bestPos = 0;
7146 for (let off = this.length, i = this.children.length - 1; i >= 0; i--) {
7147 let child = this.children[i], end = off - child.breakAfter, start = end - child.length;
7148 if (end < pos)
7149 break;
7150 if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) &&
7151 (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
7152 best = child;
7153 bestPos = start;
7154 }
7155 off = start;
7156 }
7157 return best ? best.coordsAt(pos - bestPos, side) : null;
7158 }
7159 coordsForChar(pos) {
7160 let { i, off } = this.childPos(pos, 1), child = this.children[i];
7161 if (!(child instanceof LineView))
7162 return null;
7163 while (child.children.length) {
7164 let { i, off: childOff } = child.childPos(off, 1);
7165 for (;; i++) {
7166 if (i == child.children.length)
7167 return null;
7168 if ((child = child.children[i]).length)
7169 break;
7170 }
7171 off = childOff;
7172 }
7173 if (!(child instanceof TextView))
7174 return null;
7175 let end = findClusterBreak(child.text, off);
7176 if (end == off)
7177 return null;
7178 let rects = textRange(child.dom, off, end).getClientRects();
7179 for (let i = 0; i < rects.length; i++) {
7180 let rect = rects[i];
7181 if (i == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right)
7182 return rect;
7183 }
7184 return null;
7185 }
7186 measureVisibleLineHeights(viewport) {
7187 let result = [], { from, to } = viewport;
7188 let contentWidth = this.view.contentDOM.clientWidth;
7189 let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
7190 let widest = -1, ltr = this.view.textDirection == exports.Direction.LTR;
7191 for (let pos = 0, i = 0; i < this.children.length; i++) {
7192 let child = this.children[i], end = pos + child.length;
7193 if (end > to)
7194 break;
7195 if (pos >= from) {
7196 let childRect = child.dom.getBoundingClientRect();
7197 result.push(childRect.height);
7198 if (isWider) {
7199 let last = child.dom.lastChild;
7200 let rects = last ? clientRectsFor(last) : [];
7201 if (rects.length) {
7202 let rect = rects[rects.length - 1];
7203 let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
7204 if (width > widest) {
7205 widest = width;
7206 this.minWidth = contentWidth;
7207 this.minWidthFrom = pos;
7208 this.minWidthTo = end;
7209 }
7210 }
7211 }
7212 }
7213 pos = end + child.breakAfter;
7214 }
7215 return result;
7216 }
7217 textDirectionAt(pos) {
7218 let { i } = this.childPos(pos, 1);
7219 return getComputedStyle(this.children[i].dom).direction == "rtl" ? exports.Direction.RTL : exports.Direction.LTR;
7220 }
7221 measureTextSize() {
7222 for (let child of this.children) {
7223 if (child instanceof LineView) {
7224 let measure = child.measureTextSize();
7225 if (measure)
7226 return measure;
7227 }
7228 }
7229 // If no workable line exists, force a layout of a measurable element
7230 let dummy = document.createElement("div"), lineHeight, charWidth, textHeight;
7231 dummy.className = "cm-line";
7232 dummy.style.width = "99999px";
7233 dummy.style.position = "absolute";
7234 dummy.textContent = "abc def ghi jkl mno pqr stu";
7235 this.view.observer.ignore(() => {
7236 this.dom.appendChild(dummy);
7237 let rect = clientRectsFor(dummy.firstChild)[0];
7238 lineHeight = dummy.getBoundingClientRect().height;
7239 charWidth = rect ? rect.width / 27 : 7;
7240 textHeight = rect ? rect.height : lineHeight;
7241 dummy.remove();
7242 });
7243 return { lineHeight, charWidth, textHeight };
7244 }
7245 childCursor(pos = this.length) {
7246 // Move back to start of last element when possible, so that
7247 // `ChildCursor.findPos` doesn't have to deal with the edge case
7248 // of being after the last element.
7249 let i = this.children.length;
7250 if (i)
7251 pos -= this.children[--i].length;
7252 return new ChildCursor(this.children, pos, i);
7253 }
7254 computeBlockGapDeco() {
7255 let deco = [], vs = this.view.viewState;
7256 for (let pos = 0, i = 0;; i++) {
7257 let next = i == vs.viewports.length ? null : vs.viewports[i];
7258 let end = next ? next.from - 1 : this.length;
7259 if (end > pos) {
7260 let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
7261 deco.push(Decoration.replace({
7262 widget: new BlockGapWidget(height),
7263 block: true,
7264 inclusive: true,
7265 isBlockGap: true,
7266 }).range(pos, end));
7267 }
7268 if (!next)
7269 break;
7270 pos = next.to + 1;
7271 }
7272 return Decoration.set(deco);
7273 }
7274 updateDeco() {
7275 let allDeco = this.view.state.facet(decorations).map((d, i) => {
7276 let dynamic = this.dynamicDecorationMap[i] = typeof d == "function";
7277 return dynamic ? d(this.view) : d;
7278 });
7279 for (let i = allDeco.length; i < allDeco.length + 3; i++)
7280 this.dynamicDecorationMap[i] = false;
7281 return this.decorations = [
7282 ...allDeco,
7283 this.computeBlockGapDeco(),
7284 this.view.viewState.lineGapDeco
7285 ];
7286 }
7287 scrollIntoView(target) {
7288 if (target.isSnapshot) {
7289 let ref = this.view.viewState.lineBlockAt(target.range.head);
7290 this.view.scrollDOM.scrollTop = ref.top - target.yMargin;
7291 this.view.scrollDOM.scrollLeft = target.xMargin;
7292 return;
7293 }
7294 let { range } = target;
7295 let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1), other;
7296 if (!rect)
7297 return;
7298 if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)))
7299 rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top),
7300 right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) };
7301 let margins = getScrollMargins(this.view);
7302 let targetRect = {
7303 left: rect.left - margins.left, top: rect.top - margins.top,
7304 right: rect.right + margins.right, bottom: rect.bottom + margins.bottom
7305 };
7306 let { offsetWidth, offsetHeight } = this.view.scrollDOM;
7307 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 == exports.Direction.LTR);
7308 }
7309 }
7310 function betweenUneditable(pos) {
7311 return pos.node.nodeType == 1 && pos.node.firstChild &&
7312 (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") &&
7313 (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
7314 }
7315 class BlockGapWidget extends WidgetType {
7316 constructor(height) {
7317 super();
7318 this.height = height;
7319 }
7320 toDOM() {
7321 let elt = document.createElement("div");
7322 this.updateDOM(elt);
7323 return elt;
7324 }
7325 eq(other) { return other.height == this.height; }
7326 updateDOM(elt) {
7327 elt.style.height = this.height + "px";
7328 return true;
7329 }
7330 get estimatedHeight() { return this.height; }
7331 }
7332 function findCompositionNode(view, headPos) {
7333 let sel = view.observer.selectionRange;
7334 let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);
7335 if (!textNode)
7336 return null;
7337 let from = headPos - textNode.offset;
7338 return { from, to: from + textNode.node.nodeValue.length, node: textNode.node };
7339 }
7340 function findCompositionRange(view, changes, headPos) {
7341 let found = findCompositionNode(view, headPos);
7342 if (!found)
7343 return null;
7344 let { node: textNode, from, to } = found, text = textNode.nodeValue;
7345 // Don't try to preserve multi-line compositions
7346 if (/[\n\r]/.test(text))
7347 return null;
7348 if (view.state.doc.sliceString(found.from, found.to) != text)
7349 return null;
7350 let inv = changes.invertedDesc;
7351 let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
7352 let marks = [];
7353 for (let parent = textNode.parentNode;; parent = parent.parentNode) {
7354 let parentView = ContentView.get(parent);
7355 if (parentView instanceof MarkView)
7356 marks.push({ node: parent, deco: parentView.mark });
7357 else if (parentView instanceof LineView || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM)
7358 return { range, text: textNode, marks, line: parent };
7359 else if (parent != view.contentDOM)
7360 marks.push({ node: parent, deco: new MarkDecoration({
7361 inclusive: true,
7362 attributes: getAttrs(parent),
7363 tagName: parent.tagName.toLowerCase()
7364 }) });
7365 else
7366 return null;
7367 }
7368 }
7369 function nearbyTextNode(startNode, startOffset, side) {
7370 if (side <= 0)
7371 for (let node = startNode, offset = startOffset;;) {
7372 if (node.nodeType == 3)
7373 return { node: node, offset: offset };
7374 if (node.nodeType == 1 && offset > 0) {
7375 node = node.childNodes[offset - 1];
7376 offset = maxOffset(node);
7377 }
7378 else {
7379 break;
7380 }
7381 }
7382 if (side >= 0)
7383 for (let node = startNode, offset = startOffset;;) {
7384 if (node.nodeType == 3)
7385 return { node: node, offset: offset };
7386 if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {
7387 node = node.childNodes[offset];
7388 offset = 0;
7389 }
7390 else {
7391 break;
7392 }
7393 }
7394 return null;
7395 }
7396 function nextToUneditable(node, offset) {
7397 if (node.nodeType != 1)
7398 return 0;
7399 return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* NextTo.Before */ : 0) |
7400 (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* NextTo.After */ : 0);
7401 }
7402 let DecorationComparator$1 = class DecorationComparator {
7403 constructor() {
7404 this.changes = [];
7405 }
7406 compareRange(from, to) { addRange(from, to, this.changes); }
7407 comparePoint(from, to) { addRange(from, to, this.changes); }
7408 };
7409 function findChangedDeco(a, b, diff) {
7410 let comp = new DecorationComparator$1;
7411 RangeSet.compare(a, b, diff, comp);
7412 return comp.changes;
7413 }
7414 function inUneditable(node, inside) {
7415 for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode) {
7416 if (cur.nodeType == 1 && cur.contentEditable == 'false') {
7417 return true;
7418 }
7419 }
7420 return false;
7421 }
7422 function touchesComposition(changes, composition) {
7423 let touched = false;
7424 if (composition)
7425 changes.iterChangedRanges((from, to) => {
7426 if (from < composition.to && to > composition.from)
7427 touched = true;
7428 });
7429 return touched;
7430 }
7431
7432 function groupAt(state, pos, bias = 1) {
7433 let categorize = state.charCategorizer(pos);
7434 let line = state.doc.lineAt(pos), linePos = pos - line.from;
7435 if (line.length == 0)
7436 return EditorSelection.cursor(pos);
7437 if (linePos == 0)
7438 bias = 1;
7439 else if (linePos == line.length)
7440 bias = -1;
7441 let from = linePos, to = linePos;
7442 if (bias < 0)
7443 from = findClusterBreak(line.text, linePos, false);
7444 else
7445 to = findClusterBreak(line.text, linePos);
7446 let cat = categorize(line.text.slice(from, to));
7447 while (from > 0) {
7448 let prev = findClusterBreak(line.text, from, false);
7449 if (categorize(line.text.slice(prev, from)) != cat)
7450 break;
7451 from = prev;
7452 }
7453 while (to < line.length) {
7454 let next = findClusterBreak(line.text, to);
7455 if (categorize(line.text.slice(to, next)) != cat)
7456 break;
7457 to = next;
7458 }
7459 return EditorSelection.range(from + line.from, to + line.from);
7460 }
7461 // Search the DOM for the {node, offset} position closest to the given
7462 // coordinates. Very inefficient and crude, but can usually be avoided
7463 // by calling caret(Position|Range)FromPoint instead.
7464 function getdx(x, rect) {
7465 return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
7466 }
7467 function getdy(y, rect) {
7468 return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
7469 }
7470 function yOverlap(a, b) {
7471 return a.top < b.bottom - 1 && a.bottom > b.top + 1;
7472 }
7473 function upTop(rect, top) {
7474 return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
7475 }
7476 function upBot(rect, bottom) {
7477 return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;
7478 }
7479 function domPosAtCoords(parent, x, y) {
7480 let closest, closestRect, closestX, closestY, closestOverlap = false;
7481 let above, below, aboveRect, belowRect;
7482 for (let child = parent.firstChild; child; child = child.nextSibling) {
7483 let rects = clientRectsFor(child);
7484 for (let i = 0; i < rects.length; i++) {
7485 let rect = rects[i];
7486 if (closestRect && yOverlap(closestRect, rect))
7487 rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
7488 let dx = getdx(x, rect), dy = getdy(y, rect);
7489 if (dx == 0 && dy == 0)
7490 return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);
7491 if (!closest || closestY > dy || closestY == dy && closestX > dx) {
7492 closest = child;
7493 closestRect = rect;
7494 closestX = dx;
7495 closestY = dy;
7496 let side = dy ? (y < rect.top ? -1 : 1) : dx ? (x < rect.left ? -1 : 1) : 0;
7497 closestOverlap = !side || (side > 0 ? i < rects.length - 1 : i > 0);
7498 }
7499 if (dx == 0) {
7500 if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
7501 above = child;
7502 aboveRect = rect;
7503 }
7504 else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
7505 below = child;
7506 belowRect = rect;
7507 }
7508 }
7509 else if (aboveRect && yOverlap(aboveRect, rect)) {
7510 aboveRect = upBot(aboveRect, rect.bottom);
7511 }
7512 else if (belowRect && yOverlap(belowRect, rect)) {
7513 belowRect = upTop(belowRect, rect.top);
7514 }
7515 }
7516 }
7517 if (aboveRect && aboveRect.bottom >= y) {
7518 closest = above;
7519 closestRect = aboveRect;
7520 }
7521 else if (belowRect && belowRect.top <= y) {
7522 closest = below;
7523 closestRect = belowRect;
7524 }
7525 if (!closest)
7526 return { node: parent, offset: 0 };
7527 let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
7528 if (closest.nodeType == 3)
7529 return domPosInText(closest, clipX, y);
7530 if (closestOverlap && closest.contentEditable != "false")
7531 return domPosAtCoords(closest, clipX, y);
7532 let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +
7533 (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
7534 return { node: parent, offset };
7535 }
7536 function domPosInText(node, x, y) {
7537 let len = node.nodeValue.length;
7538 let closestOffset = -1, closestDY = 1e9, generalSide = 0;
7539 for (let i = 0; i < len; i++) {
7540 let rects = textRange(node, i, i + 1).getClientRects();
7541 for (let j = 0; j < rects.length; j++) {
7542 let rect = rects[j];
7543 if (rect.top == rect.bottom)
7544 continue;
7545 if (!generalSide)
7546 generalSide = x - rect.left;
7547 let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
7548 if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {
7549 let right = x >= (rect.left + rect.right) / 2, after = right;
7550 if (browser.chrome || browser.gecko) {
7551 // Check for RTL on browsers that support getting client
7552 // rects for empty ranges.
7553 let rectBefore = textRange(node, i).getBoundingClientRect();
7554 if (rectBefore.left == rect.right)
7555 after = !right;
7556 }
7557 if (dy <= 0)
7558 return { node, offset: i + (after ? 1 : 0) };
7559 closestOffset = i + (after ? 1 : 0);
7560 closestDY = dy;
7561 }
7562 }
7563 }
7564 return { node, offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0 };
7565 }
7566 function posAtCoords(view, coords, precise, bias = -1) {
7567 var _a, _b;
7568 let content = view.contentDOM.getBoundingClientRect(), docTop = content.top + view.viewState.paddingTop;
7569 let block, { docHeight } = view.viewState;
7570 let { x, y } = coords, yOffset = y - docTop;
7571 if (yOffset < 0)
7572 return 0;
7573 if (yOffset > docHeight)
7574 return view.state.doc.length;
7575 // Scan for a text block near the queried y position
7576 for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {
7577 block = view.elementAtHeight(yOffset);
7578 if (block.type == exports.BlockType.Text)
7579 break;
7580 for (;;) {
7581 // Move the y position out of this block
7582 yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
7583 if (yOffset >= 0 && yOffset <= docHeight)
7584 break;
7585 // If the document consists entirely of replaced widgets, we
7586 // won't find a text block, so return 0
7587 if (bounced)
7588 return precise ? null : 0;
7589 bounced = true;
7590 bias = -bias;
7591 }
7592 }
7593 y = docTop + yOffset;
7594 let lineStart = block.from;
7595 // If this is outside of the rendered viewport, we can't determine a position
7596 if (lineStart < view.viewport.from)
7597 return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7598 if (lineStart > view.viewport.to)
7599 return view.viewport.to == view.state.doc.length ? view.state.doc.length :
7600 precise ? null : posAtCoordsImprecise(view, content, block, x, y);
7601 // Prefer ShadowRootOrDocument.elementFromPoint if present, fall back to document if not
7602 let doc = view.dom.ownerDocument;
7603 let root = view.root.elementFromPoint ? view.root : doc;
7604 let element = root.elementFromPoint(x, y);
7605 if (element && !view.contentDOM.contains(element))
7606 element = null;
7607 // If the element is unexpected, clip x at the sides of the content area and try again
7608 if (!element) {
7609 x = Math.max(content.left + 1, Math.min(content.right - 1, x));
7610 element = root.elementFromPoint(x, y);
7611 if (element && !view.contentDOM.contains(element))
7612 element = null;
7613 }
7614 // There's visible editor content under the point, so we can try
7615 // using caret(Position|Range)FromPoint as a shortcut
7616 let node, offset = -1;
7617 if (element && ((_a = view.docView.nearest(element)) === null || _a === void 0 ? void 0 : _a.isEditable) != false) {
7618 if (doc.caretPositionFromPoint) {
7619 let pos = doc.caretPositionFromPoint(x, y);
7620 if (pos)
7621 ({ offsetNode: node, offset } = pos);
7622 }
7623 else if (doc.caretRangeFromPoint) {
7624 let range = doc.caretRangeFromPoint(x, y);
7625 if (range) {
7626 ({ startContainer: node, startOffset: offset } = range);
7627 if (!view.contentDOM.contains(node) ||
7628 browser.safari && isSuspiciousSafariCaretResult(node, offset, x) ||
7629 browser.chrome && isSuspiciousChromeCaretResult(node, offset, x))
7630 node = undefined;
7631 }
7632 }
7633 }
7634 // No luck, do our own (potentially expensive) search
7635 if (!node || !view.docView.dom.contains(node)) {
7636 let line = LineView.find(view.docView, lineStart);
7637 if (!line)
7638 return yOffset > block.top + block.height / 2 ? block.to : block.from;
7639 ({ node, offset } = domPosAtCoords(line.dom, x, y));
7640 }
7641 let nearest = view.docView.nearest(node);
7642 if (!nearest)
7643 return null;
7644 if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
7645 let rect = nearest.dom.getBoundingClientRect();
7646 return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2
7647 ? nearest.posAtStart : nearest.posAtEnd;
7648 }
7649 else {
7650 return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
7651 }
7652 }
7653 function posAtCoordsImprecise(view, contentRect, block, x, y) {
7654 let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
7655 if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
7656 let textHeight = view.viewState.heightOracle.textHeight;
7657 let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * 0.5) / textHeight);
7658 into += line * view.viewState.heightOracle.lineLength;
7659 }
7660 let content = view.state.sliceDoc(block.from, block.to);
7661 return block.from + findColumn(content, into, view.state.tabSize);
7662 }
7663 // In case of a high line height, Safari's caretRangeFromPoint treats
7664 // the space between lines as belonging to the last character of the
7665 // line before. This is used to detect such a result so that it can be
7666 // ignored (issue #401).
7667 function isSuspiciousSafariCaretResult(node, offset, x) {
7668 let len;
7669 if (node.nodeType != 3 || offset != (len = node.nodeValue.length))
7670 return false;
7671 for (let next = node.nextSibling; next; next = next.nextSibling)
7672 if (next.nodeType != 1 || next.nodeName != "BR")
7673 return false;
7674 return textRange(node, len - 1, len).getBoundingClientRect().left > x;
7675 }
7676 // Chrome will move positions between lines to the start of the next line
7677 function isSuspiciousChromeCaretResult(node, offset, x) {
7678 if (offset != 0)
7679 return false;
7680 for (let cur = node;;) {
7681 let parent = cur.parentNode;
7682 if (!parent || parent.nodeType != 1 || parent.firstChild != cur)
7683 return false;
7684 if (parent.classList.contains("cm-line"))
7685 break;
7686 cur = parent;
7687 }
7688 let rect = node.nodeType == 1 ? node.getBoundingClientRect()
7689 : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect();
7690 return x - rect.left > 5;
7691 }
7692 function blockAt(view, pos) {
7693 let line = view.lineBlockAt(pos);
7694 if (Array.isArray(line.type))
7695 for (let l of line.type) {
7696 if (l.to > pos || l.to == pos && (l.to == line.to || l.type == exports.BlockType.Text))
7697 return l;
7698 }
7699 return line;
7700 }
7701 function moveToLineBoundary(view, start, forward, includeWrap) {
7702 let line = blockAt(view, start.head);
7703 let coords = !includeWrap || line.type != exports.BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null
7704 : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
7705 if (coords) {
7706 let editorRect = view.dom.getBoundingClientRect();
7707 let direction = view.textDirectionAt(line.from);
7708 let pos = view.posAtCoords({ x: forward == (direction == exports.Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
7709 y: (coords.top + coords.bottom) / 2 });
7710 if (pos != null)
7711 return EditorSelection.cursor(pos, forward ? -1 : 1);
7712 }
7713 return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
7714 }
7715 function moveByChar(view, start, forward, by) {
7716 let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
7717 let direction = view.textDirectionAt(line.from);
7718 for (let cur = start, check = null;;) {
7719 let next = moveVisually(line, spans, direction, cur, forward), char = movedOver;
7720 if (!next) {
7721 if (line.number == (forward ? view.state.doc.lines : 1))
7722 return cur;
7723 char = "\n";
7724 line = view.state.doc.line(line.number + (forward ? 1 : -1));
7725 spans = view.bidiSpans(line);
7726 next = EditorSelection.cursor(forward ? line.from : line.to);
7727 }
7728 if (!check) {
7729 if (!by)
7730 return next;
7731 check = by(char);
7732 }
7733 else if (!check(char)) {
7734 return cur;
7735 }
7736 cur = next;
7737 }
7738 }
7739 function byGroup(view, pos, start) {
7740 let categorize = view.state.charCategorizer(pos);
7741 let cat = categorize(start);
7742 return (next) => {
7743 let nextCat = categorize(next);
7744 if (cat == exports.CharCategory.Space)
7745 cat = nextCat;
7746 return cat == nextCat;
7747 };
7748 }
7749 function moveVertically(view, start, forward, distance) {
7750 let startPos = start.head, dir = forward ? 1 : -1;
7751 if (startPos == (forward ? view.state.doc.length : 0))
7752 return EditorSelection.cursor(startPos, start.assoc);
7753 let goal = start.goalColumn, startY;
7754 let rect = view.contentDOM.getBoundingClientRect();
7755 let startCoords = view.coordsAtPos(startPos, start.assoc || -1), docTop = view.documentTop;
7756 if (startCoords) {
7757 if (goal == null)
7758 goal = startCoords.left - rect.left;
7759 startY = dir < 0 ? startCoords.top : startCoords.bottom;
7760 }
7761 else {
7762 let line = view.viewState.lineBlockAt(startPos);
7763 if (goal == null)
7764 goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
7765 startY = (dir < 0 ? line.top : line.bottom) + docTop;
7766 }
7767 let resolvedGoal = rect.left + goal;
7768 let dist = distance !== null && distance !== void 0 ? distance : (view.viewState.heightOracle.textHeight >> 1);
7769 for (let extra = 0;; extra += 10) {
7770 let curY = startY + (dist + extra) * dir;
7771 let pos = posAtCoords(view, { x: resolvedGoal, y: curY }, false, dir);
7772 if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
7773 let charRect = view.docView.coordsForChar(pos);
7774 let assoc = !charRect || curY < charRect.top ? -1 : 1;
7775 return EditorSelection.cursor(pos, assoc, undefined, goal);
7776 }
7777 }
7778 }
7779 function skipAtomicRanges(atoms, pos, bias) {
7780 for (;;) {
7781 let moved = 0;
7782 for (let set of atoms) {
7783 set.between(pos - 1, pos + 1, (from, to, value) => {
7784 if (pos > from && pos < to) {
7785 let side = moved || bias || (pos - from < to - pos ? -1 : 1);
7786 pos = side < 0 ? from : to;
7787 moved = side;
7788 }
7789 });
7790 }
7791 if (!moved)
7792 return pos;
7793 }
7794 }
7795 function skipAtoms(view, oldPos, pos) {
7796 let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
7797 return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
7798 }
7799
7800 // This will also be where dragging info and such goes
7801 class InputState {
7802 setSelectionOrigin(origin) {
7803 this.lastSelectionOrigin = origin;
7804 this.lastSelectionTime = Date.now();
7805 }
7806 constructor(view) {
7807 this.view = view;
7808 this.lastKeyCode = 0;
7809 this.lastKeyTime = 0;
7810 this.lastTouchTime = 0;
7811 this.lastFocusTime = 0;
7812 this.lastScrollTop = 0;
7813 this.lastScrollLeft = 0;
7814 // On iOS, some keys need to have their default behavior happen
7815 // (after which we retroactively handle them and reset the DOM) to
7816 // avoid messing up the virtual keyboard state.
7817 this.pendingIOSKey = undefined;
7818 this.lastSelectionOrigin = null;
7819 this.lastSelectionTime = 0;
7820 this.lastEscPress = 0;
7821 this.lastContextMenu = 0;
7822 this.scrollHandlers = [];
7823 this.handlers = Object.create(null);
7824 // -1 means not in a composition. Otherwise, this counts the number
7825 // of changes made during the composition. The count is used to
7826 // avoid treating the start state of the composition, before any
7827 // changes have been made, as part of the composition.
7828 this.composing = -1;
7829 // Tracks whether the next change should be marked as starting the
7830 // composition (null means no composition, true means next is the
7831 // first, false means first has already been marked for this
7832 // composition)
7833 this.compositionFirstChange = null;
7834 // End time of the previous composition
7835 this.compositionEndedAt = 0;
7836 // Used in a kludge to detect when an Enter keypress should be
7837 // considered part of the composition on Safari, which fires events
7838 // in the wrong order
7839 this.compositionPendingKey = false;
7840 // Used to categorize changes as part of a composition, even when
7841 // the mutation events fire shortly after the compositionend event
7842 this.compositionPendingChange = false;
7843 this.mouseSelection = null;
7844 // When a drag from the editor is active, this points at the range
7845 // being dragged.
7846 this.draggedContent = null;
7847 this.handleEvent = this.handleEvent.bind(this);
7848 this.notifiedFocused = view.hasFocus;
7849 // On Safari adding an input event handler somehow prevents an
7850 // issue where the composition vanishes when you press enter.
7851 if (browser.safari)
7852 view.contentDOM.addEventListener("input", () => null);
7853 if (browser.gecko)
7854 firefoxCopyCutHack(view.contentDOM.ownerDocument);
7855 }
7856 handleEvent(event) {
7857 if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event))
7858 return;
7859 if (event.type == "keydown" && this.keydown(event))
7860 return;
7861 this.runHandlers(event.type, event);
7862 }
7863 runHandlers(type, event) {
7864 let handlers = this.handlers[type];
7865 if (handlers) {
7866 for (let observer of handlers.observers)
7867 observer(this.view, event);
7868 for (let handler of handlers.handlers) {
7869 if (event.defaultPrevented)
7870 break;
7871 if (handler(this.view, event)) {
7872 event.preventDefault();
7873 break;
7874 }
7875 }
7876 }
7877 }
7878 ensureHandlers(plugins) {
7879 let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM;
7880 for (let type in handlers)
7881 if (type != "scroll") {
7882 let passive = !handlers[type].handlers.length;
7883 let exists = prev[type];
7884 if (exists && passive != !exists.handlers.length) {
7885 dom.removeEventListener(type, this.handleEvent);
7886 exists = null;
7887 }
7888 if (!exists)
7889 dom.addEventListener(type, this.handleEvent, { passive });
7890 }
7891 for (let type in prev)
7892 if (type != "scroll" && !handlers[type])
7893 dom.removeEventListener(type, this.handleEvent);
7894 this.handlers = handlers;
7895 }
7896 keydown(event) {
7897 // Must always run, even if a custom handler handled the event
7898 this.lastKeyCode = event.keyCode;
7899 this.lastKeyTime = Date.now();
7900 if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000)
7901 return true;
7902 if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0)
7903 this.view.inputState.lastEscPress = 0;
7904 // Chrome for Android usually doesn't fire proper key events, but
7905 // occasionally does, usually surrounded by a bunch of complicated
7906 // composition changes. When an enter or backspace key event is
7907 // seen, hold off on handling DOM events for a bit, and then
7908 // dispatch it.
7909 if (browser.android && browser.chrome && !event.synthetic &&
7910 (event.keyCode == 13 || event.keyCode == 8)) {
7911 this.view.observer.delayAndroidKey(event.key, event.keyCode);
7912 return true;
7913 }
7914 // Preventing the default behavior of Enter on iOS makes the
7915 // virtual keyboard get stuck in the wrong (lowercase)
7916 // state. So we let it go through, and then, in
7917 // applyDOMChange, notify key handlers of it and reset to
7918 // the state they produce.
7919 let pending;
7920 if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey &&
7921 ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||
7922 EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
7923 this.pendingIOSKey = pending || event;
7924 setTimeout(() => this.flushIOSKey(), 250);
7925 return true;
7926 }
7927 if (event.keyCode != 229)
7928 this.view.observer.forceFlush();
7929 return false;
7930 }
7931 flushIOSKey() {
7932 let key = this.pendingIOSKey;
7933 if (!key)
7934 return false;
7935 this.pendingIOSKey = undefined;
7936 return dispatchKey(this.view.contentDOM, key.key, key.keyCode);
7937 }
7938 ignoreDuringComposition(event) {
7939 if (!/^key/.test(event.type))
7940 return false;
7941 if (this.composing > 0)
7942 return true;
7943 // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
7944 // On some input method editors (IMEs), the Enter key is used to
7945 // confirm character selection. On Safari, when Enter is pressed,
7946 // compositionend and keydown events are sometimes emitted in the
7947 // wrong order. The key event should still be ignored, even when
7948 // it happens after the compositionend event.
7949 if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
7950 this.compositionPendingKey = false;
7951 return true;
7952 }
7953 return false;
7954 }
7955 startMouseSelection(mouseSelection) {
7956 if (this.mouseSelection)
7957 this.mouseSelection.destroy();
7958 this.mouseSelection = mouseSelection;
7959 }
7960 update(update) {
7961 if (this.mouseSelection)
7962 this.mouseSelection.update(update);
7963 if (this.draggedContent && update.docChanged)
7964 this.draggedContent = this.draggedContent.map(update.changes);
7965 if (update.transactions.length)
7966 this.lastKeyCode = this.lastSelectionTime = 0;
7967 }
7968 destroy() {
7969 if (this.mouseSelection)
7970 this.mouseSelection.destroy();
7971 }
7972 }
7973 function bindHandler(plugin, handler) {
7974 return (view, event) => {
7975 try {
7976 return handler.call(plugin, event, view);
7977 }
7978 catch (e) {
7979 logException(view.state, e);
7980 }
7981 };
7982 }
7983 function computeHandlers(plugins) {
7984 let result = Object.create(null);
7985 function record(type) {
7986 return result[type] || (result[type] = { observers: [], handlers: [] });
7987 }
7988 for (let plugin of plugins) {
7989 let spec = plugin.spec;
7990 if (spec && spec.domEventHandlers)
7991 for (let type in spec.domEventHandlers) {
7992 let f = spec.domEventHandlers[type];
7993 if (f)
7994 record(type).handlers.push(bindHandler(plugin.value, f));
7995 }
7996 if (spec && spec.domEventObservers)
7997 for (let type in spec.domEventObservers) {
7998 let f = spec.domEventObservers[type];
7999 if (f)
8000 record(type).observers.push(bindHandler(plugin.value, f));
8001 }
8002 }
8003 for (let type in handlers)
8004 record(type).handlers.push(handlers[type]);
8005 for (let type in observers)
8006 record(type).observers.push(observers[type]);
8007 return result;
8008 }
8009 const PendingKeys = [
8010 { key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" },
8011 { key: "Enter", keyCode: 13, inputType: "insertParagraph" },
8012 { key: "Enter", keyCode: 13, inputType: "insertLineBreak" },
8013 { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }
8014 ];
8015 const EmacsyPendingKeys = "dthko";
8016 // Key codes for modifier keys
8017 const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
8018 const dragScrollMargin = 6;
8019 function dragScrollSpeed(dist) {
8020 return Math.max(0, dist) * 0.7 + 8;
8021 }
8022 function dist(a, b) {
8023 return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
8024 }
8025 class MouseSelection {
8026 constructor(view, startEvent, style, mustSelect) {
8027 this.view = view;
8028 this.startEvent = startEvent;
8029 this.style = style;
8030 this.mustSelect = mustSelect;
8031 this.scrollSpeed = { x: 0, y: 0 };
8032 this.scrolling = -1;
8033 this.lastEvent = startEvent;
8034 this.scrollParent = scrollableParent(view.contentDOM);
8035 this.atoms = view.state.facet(atomicRanges).map(f => f(view));
8036 let doc = view.contentDOM.ownerDocument;
8037 doc.addEventListener("mousemove", this.move = this.move.bind(this));
8038 doc.addEventListener("mouseup", this.up = this.up.bind(this));
8039 this.extend = startEvent.shiftKey;
8040 this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
8041 this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
8042 }
8043 start(event) {
8044 // When clicking outside of the selection, immediately apply the
8045 // effect of starting the selection
8046 if (this.dragging === false)
8047 this.select(event);
8048 }
8049 move(event) {
8050 var _a;
8051 if (event.buttons == 0)
8052 return this.destroy();
8053 if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10)
8054 return;
8055 this.select(this.lastEvent = event);
8056 let sx = 0, sy = 0;
8057 let rect = ((_a = this.scrollParent) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect())
8058 || { left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight };
8059 let margins = getScrollMargins(this.view);
8060 if (event.clientX - margins.left <= rect.left + dragScrollMargin)
8061 sx = -dragScrollSpeed(rect.left - event.clientX);
8062 else if (event.clientX + margins.right >= rect.right - dragScrollMargin)
8063 sx = dragScrollSpeed(event.clientX - rect.right);
8064 if (event.clientY - margins.top <= rect.top + dragScrollMargin)
8065 sy = -dragScrollSpeed(rect.top - event.clientY);
8066 else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)
8067 sy = dragScrollSpeed(event.clientY - rect.bottom);
8068 this.setScrollSpeed(sx, sy);
8069 }
8070 up(event) {
8071 if (this.dragging == null)
8072 this.select(this.lastEvent);
8073 if (!this.dragging)
8074 event.preventDefault();
8075 this.destroy();
8076 }
8077 destroy() {
8078 this.setScrollSpeed(0, 0);
8079 let doc = this.view.contentDOM.ownerDocument;
8080 doc.removeEventListener("mousemove", this.move);
8081 doc.removeEventListener("mouseup", this.up);
8082 this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
8083 }
8084 setScrollSpeed(sx, sy) {
8085 this.scrollSpeed = { x: sx, y: sy };
8086 if (sx || sy) {
8087 if (this.scrolling < 0)
8088 this.scrolling = setInterval(() => this.scroll(), 50);
8089 }
8090 else if (this.scrolling > -1) {
8091 clearInterval(this.scrolling);
8092 this.scrolling = -1;
8093 }
8094 }
8095 scroll() {
8096 if (this.scrollParent) {
8097 this.scrollParent.scrollLeft += this.scrollSpeed.x;
8098 this.scrollParent.scrollTop += this.scrollSpeed.y;
8099 }
8100 else {
8101 this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);
8102 }
8103 if (this.dragging === false)
8104 this.select(this.lastEvent);
8105 }
8106 skipAtoms(sel) {
8107 let ranges = null;
8108 for (let i = 0; i < sel.ranges.length; i++) {
8109 let range = sel.ranges[i], updated = null;
8110 if (range.empty) {
8111 let pos = skipAtomicRanges(this.atoms, range.from, 0);
8112 if (pos != range.from)
8113 updated = EditorSelection.cursor(pos, -1);
8114 }
8115 else {
8116 let from = skipAtomicRanges(this.atoms, range.from, -1);
8117 let to = skipAtomicRanges(this.atoms, range.to, 1);
8118 if (from != range.from || to != range.to)
8119 updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
8120 }
8121 if (updated) {
8122 if (!ranges)
8123 ranges = sel.ranges.slice();
8124 ranges[i] = updated;
8125 }
8126 }
8127 return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
8128 }
8129 select(event) {
8130 let { view } = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
8131 if (this.mustSelect || !selection.eq(view.state.selection) ||
8132 selection.main.assoc != view.state.selection.main.assoc && this.dragging === false)
8133 this.view.dispatch({
8134 selection,
8135 userEvent: "select.pointer"
8136 });
8137 this.mustSelect = false;
8138 }
8139 update(update) {
8140 if (this.style.update(update))
8141 setTimeout(() => this.select(this.lastEvent), 20);
8142 }
8143 }
8144 function addsSelectionRange(view, event) {
8145 let facet = view.state.facet(clickAddsSelectionRange);
8146 return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
8147 }
8148 function dragMovesSelection(view, event) {
8149 let facet = view.state.facet(dragMovesSelection$1);
8150 return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
8151 }
8152 function isInPrimarySelection(view, event) {
8153 let { main } = view.state.selection;
8154 if (main.empty)
8155 return false;
8156 // On boundary clicks, check whether the coordinates are inside the
8157 // selection's client rectangles
8158 let sel = getSelection(view.root);
8159 if (!sel || sel.rangeCount == 0)
8160 return true;
8161 let rects = sel.getRangeAt(0).getClientRects();
8162 for (let i = 0; i < rects.length; i++) {
8163 let rect = rects[i];
8164 if (rect.left <= event.clientX && rect.right >= event.clientX &&
8165 rect.top <= event.clientY && rect.bottom >= event.clientY)
8166 return true;
8167 }
8168 return false;
8169 }
8170 function eventBelongsToEditor(view, event) {
8171 if (!event.bubbles)
8172 return true;
8173 if (event.defaultPrevented)
8174 return false;
8175 for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)
8176 if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))
8177 return false;
8178 return true;
8179 }
8180 const handlers = /*@__PURE__*/Object.create(null);
8181 const observers = /*@__PURE__*/Object.create(null);
8182 // This is very crude, but unfortunately both these browsers _pretend_
8183 // that they have a clipboard API—all the objects and methods are
8184 // there, they just don't work, and they are hard to test.
8185 const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
8186 (browser.ios && browser.webkit_version < 604);
8187 function capturePaste(view) {
8188 let parent = view.dom.parentNode;
8189 if (!parent)
8190 return;
8191 let target = parent.appendChild(document.createElement("textarea"));
8192 target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8193 target.focus();
8194 setTimeout(() => {
8195 view.focus();
8196 target.remove();
8197 doPaste(view, target.value);
8198 }, 50);
8199 }
8200 function doPaste(view, input) {
8201 let { state } = view, changes, i = 1, text = state.toText(input);
8202 let byLine = text.lines == state.selection.ranges.length;
8203 let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();
8204 if (linewise) {
8205 let lastLine = -1;
8206 changes = state.changeByRange(range => {
8207 let line = state.doc.lineAt(range.from);
8208 if (line.from == lastLine)
8209 return { range };
8210 lastLine = line.from;
8211 let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak);
8212 return { changes: { from: line.from, insert },
8213 range: EditorSelection.cursor(range.from + insert.length) };
8214 });
8215 }
8216 else if (byLine) {
8217 changes = state.changeByRange(range => {
8218 let line = text.line(i++);
8219 return { changes: { from: range.from, to: range.to, insert: line.text },
8220 range: EditorSelection.cursor(range.from + line.length) };
8221 });
8222 }
8223 else {
8224 changes = state.replaceSelection(text);
8225 }
8226 view.dispatch(changes, {
8227 userEvent: "input.paste",
8228 scrollIntoView: true
8229 });
8230 }
8231 observers.scroll = view => {
8232 view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
8233 view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
8234 };
8235 handlers.keydown = (view, event) => {
8236 view.inputState.setSelectionOrigin("select");
8237 if (event.keyCode == 27)
8238 view.inputState.lastEscPress = Date.now();
8239 return false;
8240 };
8241 observers.touchstart = (view, e) => {
8242 view.inputState.lastTouchTime = Date.now();
8243 view.inputState.setSelectionOrigin("select.pointer");
8244 };
8245 observers.touchmove = view => {
8246 view.inputState.setSelectionOrigin("select.pointer");
8247 };
8248 handlers.mousedown = (view, event) => {
8249 view.observer.flush();
8250 if (view.inputState.lastTouchTime > Date.now() - 2000)
8251 return false; // Ignore touch interaction
8252 let style = null;
8253 for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
8254 style = makeStyle(view, event);
8255 if (style)
8256 break;
8257 }
8258 if (!style && event.button == 0)
8259 style = basicMouseSelection(view, event);
8260 if (style) {
8261 let mustFocus = !view.hasFocus;
8262 view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
8263 if (mustFocus)
8264 view.observer.ignore(() => focusPreventScroll(view.contentDOM));
8265 let mouseSel = view.inputState.mouseSelection;
8266 if (mouseSel) {
8267 mouseSel.start(event);
8268 return mouseSel.dragging === false;
8269 }
8270 }
8271 return false;
8272 };
8273 function rangeForClick(view, pos, bias, type) {
8274 if (type == 1) { // Single click
8275 return EditorSelection.cursor(pos, bias);
8276 }
8277 else if (type == 2) { // Double click
8278 return groupAt(view.state, pos, bias);
8279 }
8280 else { // Triple click
8281 let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
8282 let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to;
8283 if (to < view.state.doc.length && to == line.to)
8284 to++;
8285 return EditorSelection.range(from, to);
8286 }
8287 }
8288 let insideY = (y, rect) => y >= rect.top && y <= rect.bottom;
8289 let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;
8290 // Try to determine, for the given coordinates, associated with the
8291 // given position, whether they are related to the element before or
8292 // the element after the position.
8293 function findPositionSide(view, pos, x, y) {
8294 let line = LineView.find(view.docView, pos);
8295 if (!line)
8296 return 1;
8297 let off = pos - line.posAtStart;
8298 // Line boundaries point into the line
8299 if (off == 0)
8300 return 1;
8301 if (off == line.length)
8302 return -1;
8303 // Positions on top of an element point at that element
8304 let before = line.coordsAt(off, -1);
8305 if (before && inside(x, y, before))
8306 return -1;
8307 let after = line.coordsAt(off, 1);
8308 if (after && inside(x, y, after))
8309 return 1;
8310 // This is probably a line wrap point. Pick before if the point is
8311 // beside it.
8312 return before && insideY(y, before) ? -1 : 1;
8313 }
8314 function queryPos(view, event) {
8315 let pos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
8316 return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };
8317 }
8318 const BadMouseDetail = browser.ie && browser.ie_version <= 11;
8319 let lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
8320 function getClickType(event) {
8321 if (!BadMouseDetail)
8322 return event.detail;
8323 let last = lastMouseDown, lastTime = lastMouseDownTime;
8324 lastMouseDown = event;
8325 lastMouseDownTime = Date.now();
8326 return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
8327 Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;
8328 }
8329 function basicMouseSelection(view, event) {
8330 let start = queryPos(view, event), type = getClickType(event);
8331 let startSel = view.state.selection;
8332 return {
8333 update(update) {
8334 if (update.docChanged) {
8335 start.pos = update.changes.mapPos(start.pos);
8336 startSel = startSel.map(update.changes);
8337 }
8338 },
8339 get(event, extend, multiple) {
8340 let cur = queryPos(view, event), removed;
8341 let range = rangeForClick(view, cur.pos, cur.bias, type);
8342 if (start.pos != cur.pos && !extend) {
8343 let startRange = rangeForClick(view, start.pos, start.bias, type);
8344 let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
8345 range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
8346 }
8347 if (extend)
8348 return startSel.replaceRange(startSel.main.extend(range.from, range.to));
8349 else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))
8350 return removed;
8351 else if (multiple)
8352 return startSel.addRange(range);
8353 else
8354 return EditorSelection.create([range]);
8355 }
8356 };
8357 }
8358 function removeRangeAround(sel, pos) {
8359 for (let i = 0; i < sel.ranges.length; i++) {
8360 let { from, to } = sel.ranges[i];
8361 if (from <= pos && to >= pos)
8362 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));
8363 }
8364 return null;
8365 }
8366 handlers.dragstart = (view, event) => {
8367 let { selection: { main: range } } = view.state;
8368 if (event.target.draggable) {
8369 let cView = view.docView.nearest(event.target);
8370 if (cView && cView.isWidget) {
8371 let from = cView.posAtStart, to = from + cView.length;
8372 if (from >= range.to || to <= range.from)
8373 range = EditorSelection.range(from, to);
8374 }
8375 }
8376 let { inputState } = view;
8377 if (inputState.mouseSelection)
8378 inputState.mouseSelection.dragging = true;
8379 inputState.draggedContent = range;
8380 if (event.dataTransfer) {
8381 event.dataTransfer.setData("Text", view.state.sliceDoc(range.from, range.to));
8382 event.dataTransfer.effectAllowed = "copyMove";
8383 }
8384 return false;
8385 };
8386 handlers.dragend = view => {
8387 view.inputState.draggedContent = null;
8388 return false;
8389 };
8390 function dropText(view, event, text, direct) {
8391 if (!text)
8392 return;
8393 let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
8394 let { draggedContent } = view.inputState;
8395 let del = direct && draggedContent && dragMovesSelection(view, event)
8396 ? { from: draggedContent.from, to: draggedContent.to } : null;
8397 let ins = { from: dropPos, insert: text };
8398 let changes = view.state.changes(del ? [del, ins] : ins);
8399 view.focus();
8400 view.dispatch({
8401 changes,
8402 selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
8403 userEvent: del ? "move.drop" : "input.drop"
8404 });
8405 view.inputState.draggedContent = null;
8406 }
8407 handlers.drop = (view, event) => {
8408 if (!event.dataTransfer)
8409 return false;
8410 if (view.state.readOnly)
8411 return true;
8412 let files = event.dataTransfer.files;
8413 if (files && files.length) { // For a file drop, read the file's text.
8414 let text = Array(files.length), read = 0;
8415 let finishFile = () => {
8416 if (++read == files.length)
8417 dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
8418 };
8419 for (let i = 0; i < files.length; i++) {
8420 let reader = new FileReader;
8421 reader.onerror = finishFile;
8422 reader.onload = () => {
8423 if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result))
8424 text[i] = reader.result;
8425 finishFile();
8426 };
8427 reader.readAsText(files[i]);
8428 }
8429 return true;
8430 }
8431 else {
8432 let text = event.dataTransfer.getData("Text");
8433 if (text) {
8434 dropText(view, event, text, true);
8435 return true;
8436 }
8437 }
8438 return false;
8439 };
8440 handlers.paste = (view, event) => {
8441 if (view.state.readOnly)
8442 return true;
8443 view.observer.flush();
8444 let data = brokenClipboardAPI ? null : event.clipboardData;
8445 if (data) {
8446 doPaste(view, data.getData("text/plain") || data.getData("text/uri-text"));
8447 return true;
8448 }
8449 else {
8450 capturePaste(view);
8451 return false;
8452 }
8453 };
8454 function captureCopy(view, text) {
8455 // The extra wrapper is somehow necessary on IE/Edge to prevent the
8456 // content from being mangled when it is put onto the clipboard
8457 let parent = view.dom.parentNode;
8458 if (!parent)
8459 return;
8460 let target = parent.appendChild(document.createElement("textarea"));
8461 target.style.cssText = "position: fixed; left: -10000px; top: 10px";
8462 target.value = text;
8463 target.focus();
8464 target.selectionEnd = text.length;
8465 target.selectionStart = 0;
8466 setTimeout(() => {
8467 target.remove();
8468 view.focus();
8469 }, 50);
8470 }
8471 function copiedRange(state) {
8472 let content = [], ranges = [], linewise = false;
8473 for (let range of state.selection.ranges)
8474 if (!range.empty) {
8475 content.push(state.sliceDoc(range.from, range.to));
8476 ranges.push(range);
8477 }
8478 if (!content.length) {
8479 // Nothing selected, do a line-wise copy
8480 let upto = -1;
8481 for (let { from } of state.selection.ranges) {
8482 let line = state.doc.lineAt(from);
8483 if (line.number > upto) {
8484 content.push(line.text);
8485 ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
8486 }
8487 upto = line.number;
8488 }
8489 linewise = true;
8490 }
8491 return { text: content.join(state.lineBreak), ranges, linewise };
8492 }
8493 let lastLinewiseCopy = null;
8494 handlers.copy = handlers.cut = (view, event) => {
8495 let { text, ranges, linewise } = copiedRange(view.state);
8496 if (!text && !linewise)
8497 return false;
8498 lastLinewiseCopy = linewise ? text : null;
8499 if (event.type == "cut" && !view.state.readOnly)
8500 view.dispatch({
8501 changes: ranges,
8502 scrollIntoView: true,
8503 userEvent: "delete.cut"
8504 });
8505 let data = brokenClipboardAPI ? null : event.clipboardData;
8506 if (data) {
8507 data.clearData();
8508 data.setData("text/plain", text);
8509 return true;
8510 }
8511 else {
8512 captureCopy(view, text);
8513 return false;
8514 }
8515 };
8516 const isFocusChange = /*@__PURE__*/Annotation.define();
8517 function focusChangeTransaction(state, focus) {
8518 let effects = [];
8519 for (let getEffect of state.facet(focusChangeEffect)) {
8520 let effect = getEffect(state, focus);
8521 if (effect)
8522 effects.push(effect);
8523 }
8524 return effects ? state.update({ effects, annotations: isFocusChange.of(true) }) : null;
8525 }
8526 function updateForFocusChange(view) {
8527 setTimeout(() => {
8528 let focus = view.hasFocus;
8529 if (focus != view.inputState.notifiedFocused) {
8530 let tr = focusChangeTransaction(view.state, focus);
8531 if (tr)
8532 view.dispatch(tr);
8533 else
8534 view.update([]);
8535 }
8536 }, 10);
8537 }
8538 observers.focus = view => {
8539 view.inputState.lastFocusTime = Date.now();
8540 // When focusing reset the scroll position, move it back to where it was
8541 if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
8542 view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
8543 view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
8544 }
8545 updateForFocusChange(view);
8546 };
8547 observers.blur = view => {
8548 view.observer.clearSelectionRange();
8549 updateForFocusChange(view);
8550 };
8551 observers.compositionstart = observers.compositionupdate = view => {
8552 if (view.inputState.compositionFirstChange == null)
8553 view.inputState.compositionFirstChange = true;
8554 if (view.inputState.composing < 0) {
8555 // FIXME possibly set a timeout to clear it again on Android
8556 view.inputState.composing = 0;
8557 }
8558 };
8559 observers.compositionend = view => {
8560 view.inputState.composing = -1;
8561 view.inputState.compositionEndedAt = Date.now();
8562 view.inputState.compositionPendingKey = true;
8563 view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
8564 view.inputState.compositionFirstChange = null;
8565 if (browser.chrome && browser.android) {
8566 // Delay flushing for a bit on Android because it'll often fire a
8567 // bunch of contradictory changes in a row at end of compositon
8568 view.observer.flushSoon();
8569 }
8570 else if (view.inputState.compositionPendingChange) {
8571 // If we found pending records, schedule a flush.
8572 Promise.resolve().then(() => view.observer.flush());
8573 }
8574 else {
8575 // Otherwise, make sure that, if no changes come in soon, the
8576 // composition view is cleared.
8577 setTimeout(() => {
8578 if (view.inputState.composing < 0 && view.docView.hasComposition)
8579 view.update([]);
8580 }, 50);
8581 }
8582 };
8583 observers.contextmenu = view => {
8584 view.inputState.lastContextMenu = Date.now();
8585 };
8586 handlers.beforeinput = (view, event) => {
8587 var _a;
8588 // Because Chrome Android doesn't fire useful key events, use
8589 // beforeinput to detect backspace (and possibly enter and delete,
8590 // but those usually don't even seem to fire beforeinput events at
8591 // the moment) and fake a key event for it.
8592 //
8593 // (preventDefault on beforeinput, though supported in the spec,
8594 // seems to do nothing at all on Chrome).
8595 let pending;
8596 if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
8597 view.observer.delayAndroidKey(pending.key, pending.keyCode);
8598 if (pending.key == "Backspace" || pending.key == "Delete") {
8599 let startViewHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0;
8600 setTimeout(() => {
8601 var _a;
8602 // Backspacing near uneditable nodes on Chrome Android sometimes
8603 // closes the virtual keyboard. This tries to crudely detect
8604 // that and refocus to get it back.
8605 if ((((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0) > startViewHeight + 10 && view.hasFocus) {
8606 view.contentDOM.blur();
8607 view.focus();
8608 }
8609 }, 100);
8610 }
8611 }
8612 return false;
8613 };
8614 const appliedFirefoxHack = /*@__PURE__*/new Set;
8615 // In Firefox, when cut/copy handlers are added to the document, that
8616 // somehow avoids a bug where those events aren't fired when the
8617 // selection is empty. See https://github.com/codemirror/dev/issues/1082
8618 // and https://bugzilla.mozilla.org/show_bug.cgi?id=995961
8619 function firefoxCopyCutHack(doc) {
8620 if (!appliedFirefoxHack.has(doc)) {
8621 appliedFirefoxHack.add(doc);
8622 doc.addEventListener("copy", () => { });
8623 doc.addEventListener("cut", () => { });
8624 }
8625 }
8626
8627 const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
8628 class HeightOracle {
8629 constructor(lineWrapping) {
8630 this.lineWrapping = lineWrapping;
8631 this.doc = Text.empty;
8632 this.heightSamples = {};
8633 this.lineHeight = 14; // The height of an entire line (line-height)
8634 this.charWidth = 7;
8635 this.textHeight = 14; // The height of the actual font (font-size)
8636 this.lineLength = 30;
8637 // Used to track, during updateHeight, if any actual heights changed
8638 this.heightChanged = false;
8639 }
8640 heightForGap(from, to) {
8641 let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
8642 if (this.lineWrapping)
8643 lines += Math.max(0, Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength));
8644 return this.lineHeight * lines;
8645 }
8646 heightForLine(length) {
8647 if (!this.lineWrapping)
8648 return this.lineHeight;
8649 let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
8650 return lines * this.lineHeight;
8651 }
8652 setDoc(doc) { this.doc = doc; return this; }
8653 mustRefreshForWrapping(whiteSpace) {
8654 return (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping;
8655 }
8656 mustRefreshForHeights(lineHeights) {
8657 let newHeight = false;
8658 for (let i = 0; i < lineHeights.length; i++) {
8659 let h = lineHeights[i];
8660 if (h < 0) {
8661 i++;
8662 }
8663 else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels
8664 newHeight = true;
8665 this.heightSamples[Math.floor(h * 10)] = true;
8666 }
8667 }
8668 return newHeight;
8669 }
8670 refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
8671 let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
8672 let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
8673 this.lineWrapping = lineWrapping;
8674 this.lineHeight = lineHeight;
8675 this.charWidth = charWidth;
8676 this.textHeight = textHeight;
8677 this.lineLength = lineLength;
8678 if (changed) {
8679 this.heightSamples = {};
8680 for (let i = 0; i < knownHeights.length; i++) {
8681 let h = knownHeights[i];
8682 if (h < 0)
8683 i++;
8684 else
8685 this.heightSamples[Math.floor(h * 10)] = true;
8686 }
8687 }
8688 return changed;
8689 }
8690 }
8691 // This object is used by `updateHeight` to make DOM measurements
8692 // arrive at the right nides. The `heights` array is a sequence of
8693 // block heights, starting from position `from`.
8694 class MeasuredHeights {
8695 constructor(from, heights) {
8696 this.from = from;
8697 this.heights = heights;
8698 this.index = 0;
8699 }
8700 get more() { return this.index < this.heights.length; }
8701 }
8702 /**
8703 Record used to represent information about a block-level element
8704 in the editor view.
8705 */
8706 class BlockInfo {
8707 /**
8708 @internal
8709 */
8710 constructor(
8711 /**
8712 The start of the element in the document.
8713 */
8714 from,
8715 /**
8716 The length of the element.
8717 */
8718 length,
8719 /**
8720 The top position of the element (relative to the top of the
8721 document).
8722 */
8723 top,
8724 /**
8725 Its height.
8726 */
8727 height,
8728 /**
8729 @internal Weird packed field that holds an array of children
8730 for composite blocks, a decoration for block widgets, and a
8731 number indicating the amount of widget-create line breaks for
8732 text blocks.
8733 */
8734 _content) {
8735 this.from = from;
8736 this.length = length;
8737 this.top = top;
8738 this.height = height;
8739 this._content = _content;
8740 }
8741 /**
8742 The type of element this is. When querying lines, this may be
8743 an array of all the blocks that make up the line.
8744 */
8745 get type() {
8746 return typeof this._content == "number" ? exports.BlockType.Text :
8747 Array.isArray(this._content) ? this._content : this._content.type;
8748 }
8749 /**
8750 The end of the element as a document position.
8751 */
8752 get to() { return this.from + this.length; }
8753 /**
8754 The bottom position of the element.
8755 */
8756 get bottom() { return this.top + this.height; }
8757 /**
8758 If this is a widget block, this will return the widget
8759 associated with it.
8760 */
8761 get widget() {
8762 return this._content instanceof PointDecoration ? this._content.widget : null;
8763 }
8764 /**
8765 If this is a textblock, this holds the number of line breaks
8766 that appear in widgets inside the block.
8767 */
8768 get widgetLineBreaks() {
8769 return typeof this._content == "number" ? this._content : 0;
8770 }
8771 /**
8772 @internal
8773 */
8774 join(other) {
8775 let content = (Array.isArray(this._content) ? this._content : [this])
8776 .concat(Array.isArray(other._content) ? other._content : [other]);
8777 return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content);
8778 }
8779 }
8780 var QueryType$1 = /*@__PURE__*/(function (QueryType) {
8781 QueryType[QueryType["ByPos"] = 0] = "ByPos";
8782 QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
8783 QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
8784 return QueryType})(QueryType$1 || (QueryType$1 = {}));
8785 const Epsilon = 1e-3;
8786 class HeightMap {
8787 constructor(length, // The number of characters covered
8788 height, // Height of this part of the document
8789 flags = 2 /* Flag.Outdated */) {
8790 this.length = length;
8791 this.height = height;
8792 this.flags = flags;
8793 }
8794 get outdated() { return (this.flags & 2 /* Flag.Outdated */) > 0; }
8795 set outdated(value) { this.flags = (value ? 2 /* Flag.Outdated */ : 0) | (this.flags & ~2 /* Flag.Outdated */); }
8796 setHeight(oracle, height) {
8797 if (this.height != height) {
8798 if (Math.abs(this.height - height) > Epsilon)
8799 oracle.heightChanged = true;
8800 this.height = height;
8801 }
8802 }
8803 // Base case is to replace a leaf node, which simply builds a tree
8804 // from the new nodes and returns that (HeightMapBranch and
8805 // HeightMapGap override this to actually use from/to)
8806 replace(_from, _to, nodes) {
8807 return HeightMap.of(nodes);
8808 }
8809 // Again, these are base cases, and are overridden for branch and gap nodes.
8810 decomposeLeft(_to, result) { result.push(this); }
8811 decomposeRight(_from, result) { result.push(this); }
8812 applyChanges(decorations, oldDoc, oracle, changes) {
8813 let me = this, doc = oracle.doc;
8814 for (let i = changes.length - 1; i >= 0; i--) {
8815 let { fromA, toA, fromB, toB } = changes[i];
8816 let start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
8817 let end = start.to >= toA ? start : me.lineAt(toA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
8818 toB += end.to - toA;
8819 toA = end.to;
8820 while (i > 0 && start.from <= changes[i - 1].toA) {
8821 fromA = changes[i - 1].fromA;
8822 fromB = changes[i - 1].fromB;
8823 i--;
8824 if (fromA < start.from)
8825 start = me.lineAt(fromA, QueryType$1.ByPosNoHeight, oracle, 0, 0);
8826 }
8827 fromB += start.from - fromA;
8828 fromA = start.from;
8829 let nodes = NodeBuilder.build(oracle.setDoc(doc), decorations, fromB, toB);
8830 me = me.replace(fromA, toA, nodes);
8831 }
8832 return me.updateHeight(oracle, 0);
8833 }
8834 static empty() { return new HeightMapText(0, 0); }
8835 // nodes uses null values to indicate the position of line breaks.
8836 // There are never line breaks at the start or end of the array, or
8837 // two line breaks next to each other, and the array isn't allowed
8838 // to be empty (same restrictions as return value from the builder).
8839 static of(nodes) {
8840 if (nodes.length == 1)
8841 return nodes[0];
8842 let i = 0, j = nodes.length, before = 0, after = 0;
8843 for (;;) {
8844 if (i == j) {
8845 if (before > after * 2) {
8846 let split = nodes[i - 1];
8847 if (split.break)
8848 nodes.splice(--i, 1, split.left, null, split.right);
8849 else
8850 nodes.splice(--i, 1, split.left, split.right);
8851 j += 1 + split.break;
8852 before -= split.size;
8853 }
8854 else if (after > before * 2) {
8855 let split = nodes[j];
8856 if (split.break)
8857 nodes.splice(j, 1, split.left, null, split.right);
8858 else
8859 nodes.splice(j, 1, split.left, split.right);
8860 j += 2 + split.break;
8861 after -= split.size;
8862 }
8863 else {
8864 break;
8865 }
8866 }
8867 else if (before < after) {
8868 let next = nodes[i++];
8869 if (next)
8870 before += next.size;
8871 }
8872 else {
8873 let next = nodes[--j];
8874 if (next)
8875 after += next.size;
8876 }
8877 }
8878 let brk = 0;
8879 if (nodes[i - 1] == null) {
8880 brk = 1;
8881 i--;
8882 }
8883 else if (nodes[i] == null) {
8884 brk = 1;
8885 j++;
8886 }
8887 return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
8888 }
8889 }
8890 HeightMap.prototype.size = 1;
8891 class HeightMapBlock extends HeightMap {
8892 constructor(length, height, deco) {
8893 super(length, height);
8894 this.deco = deco;
8895 }
8896 blockAt(_height, _oracle, top, offset) {
8897 return new BlockInfo(offset, this.length, top, this.height, this.deco || 0);
8898 }
8899 lineAt(_value, _type, oracle, top, offset) {
8900 return this.blockAt(0, oracle, top, offset);
8901 }
8902 forEachLine(from, to, oracle, top, offset, f) {
8903 if (from <= offset + this.length && to >= offset)
8904 f(this.blockAt(0, oracle, top, offset));
8905 }
8906 updateHeight(oracle, offset = 0, _force = false, measured) {
8907 if (measured && measured.from <= offset && measured.more)
8908 this.setHeight(oracle, measured.heights[measured.index++]);
8909 this.outdated = false;
8910 return this;
8911 }
8912 toString() { return `block(${this.length})`; }
8913 }
8914 class HeightMapText extends HeightMapBlock {
8915 constructor(length, height) {
8916 super(length, height, null);
8917 this.collapsed = 0; // Amount of collapsed content in the line
8918 this.widgetHeight = 0; // Maximum inline widget height
8919 this.breaks = 0; // Number of widget-introduced line breaks on the line
8920 }
8921 blockAt(_height, _oracle, top, offset) {
8922 return new BlockInfo(offset, this.length, top, this.height, this.breaks);
8923 }
8924 replace(_from, _to, nodes) {
8925 let node = nodes[0];
8926 if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* Flag.SingleLine */)) &&
8927 Math.abs(this.length - node.length) < 10) {
8928 if (node instanceof HeightMapGap)
8929 node = new HeightMapText(node.length, this.height);
8930 else
8931 node.height = this.height;
8932 if (!this.outdated)
8933 node.outdated = false;
8934 return node;
8935 }
8936 else {
8937 return HeightMap.of(nodes);
8938 }
8939 }
8940 updateHeight(oracle, offset = 0, force = false, measured) {
8941 if (measured && measured.from <= offset && measured.more)
8942 this.setHeight(oracle, measured.heights[measured.index++]);
8943 else if (force || this.outdated)
8944 this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) +
8945 this.breaks * oracle.lineHeight);
8946 this.outdated = false;
8947 return this;
8948 }
8949 toString() {
8950 return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
8951 }
8952 }
8953 class HeightMapGap extends HeightMap {
8954 constructor(length) { super(length, 0); }
8955 heightMetrics(oracle, offset) {
8956 let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number;
8957 let lines = lastLine - firstLine + 1;
8958 let perLine, perChar = 0;
8959 if (oracle.lineWrapping) {
8960 let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
8961 perLine = totalPerLine / lines;
8962 if (this.length > lines + 1)
8963 perChar = (this.height - totalPerLine) / (this.length - lines - 1);
8964 }
8965 else {
8966 perLine = this.height / lines;
8967 }
8968 return { firstLine, lastLine, perLine, perChar };
8969 }
8970 blockAt(height, oracle, top, offset) {
8971 let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset);
8972 if (oracle.lineWrapping) {
8973 let guess = offset + Math.round(Math.max(0, Math.min(1, (height - top) / this.height)) * this.length);
8974 let line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar;
8975 let lineTop = Math.max(top, height - lineHeight / 2);
8976 return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
8977 }
8978 else {
8979 let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / perLine)));
8980 let { from, length } = oracle.doc.line(firstLine + line);
8981 return new BlockInfo(from, length, top + perLine * line, perLine, 0);
8982 }
8983 }
8984 lineAt(value, type, oracle, top, offset) {
8985 if (type == QueryType$1.ByHeight)
8986 return this.blockAt(value, oracle, top, offset);
8987 if (type == QueryType$1.ByPosNoHeight) {
8988 let { from, to } = oracle.doc.lineAt(value);
8989 return new BlockInfo(from, to - from, 0, 0, 0);
8990 }
8991 let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
8992 let line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar;
8993 let linesAbove = line.number - firstLine;
8994 let lineTop = top + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
8995 return new BlockInfo(line.from, line.length, Math.max(top, Math.min(lineTop, top + this.height - lineHeight)), lineHeight, 0);
8996 }
8997 forEachLine(from, to, oracle, top, offset, f) {
8998 from = Math.max(from, offset);
8999 to = Math.min(to, offset + this.length);
9000 let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset);
9001 for (let pos = from, lineTop = top; pos <= to;) {
9002 let line = oracle.doc.lineAt(pos);
9003 if (pos == from) {
9004 let linesAbove = line.number - firstLine;
9005 lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
9006 }
9007 let lineHeight = perLine + perChar * line.length;
9008 f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
9009 lineTop += lineHeight;
9010 pos = line.to + 1;
9011 }
9012 }
9013 replace(from, to, nodes) {
9014 let after = this.length - to;
9015 if (after > 0) {
9016 let last = nodes[nodes.length - 1];
9017 if (last instanceof HeightMapGap)
9018 nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
9019 else
9020 nodes.push(null, new HeightMapGap(after - 1));
9021 }
9022 if (from > 0) {
9023 let first = nodes[0];
9024 if (first instanceof HeightMapGap)
9025 nodes[0] = new HeightMapGap(from + first.length);
9026 else
9027 nodes.unshift(new HeightMapGap(from - 1), null);
9028 }
9029 return HeightMap.of(nodes);
9030 }
9031 decomposeLeft(to, result) {
9032 result.push(new HeightMapGap(to - 1), null);
9033 }
9034 decomposeRight(from, result) {
9035 result.push(null, new HeightMapGap(this.length - from - 1));
9036 }
9037 updateHeight(oracle, offset = 0, force = false, measured) {
9038 let end = offset + this.length;
9039 if (measured && measured.from <= offset + this.length && measured.more) {
9040 // Fill in part of this gap with measured lines. We know there
9041 // can't be widgets or collapsed ranges in those lines, because
9042 // they would already have been added to the heightmap (gaps
9043 // only contain plain text).
9044 let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1;
9045 if (measured.from > offset)
9046 nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
9047 while (pos <= end && measured.more) {
9048 let len = oracle.doc.lineAt(pos).length;
9049 if (nodes.length)
9050 nodes.push(null);
9051 let height = measured.heights[measured.index++];
9052 if (singleHeight == -1)
9053 singleHeight = height;
9054 else if (Math.abs(height - singleHeight) >= Epsilon)
9055 singleHeight = -2;
9056 let line = new HeightMapText(len, height);
9057 line.outdated = false;
9058 nodes.push(line);
9059 pos += len + 1;
9060 }
9061 if (pos <= end)
9062 nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
9063 let result = HeightMap.of(nodes);
9064 if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon ||
9065 Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon)
9066 oracle.heightChanged = true;
9067 return result;
9068 }
9069 else if (force || this.outdated) {
9070 this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
9071 this.outdated = false;
9072 }
9073 return this;
9074 }
9075 toString() { return `gap(${this.length})`; }
9076 }
9077 class HeightMapBranch extends HeightMap {
9078 constructor(left, brk, right) {
9079 super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Flag.Outdated */ : 0));
9080 this.left = left;
9081 this.right = right;
9082 this.size = left.size + right.size;
9083 }
9084 get break() { return this.flags & 1 /* Flag.Break */; }
9085 blockAt(height, oracle, top, offset) {
9086 let mid = top + this.left.height;
9087 return height < mid ? this.left.blockAt(height, oracle, top, offset)
9088 : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
9089 }
9090 lineAt(value, type, oracle, top, offset) {
9091 let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9092 let left = type == QueryType$1.ByHeight ? value < rightTop : value < rightOffset;
9093 let base = left ? this.left.lineAt(value, type, oracle, top, offset)
9094 : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
9095 if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))
9096 return base;
9097 let subQuery = type == QueryType$1.ByPosNoHeight ? QueryType$1.ByPosNoHeight : QueryType$1.ByPos;
9098 if (left)
9099 return base.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));
9100 else
9101 return this.left.lineAt(rightOffset, subQuery, oracle, top, offset).join(base);
9102 }
9103 forEachLine(from, to, oracle, top, offset, f) {
9104 let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
9105 if (this.break) {
9106 if (from < rightOffset)
9107 this.left.forEachLine(from, to, oracle, top, offset, f);
9108 if (to >= rightOffset)
9109 this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
9110 }
9111 else {
9112 let mid = this.lineAt(rightOffset, QueryType$1.ByPos, oracle, top, offset);
9113 if (from < mid.from)
9114 this.left.forEachLine(from, mid.from - 1, oracle, top, offset, f);
9115 if (mid.to >= from && mid.from <= to)
9116 f(mid);
9117 if (to > mid.to)
9118 this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
9119 }
9120 }
9121 replace(from, to, nodes) {
9122 let rightStart = this.left.length + this.break;
9123 if (to < rightStart)
9124 return this.balanced(this.left.replace(from, to, nodes), this.right);
9125 if (from > this.left.length)
9126 return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
9127 let result = [];
9128 if (from > 0)
9129 this.decomposeLeft(from, result);
9130 let left = result.length;
9131 for (let node of nodes)
9132 result.push(node);
9133 if (from > 0)
9134 mergeGaps(result, left - 1);
9135 if (to < this.length) {
9136 let right = result.length;
9137 this.decomposeRight(to, result);
9138 mergeGaps(result, right);
9139 }
9140 return HeightMap.of(result);
9141 }
9142 decomposeLeft(to, result) {
9143 let left = this.left.length;
9144 if (to <= left)
9145 return this.left.decomposeLeft(to, result);
9146 result.push(this.left);
9147 if (this.break) {
9148 left++;
9149 if (to >= left)
9150 result.push(null);
9151 }
9152 if (to > left)
9153 this.right.decomposeLeft(to - left, result);
9154 }
9155 decomposeRight(from, result) {
9156 let left = this.left.length, right = left + this.break;
9157 if (from >= right)
9158 return this.right.decomposeRight(from - right, result);
9159 if (from < left)
9160 this.left.decomposeRight(from, result);
9161 if (this.break && from < right)
9162 result.push(null);
9163 result.push(this.right);
9164 }
9165 balanced(left, right) {
9166 if (left.size > 2 * right.size || right.size > 2 * left.size)
9167 return HeightMap.of(this.break ? [left, null, right] : [left, right]);
9168 this.left = left;
9169 this.right = right;
9170 this.height = left.height + right.height;
9171 this.outdated = left.outdated || right.outdated;
9172 this.size = left.size + right.size;
9173 this.length = left.length + this.break + right.length;
9174 return this;
9175 }
9176 updateHeight(oracle, offset = 0, force = false, measured) {
9177 let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
9178 if (measured && measured.from <= offset + left.length && measured.more)
9179 rebalance = left = left.updateHeight(oracle, offset, force, measured);
9180 else
9181 left.updateHeight(oracle, offset, force);
9182 if (measured && measured.from <= rightStart + right.length && measured.more)
9183 rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
9184 else
9185 right.updateHeight(oracle, rightStart, force);
9186 if (rebalance)
9187 return this.balanced(left, right);
9188 this.height = this.left.height + this.right.height;
9189 this.outdated = false;
9190 return this;
9191 }
9192 toString() { return this.left + (this.break ? " " : "-") + this.right; }
9193 }
9194 function mergeGaps(nodes, around) {
9195 let before, after;
9196 if (nodes[around] == null &&
9197 (before = nodes[around - 1]) instanceof HeightMapGap &&
9198 (after = nodes[around + 1]) instanceof HeightMapGap)
9199 nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
9200 }
9201 const relevantWidgetHeight = 5;
9202 class NodeBuilder {
9203 constructor(pos, oracle) {
9204 this.pos = pos;
9205 this.oracle = oracle;
9206 this.nodes = [];
9207 this.lineStart = -1;
9208 this.lineEnd = -1;
9209 this.covering = null;
9210 this.writtenTo = pos;
9211 }
9212 get isCovered() {
9213 return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
9214 }
9215 span(_from, to) {
9216 if (this.lineStart > -1) {
9217 let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
9218 if (last instanceof HeightMapText)
9219 last.length += end - this.pos;
9220 else if (end > this.pos || !this.isCovered)
9221 this.nodes.push(new HeightMapText(end - this.pos, -1));
9222 this.writtenTo = end;
9223 if (to > end) {
9224 this.nodes.push(null);
9225 this.writtenTo++;
9226 this.lineStart = -1;
9227 }
9228 }
9229 this.pos = to;
9230 }
9231 point(from, to, deco) {
9232 if (from < to || deco.heightRelevant) {
9233 let height = deco.widget ? deco.widget.estimatedHeight : 0;
9234 let breaks = deco.widget ? deco.widget.lineBreaks : 0;
9235 if (height < 0)
9236 height = this.oracle.lineHeight;
9237 let len = to - from;
9238 if (deco.block) {
9239 this.addBlock(new HeightMapBlock(len, height, deco));
9240 }
9241 else if (len || breaks || height >= relevantWidgetHeight) {
9242 this.addLineDeco(height, breaks, len);
9243 }
9244 }
9245 else if (to > from) {
9246 this.span(from, to);
9247 }
9248 if (this.lineEnd > -1 && this.lineEnd < this.pos)
9249 this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
9250 }
9251 enterLine() {
9252 if (this.lineStart > -1)
9253 return;
9254 let { from, to } = this.oracle.doc.lineAt(this.pos);
9255 this.lineStart = from;
9256 this.lineEnd = to;
9257 if (this.writtenTo < from) {
9258 if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
9259 this.nodes.push(this.blankContent(this.writtenTo, from - 1));
9260 this.nodes.push(null);
9261 }
9262 if (this.pos > from)
9263 this.nodes.push(new HeightMapText(this.pos - from, -1));
9264 this.writtenTo = this.pos;
9265 }
9266 blankContent(from, to) {
9267 let gap = new HeightMapGap(to - from);
9268 if (this.oracle.doc.lineAt(from).to == to)
9269 gap.flags |= 4 /* Flag.SingleLine */;
9270 return gap;
9271 }
9272 ensureLine() {
9273 this.enterLine();
9274 let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
9275 if (last instanceof HeightMapText)
9276 return last;
9277 let line = new HeightMapText(0, -1);
9278 this.nodes.push(line);
9279 return line;
9280 }
9281 addBlock(block) {
9282 this.enterLine();
9283 let deco = block.deco;
9284 if (deco && deco.startSide > 0 && !this.isCovered)
9285 this.ensureLine();
9286 this.nodes.push(block);
9287 this.writtenTo = this.pos = this.pos + block.length;
9288 if (deco && deco.endSide > 0)
9289 this.covering = block;
9290 }
9291 addLineDeco(height, breaks, length) {
9292 let line = this.ensureLine();
9293 line.length += length;
9294 line.collapsed += length;
9295 line.widgetHeight = Math.max(line.widgetHeight, height);
9296 line.breaks += breaks;
9297 this.writtenTo = this.pos = this.pos + length;
9298 }
9299 finish(from) {
9300 let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
9301 if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
9302 this.nodes.push(new HeightMapText(0, -1));
9303 else if (this.writtenTo < this.pos || last == null)
9304 this.nodes.push(this.blankContent(this.writtenTo, this.pos));
9305 let pos = from;
9306 for (let node of this.nodes) {
9307 if (node instanceof HeightMapText)
9308 node.updateHeight(this.oracle, pos);
9309 pos += node ? node.length : 1;
9310 }
9311 return this.nodes;
9312 }
9313 // Always called with a region that on both sides either stretches
9314 // to a line break or the end of the document.
9315 // The returned array uses null to indicate line breaks, but never
9316 // starts or ends in a line break, or has multiple line breaks next
9317 // to each other.
9318 static build(oracle, decorations, from, to) {
9319 let builder = new NodeBuilder(from, oracle);
9320 RangeSet.spans(decorations, from, to, builder, 0);
9321 return builder.finish(from);
9322 }
9323 }
9324 function heightRelevantDecoChanges(a, b, diff) {
9325 let comp = new DecorationComparator;
9326 RangeSet.compare(a, b, diff, comp, 0);
9327 return comp.changes;
9328 }
9329 class DecorationComparator {
9330 constructor() {
9331 this.changes = [];
9332 }
9333 compareRange() { }
9334 comparePoint(from, to, a, b) {
9335 if (from < to || a && a.heightRelevant || b && b.heightRelevant)
9336 addRange(from, to, this.changes, 5);
9337 }
9338 }
9339
9340 function visiblePixelRange(dom, paddingTop) {
9341 let rect = dom.getBoundingClientRect();
9342 let doc = dom.ownerDocument, win = doc.defaultView || window;
9343 let left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right);
9344 let top = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom);
9345 for (let parent = dom.parentNode; parent && parent != doc.body;) {
9346 if (parent.nodeType == 1) {
9347 let elt = parent;
9348 let style = window.getComputedStyle(elt);
9349 if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) &&
9350 style.overflow != "visible") {
9351 let parentRect = elt.getBoundingClientRect();
9352 left = Math.max(left, parentRect.left);
9353 right = Math.min(right, parentRect.right);
9354 top = Math.max(top, parentRect.top);
9355 bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);
9356 }
9357 parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
9358 }
9359 else if (parent.nodeType == 11) { // Shadow root
9360 parent = parent.host;
9361 }
9362 else {
9363 break;
9364 }
9365 }
9366 return { left: left - rect.left, right: Math.max(left, right) - rect.left,
9367 top: top - (rect.top + paddingTop), bottom: Math.max(top, bottom) - (rect.top + paddingTop) };
9368 }
9369 function fullPixelRange(dom, paddingTop) {
9370 let rect = dom.getBoundingClientRect();
9371 return { left: 0, right: rect.right - rect.left,
9372 top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) };
9373 }
9374 // Line gaps are placeholder widgets used to hide pieces of overlong
9375 // lines within the viewport, as a kludge to keep the editor
9376 // responsive when a ridiculously long line is loaded into it.
9377 class LineGap {
9378 constructor(from, to, size) {
9379 this.from = from;
9380 this.to = to;
9381 this.size = size;
9382 }
9383 static same(a, b) {
9384 if (a.length != b.length)
9385 return false;
9386 for (let i = 0; i < a.length; i++) {
9387 let gA = a[i], gB = b[i];
9388 if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
9389 return false;
9390 }
9391 return true;
9392 }
9393 draw(viewState, wrapping) {
9394 return Decoration.replace({
9395 widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
9396 }).range(this.from, this.to);
9397 }
9398 }
9399 class LineGapWidget extends WidgetType {
9400 constructor(size, vertical) {
9401 super();
9402 this.size = size;
9403 this.vertical = vertical;
9404 }
9405 eq(other) { return other.size == this.size && other.vertical == this.vertical; }
9406 toDOM() {
9407 let elt = document.createElement("div");
9408 if (this.vertical) {
9409 elt.style.height = this.size + "px";
9410 }
9411 else {
9412 elt.style.width = this.size + "px";
9413 elt.style.height = "2px";
9414 elt.style.display = "inline-block";
9415 }
9416 return elt;
9417 }
9418 get estimatedHeight() { return this.vertical ? this.size : -1; }
9419 }
9420 class ViewState {
9421 constructor(state) {
9422 this.state = state;
9423 // These are contentDOM-local coordinates
9424 this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
9425 this.inView = true;
9426 this.paddingTop = 0; // Padding above the document, scaled
9427 this.paddingBottom = 0; // Padding below the document, scaled
9428 this.contentDOMWidth = 0; // contentDOM.getBoundingClientRect().width
9429 this.contentDOMHeight = 0; // contentDOM.getBoundingClientRect().height
9430 this.editorHeight = 0; // scrollDOM.clientHeight, unscaled
9431 this.editorWidth = 0; // scrollDOM.clientWidth, unscaled
9432 this.scrollTop = 0; // Last seen scrollDOM.scrollTop, scaled
9433 this.scrolledToBottom = true;
9434 // The CSS-transformation scale of the editor (transformed size /
9435 // concrete size)
9436 this.scaleX = 1;
9437 this.scaleY = 1;
9438 // The vertical position (document-relative) to which to anchor the
9439 // scroll position. -1 means anchor to the end of the document.
9440 this.scrollAnchorPos = 0;
9441 // The height at the anchor position. Set by the DOM update phase.
9442 // -1 means no height available.
9443 this.scrollAnchorHeight = -1;
9444 // See VP.MaxDOMHeight
9445 this.scaler = IdScaler;
9446 this.scrollTarget = null;
9447 // Briefly set to true when printing, to disable viewport limiting
9448 this.printing = false;
9449 // Flag set when editor content was redrawn, so that the next
9450 // measure stage knows it must read DOM layout
9451 this.mustMeasureContent = true;
9452 this.defaultTextDirection = exports.Direction.LTR;
9453 this.visibleRanges = [];
9454 // Cursor 'assoc' is only significant when the cursor is on a line
9455 // wrap point, where it must stick to the character that it is
9456 // associated with. Since browsers don't provide a reasonable
9457 // interface to set or query this, when a selection is set that
9458 // might cause this to be significant, this flag is set. The next
9459 // measure phase will check whether the cursor is on a line-wrapping
9460 // boundary and, if so, reset it to make sure it is positioned in
9461 // the right place.
9462 this.mustEnforceCursorAssoc = false;
9463 let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping");
9464 this.heightOracle = new HeightOracle(guessWrapping);
9465 this.stateDeco = state.facet(decorations).filter(d => typeof d != "function");
9466 this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
9467 this.viewport = this.getViewport(0, null);
9468 this.updateViewportLines();
9469 this.updateForViewport();
9470 this.lineGaps = this.ensureLineGaps([]);
9471 this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));
9472 this.computeVisibleRanges();
9473 }
9474 updateForViewport() {
9475 let viewports = [this.viewport], { main } = this.state.selection;
9476 for (let i = 0; i <= 1; i++) {
9477 let pos = i ? main.head : main.anchor;
9478 if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) {
9479 let { from, to } = this.lineBlockAt(pos);
9480 viewports.push(new Viewport(from, to));
9481 }
9482 }
9483 this.viewports = viewports.sort((a, b) => a.from - b.from);
9484 this.scaler = this.heightMap.height <= 7000000 /* VP.MaxDOMHeight */ ? IdScaler :
9485 new BigScaler(this.heightOracle, this.heightMap, this.viewports);
9486 }
9487 updateViewportLines() {
9488 this.viewportLines = [];
9489 this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
9490 this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler));
9491 });
9492 }
9493 update(update, scrollTarget = null) {
9494 this.state = update.state;
9495 let prevDeco = this.stateDeco;
9496 this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function");
9497 let contentChanges = update.changedRanges;
9498 let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
9499 let prevHeight = this.heightMap.height;
9500 let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
9501 this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
9502 if (this.heightMap.height != prevHeight)
9503 update.flags |= 2 /* UpdateFlag.Height */;
9504 if (scrollAnchor) {
9505 this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
9506 this.scrollAnchorHeight = scrollAnchor.top;
9507 }
9508 else {
9509 this.scrollAnchorPos = -1;
9510 this.scrollAnchorHeight = this.heightMap.height;
9511 }
9512 let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
9513 if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) ||
9514 !this.viewportIsAppropriate(viewport))
9515 viewport = this.getViewport(0, scrollTarget);
9516 let updateLines = !update.changes.empty || (update.flags & 2 /* UpdateFlag.Height */) ||
9517 viewport.from != this.viewport.from || viewport.to != this.viewport.to;
9518 this.viewport = viewport;
9519 this.updateForViewport();
9520 if (updateLines)
9521 this.updateViewportLines();
9522 if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
9523 this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
9524 update.flags |= this.computeVisibleRanges();
9525 if (scrollTarget)
9526 this.scrollTarget = scrollTarget;
9527 if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&
9528 update.state.selection.main.empty && update.state.selection.main.assoc &&
9529 !update.state.facet(nativeSelectionHidden))
9530 this.mustEnforceCursorAssoc = true;
9531 }
9532 measure(view) {
9533 let dom = view.contentDOM, style = window.getComputedStyle(dom);
9534 let oracle = this.heightOracle;
9535 let whiteSpace = style.whiteSpace;
9536 this.defaultTextDirection = style.direction == "rtl" ? exports.Direction.RTL : exports.Direction.LTR;
9537 let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
9538 let domRect = dom.getBoundingClientRect();
9539 let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
9540 this.contentDOMHeight = domRect.height;
9541 this.mustMeasureContent = false;
9542 let result = 0, bias = 0;
9543 if (domRect.width && domRect.height) {
9544 let { scaleX, scaleY } = getScale(dom, domRect);
9545 if (this.scaleX != scaleX || this.scaleY != scaleY) {
9546 this.scaleX = scaleX;
9547 this.scaleY = scaleY;
9548 result |= 8 /* UpdateFlag.Geometry */;
9549 refresh = measureContent = true;
9550 }
9551 }
9552 // Vertical padding
9553 let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
9554 let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
9555 if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
9556 this.paddingTop = paddingTop;
9557 this.paddingBottom = paddingBottom;
9558 result |= 8 /* UpdateFlag.Geometry */ | 2 /* UpdateFlag.Height */;
9559 }
9560 if (this.editorWidth != view.scrollDOM.clientWidth) {
9561 if (oracle.lineWrapping)
9562 measureContent = true;
9563 this.editorWidth = view.scrollDOM.clientWidth;
9564 result |= 8 /* UpdateFlag.Geometry */;
9565 }
9566 let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
9567 if (this.scrollTop != scrollTop) {
9568 this.scrollAnchorHeight = -1;
9569 this.scrollTop = scrollTop;
9570 }
9571 this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
9572 // Pixel viewport
9573 let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
9574 let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
9575 this.pixelViewport = pixelViewport;
9576 let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
9577 if (inView != this.inView) {
9578 this.inView = inView;
9579 if (inView)
9580 measureContent = true;
9581 }
9582 if (!this.inView && !this.scrollTarget)
9583 return 0;
9584 let contentWidth = domRect.width;
9585 if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
9586 this.contentDOMWidth = domRect.width;
9587 this.editorHeight = view.scrollDOM.clientHeight;
9588 result |= 8 /* UpdateFlag.Geometry */;
9589 }
9590 if (measureContent) {
9591 let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
9592 if (oracle.mustRefreshForHeights(lineHeights))
9593 refresh = true;
9594 if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
9595 let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize();
9596 refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
9597 if (refresh) {
9598 view.docView.minWidth = 0;
9599 result |= 8 /* UpdateFlag.Geometry */;
9600 }
9601 }
9602 if (dTop > 0 && dBottom > 0)
9603 bias = Math.max(dTop, dBottom);
9604 else if (dTop < 0 && dBottom < 0)
9605 bias = Math.min(dTop, dBottom);
9606 oracle.heightChanged = false;
9607 for (let vp of this.viewports) {
9608 let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
9609 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));
9610 }
9611 if (oracle.heightChanged)
9612 result |= 2 /* UpdateFlag.Height */;
9613 }
9614 let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) ||
9615 this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from ||
9616 this.scrollTarget.range.head > this.viewport.to);
9617 if (viewportChange)
9618 this.viewport = this.getViewport(bias, this.scrollTarget);
9619 this.updateForViewport();
9620 if ((result & 2 /* UpdateFlag.Height */) || viewportChange)
9621 this.updateViewportLines();
9622 if (this.lineGaps.length || this.viewport.to - this.viewport.from > (2000 /* LG.Margin */ << 1))
9623 this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
9624 result |= this.computeVisibleRanges();
9625 if (this.mustEnforceCursorAssoc) {
9626 this.mustEnforceCursorAssoc = false;
9627 // This is done in the read stage, because moving the selection
9628 // to a line end is going to trigger a layout anyway, so it
9629 // can't be a pure write. It should be rare that it does any
9630 // writing.
9631 view.docView.enforceCursorAssoc();
9632 }
9633 return result;
9634 }
9635 get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top); }
9636 get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom); }
9637 getViewport(bias, scrollTarget) {
9638 // This will divide VP.Margin between the top and the
9639 // bottom, depending on the bias (the change in viewport position
9640 // since the last update). It'll hold a number between 0 and 1
9641 let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* VP.Margin */ / 2));
9642 let map = this.heightMap, oracle = this.heightOracle;
9643 let { visibleTop, visibleBottom } = this;
9644 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);
9645 // If scrollTarget is given, make sure the viewport includes that position
9646 if (scrollTarget) {
9647 let { head } = scrollTarget.range;
9648 if (head < viewport.from || head > viewport.to) {
9649 let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
9650 let block = map.lineAt(head, QueryType$1.ByPos, oracle, 0, 0), topPos;
9651 if (scrollTarget.y == "center")
9652 topPos = (block.top + block.bottom) / 2 - viewHeight / 2;
9653 else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from)
9654 topPos = block.top;
9655 else
9656 topPos = block.bottom - viewHeight;
9657 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);
9658 }
9659 }
9660 return viewport;
9661 }
9662 mapViewport(viewport, changes) {
9663 let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
9664 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);
9665 }
9666 // Checks if a given viewport covers the visible part of the
9667 // document and not too much beyond that.
9668 viewportIsAppropriate({ from, to }, bias = 0) {
9669 if (!this.inView)
9670 return true;
9671 let { top } = this.heightMap.lineAt(from, QueryType$1.ByPos, this.heightOracle, 0, 0);
9672 let { bottom } = this.heightMap.lineAt(to, QueryType$1.ByPos, this.heightOracle, 0, 0);
9673 let { visibleTop, visibleBottom } = this;
9674 return (from == 0 || top <= visibleTop - Math.max(10 /* VP.MinCoverMargin */, Math.min(-bias, 250 /* VP.MaxCoverMargin */))) &&
9675 (to == this.state.doc.length ||
9676 bottom >= visibleBottom + Math.max(10 /* VP.MinCoverMargin */, Math.min(bias, 250 /* VP.MaxCoverMargin */))) &&
9677 (top > visibleTop - 2 * 1000 /* VP.Margin */ && bottom < visibleBottom + 2 * 1000 /* VP.Margin */);
9678 }
9679 mapLineGaps(gaps, changes) {
9680 if (!gaps.length || changes.empty)
9681 return gaps;
9682 let mapped = [];
9683 for (let gap of gaps)
9684 if (!changes.touchesRange(gap.from, gap.to))
9685 mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
9686 return mapped;
9687 }
9688 // Computes positions in the viewport where the start or end of a
9689 // line should be hidden, trying to reuse existing line gaps when
9690 // appropriate to avoid unneccesary redraws.
9691 // Uses crude character-counting for the positioning and sizing,
9692 // since actual DOM coordinates aren't always available and
9693 // predictable. Relies on generous margins (see LG.Margin) to hide
9694 // the artifacts this might produce from the user.
9695 ensureLineGaps(current, mayMeasure) {
9696 let wrapping = this.heightOracle.lineWrapping;
9697 let margin = wrapping ? 10000 /* LG.MarginWrap */ : 2000 /* LG.Margin */, halfMargin = margin >> 1, doubleMargin = margin << 1;
9698 // The non-wrapping logic won't work at all in predominantly right-to-left text.
9699 if (this.defaultTextDirection != exports.Direction.LTR && !wrapping)
9700 return [];
9701 let gaps = [];
9702 let addGap = (from, to, line, structure) => {
9703 if (to - from < halfMargin)
9704 return;
9705 let sel = this.state.selection.main, avoid = [sel.from];
9706 if (!sel.empty)
9707 avoid.push(sel.to);
9708 for (let pos of avoid) {
9709 if (pos > from && pos < to) {
9710 addGap(from, pos - 10 /* LG.SelectionMargin */, line, structure);
9711 addGap(pos + 10 /* LG.SelectionMargin */, to, line, structure);
9712 return;
9713 }
9714 }
9715 let gap = find(current, gap => gap.from >= line.from && gap.to <= line.to &&
9716 Math.abs(gap.from - from) < halfMargin && Math.abs(gap.to - to) < halfMargin &&
9717 !avoid.some(pos => gap.from < pos && gap.to > pos));
9718 if (!gap) {
9719 // When scrolling down, snap gap ends to line starts to avoid shifts in wrapping
9720 if (to < line.to && mayMeasure && wrapping &&
9721 mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
9722 let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
9723 if (lineStart > from)
9724 to = lineStart;
9725 }
9726 gap = new LineGap(from, to, this.gapSize(line, from, to, structure));
9727 }
9728 gaps.push(gap);
9729 };
9730 for (let line of this.viewportLines) {
9731 if (line.length < doubleMargin)
9732 continue;
9733 let structure = lineStructure(line.from, line.to, this.stateDeco);
9734 if (structure.total < doubleMargin)
9735 continue;
9736 let target = this.scrollTarget ? this.scrollTarget.range.head : null;
9737 let viewFrom, viewTo;
9738 if (wrapping) {
9739 let marginHeight = (margin / this.heightOracle.lineLength) * this.heightOracle.lineHeight;
9740 let top, bot;
9741 if (target != null) {
9742 let targetFrac = findFraction(structure, target);
9743 let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
9744 top = targetFrac - spaceFrac;
9745 bot = targetFrac + spaceFrac;
9746 }
9747 else {
9748 top = (this.visibleTop - line.top - marginHeight) / line.height;
9749 bot = (this.visibleBottom - line.top + marginHeight) / line.height;
9750 }
9751 viewFrom = findPosition(structure, top);
9752 viewTo = findPosition(structure, bot);
9753 }
9754 else {
9755 let totalWidth = structure.total * this.heightOracle.charWidth;
9756 let marginWidth = margin * this.heightOracle.charWidth;
9757 let left, right;
9758 if (target != null) {
9759 let targetFrac = findFraction(structure, target);
9760 let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;
9761 left = targetFrac - spaceFrac;
9762 right = targetFrac + spaceFrac;
9763 }
9764 else {
9765 left = (this.pixelViewport.left - marginWidth) / totalWidth;
9766 right = (this.pixelViewport.right + marginWidth) / totalWidth;
9767 }
9768 viewFrom = findPosition(structure, left);
9769 viewTo = findPosition(structure, right);
9770 }
9771 if (viewFrom > line.from)
9772 addGap(line.from, viewFrom, line, structure);
9773 if (viewTo < line.to)
9774 addGap(viewTo, line.to, line, structure);
9775 }
9776 return gaps;
9777 }
9778 gapSize(line, from, to, structure) {
9779 let fraction = findFraction(structure, to) - findFraction(structure, from);
9780 if (this.heightOracle.lineWrapping) {
9781 return line.height * fraction;
9782 }
9783 else {
9784 return structure.total * this.heightOracle.charWidth * fraction;
9785 }
9786 }
9787 updateLineGaps(gaps) {
9788 if (!LineGap.same(gaps, this.lineGaps)) {
9789 this.lineGaps = gaps;
9790 this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
9791 }
9792 }
9793 computeVisibleRanges() {
9794 let deco = this.stateDeco;
9795 if (this.lineGaps.length)
9796 deco = deco.concat(this.lineGapDeco);
9797 let ranges = [];
9798 RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
9799 span(from, to) { ranges.push({ from, to }); },
9800 point() { }
9801 }, 20);
9802 let changed = ranges.length != this.visibleRanges.length ||
9803 this.visibleRanges.some((r, i) => r.from != ranges[i].from || r.to != ranges[i].to);
9804 this.visibleRanges = ranges;
9805 return changed ? 4 /* UpdateFlag.Viewport */ : 0;
9806 }
9807 lineBlockAt(pos) {
9808 return (pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos)) ||
9809 scaleBlock(this.heightMap.lineAt(pos, QueryType$1.ByPos, this.heightOracle, 0, 0), this.scaler);
9810 }
9811 lineBlockAtHeight(height) {
9812 return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$1.ByHeight, this.heightOracle, 0, 0), this.scaler);
9813 }
9814 scrollAnchorAt(scrollTop) {
9815 let block = this.lineBlockAtHeight(scrollTop + 8);
9816 return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
9817 }
9818 elementAtHeight(height) {
9819 return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
9820 }
9821 get docHeight() {
9822 return this.scaler.toDOM(this.heightMap.height);
9823 }
9824 get contentHeight() {
9825 return this.docHeight + this.paddingTop + this.paddingBottom;
9826 }
9827 }
9828 class Viewport {
9829 constructor(from, to) {
9830 this.from = from;
9831 this.to = to;
9832 }
9833 }
9834 function lineStructure(from, to, stateDeco) {
9835 let ranges = [], pos = from, total = 0;
9836 RangeSet.spans(stateDeco, from, to, {
9837 span() { },
9838 point(from, to) {
9839 if (from > pos) {
9840 ranges.push({ from: pos, to: from });
9841 total += from - pos;
9842 }
9843 pos = to;
9844 }
9845 }, 20); // We're only interested in collapsed ranges of a significant size
9846 if (pos < to) {
9847 ranges.push({ from: pos, to });
9848 total += to - pos;
9849 }
9850 return { total, ranges };
9851 }
9852 function findPosition({ total, ranges }, ratio) {
9853 if (ratio <= 0)
9854 return ranges[0].from;
9855 if (ratio >= 1)
9856 return ranges[ranges.length - 1].to;
9857 let dist = Math.floor(total * ratio);
9858 for (let i = 0;; i++) {
9859 let { from, to } = ranges[i], size = to - from;
9860 if (dist <= size)
9861 return from + dist;
9862 dist -= size;
9863 }
9864 }
9865 function findFraction(structure, pos) {
9866 let counted = 0;
9867 for (let { from, to } of structure.ranges) {
9868 if (pos <= to) {
9869 counted += pos - from;
9870 break;
9871 }
9872 counted += to - from;
9873 }
9874 return counted / structure.total;
9875 }
9876 function find(array, f) {
9877 for (let val of array)
9878 if (f(val))
9879 return val;
9880 return undefined;
9881 }
9882 // Don't scale when the document height is within the range of what
9883 // the DOM can handle.
9884 const IdScaler = {
9885 toDOM(n) { return n; },
9886 fromDOM(n) { return n; },
9887 scale: 1
9888 };
9889 // When the height is too big (> VP.MaxDOMHeight), scale down the
9890 // regions outside the viewports so that the total height is
9891 // VP.MaxDOMHeight.
9892 class BigScaler {
9893 constructor(oracle, heightMap, viewports) {
9894 let vpHeight = 0, base = 0, domBase = 0;
9895 this.viewports = viewports.map(({ from, to }) => {
9896 let top = heightMap.lineAt(from, QueryType$1.ByPos, oracle, 0, 0).top;
9897 let bottom = heightMap.lineAt(to, QueryType$1.ByPos, oracle, 0, 0).bottom;
9898 vpHeight += bottom - top;
9899 return { from, to, top, bottom, domTop: 0, domBottom: 0 };
9900 });
9901 this.scale = (7000000 /* VP.MaxDOMHeight */ - vpHeight) / (heightMap.height - vpHeight);
9902 for (let obj of this.viewports) {
9903 obj.domTop = domBase + (obj.top - base) * this.scale;
9904 domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
9905 base = obj.bottom;
9906 }
9907 }
9908 toDOM(n) {
9909 for (let i = 0, base = 0, domBase = 0;; i++) {
9910 let vp = i < this.viewports.length ? this.viewports[i] : null;
9911 if (!vp || n < vp.top)
9912 return domBase + (n - base) * this.scale;
9913 if (n <= vp.bottom)
9914 return vp.domTop + (n - vp.top);
9915 base = vp.bottom;
9916 domBase = vp.domBottom;
9917 }
9918 }
9919 fromDOM(n) {
9920 for (let i = 0, base = 0, domBase = 0;; i++) {
9921 let vp = i < this.viewports.length ? this.viewports[i] : null;
9922 if (!vp || n < vp.domTop)
9923 return base + (n - domBase) / this.scale;
9924 if (n <= vp.domBottom)
9925 return vp.top + (n - vp.domTop);
9926 base = vp.bottom;
9927 domBase = vp.domBottom;
9928 }
9929 }
9930 }
9931 function scaleBlock(block, scaler) {
9932 if (scaler.scale == 1)
9933 return block;
9934 let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom);
9935 return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);
9936 }
9937
9938 const theme = /*@__PURE__*/Facet.define({ combine: strs => strs.join(" ") });
9939 const darkTheme = /*@__PURE__*/Facet.define({ combine: values => values.indexOf(true) > -1 });
9940 const baseThemeID = /*@__PURE__*/StyleModule.newName(), baseLightID = /*@__PURE__*/StyleModule.newName(), baseDarkID = /*@__PURE__*/StyleModule.newName();
9941 const lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID };
9942 function buildTheme(main, spec, scopes) {
9943 return new StyleModule(spec, {
9944 finish(sel) {
9945 return /&/.test(sel) ? sel.replace(/&\w*/, m => {
9946 if (m == "&")
9947 return main;
9948 if (!scopes || !scopes[m])
9949 throw new RangeError(`Unsupported selector: ${m}`);
9950 return scopes[m];
9951 }) : main + " " + sel;
9952 }
9953 });
9954 }
9955 const baseTheme$1$2 = /*@__PURE__*/buildTheme("." + baseThemeID, {
9956 "&": {
9957 position: "relative !important",
9958 boxSizing: "border-box",
9959 "&.cm-focused": {
9960 // Provide a simple default outline to make sure a focused
9961 // editor is visually distinct. Can't leave the default behavior
9962 // because that will apply to the content element, which is
9963 // inside the scrollable container and doesn't include the
9964 // gutters. We also can't use an 'auto' outline, since those
9965 // are, for some reason, drawn behind the element content, which
9966 // will cause things like the active line background to cover
9967 // the outline (#297).
9968 outline: "1px dotted #212121"
9969 },
9970 display: "flex !important",
9971 flexDirection: "column"
9972 },
9973 ".cm-scroller": {
9974 display: "flex !important",
9975 alignItems: "flex-start !important",
9976 fontFamily: "monospace",
9977 lineHeight: 1.4,
9978 height: "100%",
9979 overflowX: "auto",
9980 position: "relative",
9981 zIndex: 0
9982 },
9983 ".cm-content": {
9984 margin: 0,
9985 flexGrow: 2,
9986 flexShrink: 0,
9987 display: "block",
9988 whiteSpace: "pre",
9989 wordWrap: "normal",
9990 boxSizing: "border-box",
9991 minHeight: "100%",
9992 padding: "4px 0",
9993 outline: "none",
9994 "&[contenteditable=true]": {
9995 WebkitUserModify: "read-write-plaintext-only",
9996 }
9997 },
9998 ".cm-lineWrapping": {
9999 whiteSpace_fallback: "pre-wrap",
10000 whiteSpace: "break-spaces",
10001 wordBreak: "break-word",
10002 overflowWrap: "anywhere",
10003 flexShrink: 1
10004 },
10005 "&light .cm-content": { caretColor: "black" },
10006 "&dark .cm-content": { caretColor: "white" },
10007 ".cm-line": {
10008 display: "block",
10009 padding: "0 2px 0 6px"
10010 },
10011 ".cm-layer": {
10012 position: "absolute",
10013 left: 0,
10014 top: 0,
10015 contain: "size style",
10016 "& > *": {
10017 position: "absolute"
10018 }
10019 },
10020 "&light .cm-selectionBackground": {
10021 background: "#d9d9d9"
10022 },
10023 "&dark .cm-selectionBackground": {
10024 background: "#222"
10025 },
10026 "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10027 background: "#d7d4f0"
10028 },
10029 "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
10030 background: "#233"
10031 },
10032 ".cm-cursorLayer": {
10033 pointerEvents: "none"
10034 },
10035 "&.cm-focused > .cm-scroller > .cm-cursorLayer": {
10036 animation: "steps(1) cm-blink 1.2s infinite"
10037 },
10038 // Two animations defined so that we can switch between them to
10039 // restart the animation without forcing another style
10040 // recomputation.
10041 "@keyframes cm-blink": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10042 "@keyframes cm-blink2": { "0%": {}, "50%": { opacity: 0 }, "100%": {} },
10043 ".cm-cursor, .cm-dropCursor": {
10044 borderLeft: "1.2px solid black",
10045 marginLeft: "-0.6px",
10046 pointerEvents: "none",
10047 },
10048 ".cm-cursor": {
10049 display: "none"
10050 },
10051 "&dark .cm-cursor": {
10052 borderLeftColor: "#444"
10053 },
10054 ".cm-dropCursor": {
10055 position: "absolute"
10056 },
10057 "&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
10058 display: "block"
10059 },
10060 ".cm-announced": {
10061 position: "fixed",
10062 top: "-10000px"
10063 },
10064 "@media print": {
10065 ".cm-announced": { display: "none" }
10066 },
10067 "&light .cm-activeLine": { backgroundColor: "#cceeff44" },
10068 "&dark .cm-activeLine": { backgroundColor: "#99eeff33" },
10069 "&light .cm-specialChar": { color: "red" },
10070 "&dark .cm-specialChar": { color: "#f78" },
10071 ".cm-gutters": {
10072 flexShrink: 0,
10073 display: "flex",
10074 height: "100%",
10075 boxSizing: "border-box",
10076 insetInlineStart: 0,
10077 zIndex: 200
10078 },
10079 "&light .cm-gutters": {
10080 backgroundColor: "#f5f5f5",
10081 color: "#6c6c6c",
10082 borderRight: "1px solid #ddd"
10083 },
10084 "&dark .cm-gutters": {
10085 backgroundColor: "#333338",
10086 color: "#ccc"
10087 },
10088 ".cm-gutter": {
10089 display: "flex !important",
10090 flexDirection: "column",
10091 flexShrink: 0,
10092 boxSizing: "border-box",
10093 minHeight: "100%",
10094 overflow: "hidden"
10095 },
10096 ".cm-gutterElement": {
10097 boxSizing: "border-box"
10098 },
10099 ".cm-lineNumbers .cm-gutterElement": {
10100 padding: "0 3px 0 5px",
10101 minWidth: "20px",
10102 textAlign: "right",
10103 whiteSpace: "nowrap"
10104 },
10105 "&light .cm-activeLineGutter": {
10106 backgroundColor: "#e2f2ff"
10107 },
10108 "&dark .cm-activeLineGutter": {
10109 backgroundColor: "#222227"
10110 },
10111 ".cm-panels": {
10112 boxSizing: "border-box",
10113 position: "sticky",
10114 left: 0,
10115 right: 0
10116 },
10117 "&light .cm-panels": {
10118 backgroundColor: "#f5f5f5",
10119 color: "black"
10120 },
10121 "&light .cm-panels-top": {
10122 borderBottom: "1px solid #ddd"
10123 },
10124 "&light .cm-panels-bottom": {
10125 borderTop: "1px solid #ddd"
10126 },
10127 "&dark .cm-panels": {
10128 backgroundColor: "#333338",
10129 color: "white"
10130 },
10131 ".cm-tab": {
10132 display: "inline-block",
10133 overflow: "hidden",
10134 verticalAlign: "bottom"
10135 },
10136 ".cm-widgetBuffer": {
10137 verticalAlign: "text-top",
10138 height: "1em",
10139 width: 0,
10140 display: "inline"
10141 },
10142 ".cm-placeholder": {
10143 color: "#888",
10144 display: "inline-block",
10145 verticalAlign: "top",
10146 },
10147 ".cm-highlightSpace:before": {
10148 content: "attr(data-display)",
10149 position: "absolute",
10150 pointerEvents: "none",
10151 color: "#888"
10152 },
10153 ".cm-highlightTab": {
10154 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>')`,
10155 backgroundSize: "auto 100%",
10156 backgroundPosition: "right 90%",
10157 backgroundRepeat: "no-repeat"
10158 },
10159 ".cm-trailingSpace": {
10160 backgroundColor: "#ff332255"
10161 },
10162 ".cm-button": {
10163 verticalAlign: "middle",
10164 color: "inherit",
10165 fontSize: "70%",
10166 padding: ".2em 1em",
10167 borderRadius: "1px"
10168 },
10169 "&light .cm-button": {
10170 backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
10171 border: "1px solid #888",
10172 "&:active": {
10173 backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
10174 }
10175 },
10176 "&dark .cm-button": {
10177 backgroundImage: "linear-gradient(#393939, #111)",
10178 border: "1px solid #888",
10179 "&:active": {
10180 backgroundImage: "linear-gradient(#111, #333)"
10181 }
10182 },
10183 ".cm-textfield": {
10184 verticalAlign: "middle",
10185 color: "inherit",
10186 fontSize: "70%",
10187 border: "1px solid silver",
10188 padding: ".2em .5em"
10189 },
10190 "&light .cm-textfield": {
10191 backgroundColor: "white"
10192 },
10193 "&dark .cm-textfield": {
10194 border: "1px solid #555",
10195 backgroundColor: "inherit"
10196 }
10197 }, lightDarkIDs);
10198
10199 const LineBreakPlaceholder = "\uffff";
10200 class DOMReader {
10201 constructor(points, state) {
10202 this.points = points;
10203 this.text = "";
10204 this.lineSeparator = state.facet(EditorState.lineSeparator);
10205 }
10206 append(text) {
10207 this.text += text;
10208 }
10209 lineBreak() {
10210 this.text += LineBreakPlaceholder;
10211 }
10212 readRange(start, end) {
10213 if (!start)
10214 return this;
10215 let parent = start.parentNode;
10216 for (let cur = start;;) {
10217 this.findPointBefore(parent, cur);
10218 let oldLen = this.text.length;
10219 this.readNode(cur);
10220 let next = cur.nextSibling;
10221 if (next == end)
10222 break;
10223 let view = ContentView.get(cur), nextView = ContentView.get(next);
10224 if (view && nextView ? view.breakAfter :
10225 (view ? view.breakAfter : isBlockElement(cur)) ||
10226 (isBlockElement(next) && (cur.nodeName != "BR" || cur.cmIgnore) && this.text.length > oldLen))
10227 this.lineBreak();
10228 cur = next;
10229 }
10230 this.findPointBefore(parent, end);
10231 return this;
10232 }
10233 readTextNode(node) {
10234 let text = node.nodeValue;
10235 for (let point of this.points)
10236 if (point.node == node)
10237 point.pos = this.text.length + Math.min(point.offset, text.length);
10238 for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
10239 let nextBreak = -1, breakSize = 1, m;
10240 if (this.lineSeparator) {
10241 nextBreak = text.indexOf(this.lineSeparator, off);
10242 breakSize = this.lineSeparator.length;
10243 }
10244 else if (m = re.exec(text)) {
10245 nextBreak = m.index;
10246 breakSize = m[0].length;
10247 }
10248 this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
10249 if (nextBreak < 0)
10250 break;
10251 this.lineBreak();
10252 if (breakSize > 1)
10253 for (let point of this.points)
10254 if (point.node == node && point.pos > this.text.length)
10255 point.pos -= breakSize - 1;
10256 off = nextBreak + breakSize;
10257 }
10258 }
10259 readNode(node) {
10260 if (node.cmIgnore)
10261 return;
10262 let view = ContentView.get(node);
10263 let fromView = view && view.overrideDOMText;
10264 if (fromView != null) {
10265 this.findPointInside(node, fromView.length);
10266 for (let i = fromView.iter(); !i.next().done;) {
10267 if (i.lineBreak)
10268 this.lineBreak();
10269 else
10270 this.append(i.value);
10271 }
10272 }
10273 else if (node.nodeType == 3) {
10274 this.readTextNode(node);
10275 }
10276 else if (node.nodeName == "BR") {
10277 if (node.nextSibling)
10278 this.lineBreak();
10279 }
10280 else if (node.nodeType == 1) {
10281 this.readRange(node.firstChild, null);
10282 }
10283 }
10284 findPointBefore(node, next) {
10285 for (let point of this.points)
10286 if (point.node == node && node.childNodes[point.offset] == next)
10287 point.pos = this.text.length;
10288 }
10289 findPointInside(node, length) {
10290 for (let point of this.points)
10291 if (node.nodeType == 3 ? point.node == node : node.contains(point.node))
10292 point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
10293 }
10294 }
10295 function isAtEnd(parent, node, offset) {
10296 for (;;) {
10297 if (!node || offset < maxOffset(node))
10298 return false;
10299 if (node == parent)
10300 return true;
10301 offset = domIndex(node) + 1;
10302 node = node.parentNode;
10303 }
10304 }
10305 function isBlockElement(node) {
10306 return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
10307 }
10308 class DOMPoint {
10309 constructor(node, offset) {
10310 this.node = node;
10311 this.offset = offset;
10312 this.pos = -1;
10313 }
10314 }
10315
10316 class DOMChange {
10317 constructor(view, start, end, typeOver) {
10318 this.typeOver = typeOver;
10319 this.bounds = null;
10320 this.text = "";
10321 let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
10322 if (view.state.readOnly && start > -1) {
10323 // Ignore changes when the editor is read-only
10324 this.newSel = null;
10325 }
10326 else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
10327 let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
10328 let reader = new DOMReader(selPoints, view.state);
10329 reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
10330 this.text = reader.text;
10331 this.newSel = selectionFromPoints(selPoints, this.bounds.from);
10332 }
10333 else {
10334 let domSel = view.observer.selectionRange;
10335 let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ||
10336 !contains(view.contentDOM, domSel.focusNode)
10337 ? view.state.selection.main.head
10338 : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
10339 let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset ||
10340 !contains(view.contentDOM, domSel.anchorNode)
10341 ? view.state.selection.main.anchor
10342 : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
10343 this.newSel = EditorSelection.single(anchor, head);
10344 }
10345 }
10346 }
10347 function applyDOMChange(view, domChange) {
10348 let change;
10349 let { newSel } = domChange, sel = view.state.selection.main;
10350 let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
10351 if (domChange.bounds) {
10352 let { from, to } = domChange.bounds;
10353 let preferredPos = sel.from, preferredSide = null;
10354 // Prefer anchoring to end when Backspace is pressed (or, on
10355 // Android, when something was deleted)
10356 if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
10357 preferredPos = sel.to;
10358 preferredSide = "end";
10359 }
10360 let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
10361 if (diff) {
10362 // Chrome inserts two newlines when pressing shift-enter at the
10363 // end of a line. DomChange drops one of those.
10364 if (browser.chrome && lastKey == 13 &&
10365 diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder)
10366 diff.toB--;
10367 change = { from: from + diff.from, to: from + diff.toA,
10368 insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) };
10369 }
10370 }
10371 else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) {
10372 newSel = null;
10373 }
10374 if (!change && !newSel)
10375 return false;
10376 if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) {
10377 // Heuristic to notice typing over a selected character
10378 change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
10379 }
10380 else if (change && change.from >= sel.from && change.to <= sel.to &&
10381 (change.from != sel.from || change.to != sel.to) &&
10382 (sel.to - sel.from) - (change.to - change.from) <= 4) {
10383 // If the change is inside the selection and covers most of it,
10384 // assume it is a selection replace (with identical characters at
10385 // the start/end not included in the diff)
10386 change = {
10387 from: sel.from, to: sel.to,
10388 insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
10389 };
10390 }
10391 else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 &&
10392 /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
10393 // Detect insert-period-on-double-space Mac and Android behavior,
10394 // and transform it into a regular space insert.
10395 if (newSel && change.insert.length == 2)
10396 newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
10397 change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
10398 }
10399 else if (browser.chrome && change && change.from == change.to && change.from == sel.head &&
10400 change.insert.toString() == "\n " && view.lineWrapping) {
10401 // In Chrome, if you insert a space at the start of a wrapped
10402 // line, it will actually insert a newline and a space, causing a
10403 // bogus new line to be created in CodeMirror (#968)
10404 if (newSel)
10405 newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
10406 change = { from: sel.from, to: sel.to, insert: Text.of([" "]) };
10407 }
10408 if (change) {
10409 if (browser.ios && view.inputState.flushIOSKey())
10410 return true;
10411 // Android browsers don't fire reasonable key events for enter,
10412 // backspace, or delete. So this detects changes that look like
10413 // they're caused by those keys, and reinterprets them as key
10414 // events. (Some of these keys are also handled by beforeinput
10415 // events and the pendingAndroidKey mechanism, but that's not
10416 // reliable in all situations.)
10417 if (browser.android &&
10418 ((change.from == sel.from && change.to == sel.to &&
10419 change.insert.length == 1 && change.insert.lines == 2 &&
10420 dispatchKey(view.contentDOM, "Enter", 13)) ||
10421 ((change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 ||
10422 lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) &&
10423 dispatchKey(view.contentDOM, "Backspace", 8)) ||
10424 (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&
10425 dispatchKey(view.contentDOM, "Delete", 46))))
10426 return true;
10427 let text = change.insert.toString();
10428 if (view.inputState.composing >= 0)
10429 view.inputState.composing++;
10430 let defaultTr;
10431 let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
10432 if (!view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)))
10433 view.dispatch(defaultInsert());
10434 return true;
10435 }
10436 else if (newSel && !newSel.main.eq(sel)) {
10437 let scrollIntoView = false, userEvent = "select";
10438 if (view.inputState.lastSelectionTime > Date.now() - 50) {
10439 if (view.inputState.lastSelectionOrigin == "select")
10440 scrollIntoView = true;
10441 userEvent = view.inputState.lastSelectionOrigin;
10442 }
10443 view.dispatch({ selection: newSel, scrollIntoView, userEvent });
10444 return true;
10445 }
10446 else {
10447 return false;
10448 }
10449 }
10450 function applyDefaultInsert(view, change, newSel) {
10451 let tr, startState = view.state, sel = startState.selection.main;
10452 if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 &&
10453 (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) &&
10454 view.inputState.composing < 0) {
10455 let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
10456 let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
10457 tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) + after));
10458 }
10459 else {
10460 let changes = startState.changes(change);
10461 let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : undefined;
10462 // Try to apply a composition change to all cursors
10463 if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 &&
10464 change.to <= sel.to && change.to >= sel.to - 10) {
10465 let replaced = view.state.sliceDoc(change.from, change.to);
10466 let compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head);
10467 if (composition) {
10468 let dLen = change.insert.length - (change.to - change.from);
10469 compositionRange = { from: composition.from, to: composition.to - dLen };
10470 }
10471 else {
10472 compositionRange = view.state.doc.lineAt(sel.head);
10473 }
10474 let offset = sel.to - change.to, size = sel.to - sel.from;
10475 tr = startState.changeByRange(range => {
10476 if (range.from == sel.from && range.to == sel.to)
10477 return { changes, range: mainSel || range.map(changes) };
10478 let to = range.to - offset, from = to - replaced.length;
10479 if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced ||
10480 // Unfortunately, there's no way to make multiple
10481 // changes in the same node work without aborting
10482 // composition, so cursors in the composition range are
10483 // ignored.
10484 range.to >= compositionRange.from && range.from <= compositionRange.to)
10485 return { range };
10486 let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to;
10487 return {
10488 changes: rangeChanges,
10489 range: !mainSel ? range.map(rangeChanges) :
10490 EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
10491 };
10492 });
10493 }
10494 else {
10495 tr = {
10496 changes,
10497 selection: mainSel && startState.selection.replaceRange(mainSel)
10498 };
10499 }
10500 }
10501 let userEvent = "input.type";
10502 if (view.composing ||
10503 view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
10504 view.inputState.compositionPendingChange = false;
10505 userEvent += ".compose";
10506 if (view.inputState.compositionFirstChange) {
10507 userEvent += ".start";
10508 view.inputState.compositionFirstChange = false;
10509 }
10510 }
10511 return startState.update(tr, { userEvent, scrollIntoView: true });
10512 }
10513 function findDiff(a, b, preferredPos, preferredSide) {
10514 let minLen = Math.min(a.length, b.length);
10515 let from = 0;
10516 while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
10517 from++;
10518 if (from == minLen && a.length == b.length)
10519 return null;
10520 let toA = a.length, toB = b.length;
10521 while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
10522 toA--;
10523 toB--;
10524 }
10525 if (preferredSide == "end") {
10526 let adjust = Math.max(0, from - Math.min(toA, toB));
10527 preferredPos -= toA + adjust - from;
10528 }
10529 if (toA < from && a.length < b.length) {
10530 let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
10531 from -= move;
10532 toB = from + (toB - toA);
10533 toA = from;
10534 }
10535 else if (toB < from) {
10536 let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
10537 from -= move;
10538 toA = from + (toA - toB);
10539 toB = from;
10540 }
10541 return { from, toA, toB };
10542 }
10543 function selectionPoints(view) {
10544 let result = [];
10545 if (view.root.activeElement != view.contentDOM)
10546 return result;
10547 let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange;
10548 if (anchorNode) {
10549 result.push(new DOMPoint(anchorNode, anchorOffset));
10550 if (focusNode != anchorNode || focusOffset != anchorOffset)
10551 result.push(new DOMPoint(focusNode, focusOffset));
10552 }
10553 return result;
10554 }
10555 function selectionFromPoints(points, base) {
10556 if (points.length == 0)
10557 return null;
10558 let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
10559 return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null;
10560 }
10561
10562 const observeOptions = {
10563 childList: true,
10564 characterData: true,
10565 subtree: true,
10566 attributes: true,
10567 characterDataOldValue: true
10568 };
10569 // IE11 has very broken mutation observers, so we also listen to
10570 // DOMCharacterDataModified there
10571 const useCharData = browser.ie && browser.ie_version <= 11;
10572 class DOMObserver {
10573 constructor(view) {
10574 this.view = view;
10575 this.active = false;
10576 // The known selection. Kept in our own object, as opposed to just
10577 // directly accessing the selection because:
10578 // - Safari doesn't report the right selection in shadow DOM
10579 // - Reading from the selection forces a DOM layout
10580 // - This way, we can ignore selectionchange events if we have
10581 // already seen the 'new' selection
10582 this.selectionRange = new DOMSelectionState;
10583 // Set when a selection change is detected, cleared on flush
10584 this.selectionChanged = false;
10585 this.delayedFlush = -1;
10586 this.resizeTimeout = -1;
10587 this.queue = [];
10588 this.delayedAndroidKey = null;
10589 this.flushingAndroidKey = -1;
10590 this.lastChange = 0;
10591 this.scrollTargets = [];
10592 this.intersection = null;
10593 this.resizeScroll = null;
10594 this.intersecting = false;
10595 this.gapIntersection = null;
10596 this.gaps = [];
10597 // Timeout for scheduling check of the parents that need scroll handlers
10598 this.parentCheck = -1;
10599 this.dom = view.contentDOM;
10600 this.observer = new MutationObserver(mutations => {
10601 for (let mut of mutations)
10602 this.queue.push(mut);
10603 // IE11 will sometimes (on typing over a selection or
10604 // backspacing out a single character text node) call the
10605 // observer callback before actually updating the DOM.
10606 //
10607 // Unrelatedly, iOS Safari will, when ending a composition,
10608 // sometimes first clear it, deliver the mutations, and then
10609 // reinsert the finished text. CodeMirror's handling of the
10610 // deletion will prevent the reinsertion from happening,
10611 // breaking composition.
10612 if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) &&
10613 mutations.some(m => m.type == "childList" && m.removedNodes.length ||
10614 m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
10615 this.flushSoon();
10616 else
10617 this.flush();
10618 });
10619 if (useCharData)
10620 this.onCharData = (event) => {
10621 this.queue.push({ target: event.target,
10622 type: "characterData",
10623 oldValue: event.prevValue });
10624 this.flushSoon();
10625 };
10626 this.onSelectionChange = this.onSelectionChange.bind(this);
10627 this.onResize = this.onResize.bind(this);
10628 this.onPrint = this.onPrint.bind(this);
10629 this.onScroll = this.onScroll.bind(this);
10630 if (typeof ResizeObserver == "function") {
10631 this.resizeScroll = new ResizeObserver(() => {
10632 var _a;
10633 if (((_a = this.view.docView) === null || _a === void 0 ? void 0 : _a.lastUpdate) < Date.now() - 75)
10634 this.onResize();
10635 });
10636 this.resizeScroll.observe(view.scrollDOM);
10637 }
10638 this.addWindowListeners(this.win = view.win);
10639 this.start();
10640 if (typeof IntersectionObserver == "function") {
10641 this.intersection = new IntersectionObserver(entries => {
10642 if (this.parentCheck < 0)
10643 this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);
10644 if (entries.length > 0 && (entries[entries.length - 1].intersectionRatio > 0) != this.intersecting) {
10645 this.intersecting = !this.intersecting;
10646 if (this.intersecting != this.view.inView)
10647 this.onScrollChanged(document.createEvent("Event"));
10648 }
10649 }, { threshold: [0, .001] });
10650 this.intersection.observe(this.dom);
10651 this.gapIntersection = new IntersectionObserver(entries => {
10652 if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0)
10653 this.onScrollChanged(document.createEvent("Event"));
10654 }, {});
10655 }
10656 this.listenForScroll();
10657 this.readSelectionRange();
10658 }
10659 onScrollChanged(e) {
10660 this.view.inputState.runHandlers("scroll", e);
10661 if (this.intersecting)
10662 this.view.measure();
10663 }
10664 onScroll(e) {
10665 if (this.intersecting)
10666 this.flush(false);
10667 this.onScrollChanged(e);
10668 }
10669 onResize() {
10670 if (this.resizeTimeout < 0)
10671 this.resizeTimeout = setTimeout(() => {
10672 this.resizeTimeout = -1;
10673 this.view.requestMeasure();
10674 }, 50);
10675 }
10676 onPrint() {
10677 this.view.viewState.printing = true;
10678 this.view.measure();
10679 setTimeout(() => {
10680 this.view.viewState.printing = false;
10681 this.view.requestMeasure();
10682 }, 500);
10683 }
10684 updateGaps(gaps) {
10685 if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i) => g != gaps[i]))) {
10686 this.gapIntersection.disconnect();
10687 for (let gap of gaps)
10688 this.gapIntersection.observe(gap);
10689 this.gaps = gaps;
10690 }
10691 }
10692 onSelectionChange(event) {
10693 let wasChanged = this.selectionChanged;
10694 if (!this.readSelectionRange() || this.delayedAndroidKey)
10695 return;
10696 let { view } = this, sel = this.selectionRange;
10697 if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel))
10698 return;
10699 let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
10700 if (context && context.ignoreEvent(event)) {
10701 if (!wasChanged)
10702 this.selectionChanged = false;
10703 return;
10704 }
10705 // Deletions on IE11 fire their events in the wrong order, giving
10706 // us a selection change event before the DOM changes are
10707 // reported.
10708 // Chrome Android has a similar issue when backspacing out a
10709 // selection (#645).
10710 if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty &&
10711 // (Selection.isCollapsed isn't reliable on IE)
10712 sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
10713 this.flushSoon();
10714 else
10715 this.flush(false);
10716 }
10717 readSelectionRange() {
10718 let { view } = this;
10719 // The Selection object is broken in shadow roots in Safari. See
10720 // https://github.com/codemirror/dev/issues/414
10721 let range = browser.safari && view.root.nodeType == 11 &&
10722 deepActiveElement(this.dom.ownerDocument) == this.dom &&
10723 safariSelectionRangeHack(this.view) || getSelection(view.root);
10724 if (!range || this.selectionRange.eq(range))
10725 return false;
10726 let local = hasSelection(this.dom, range);
10727 // Detect the situation where the browser has, on focus, moved the
10728 // selection to the start of the content element. Reset it to the
10729 // position from the editor state.
10730 if (local && !this.selectionChanged &&
10731 view.inputState.lastFocusTime > Date.now() - 200 &&
10732 view.inputState.lastTouchTime < Date.now() - 300 &&
10733 atElementStart(this.dom, range)) {
10734 this.view.inputState.lastFocusTime = 0;
10735 view.docView.updateSelection();
10736 return false;
10737 }
10738 this.selectionRange.setRange(range);
10739 if (local)
10740 this.selectionChanged = true;
10741 return true;
10742 }
10743 setSelectionRange(anchor, head) {
10744 this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
10745 this.selectionChanged = false;
10746 }
10747 clearSelectionRange() {
10748 this.selectionRange.set(null, 0, null, 0);
10749 }
10750 listenForScroll() {
10751 this.parentCheck = -1;
10752 let i = 0, changed = null;
10753 for (let dom = this.dom; dom;) {
10754 if (dom.nodeType == 1) {
10755 if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
10756 i++;
10757 else if (!changed)
10758 changed = this.scrollTargets.slice(0, i);
10759 if (changed)
10760 changed.push(dom);
10761 dom = dom.assignedSlot || dom.parentNode;
10762 }
10763 else if (dom.nodeType == 11) { // Shadow root
10764 dom = dom.host;
10765 }
10766 else {
10767 break;
10768 }
10769 }
10770 if (i < this.scrollTargets.length && !changed)
10771 changed = this.scrollTargets.slice(0, i);
10772 if (changed) {
10773 for (let dom of this.scrollTargets)
10774 dom.removeEventListener("scroll", this.onScroll);
10775 for (let dom of this.scrollTargets = changed)
10776 dom.addEventListener("scroll", this.onScroll);
10777 }
10778 }
10779 ignore(f) {
10780 if (!this.active)
10781 return f();
10782 try {
10783 this.stop();
10784 return f();
10785 }
10786 finally {
10787 this.start();
10788 this.clear();
10789 }
10790 }
10791 start() {
10792 if (this.active)
10793 return;
10794 this.observer.observe(this.dom, observeOptions);
10795 if (useCharData)
10796 this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
10797 this.active = true;
10798 }
10799 stop() {
10800 if (!this.active)
10801 return;
10802 this.active = false;
10803 this.observer.disconnect();
10804 if (useCharData)
10805 this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
10806 }
10807 // Throw away any pending changes
10808 clear() {
10809 this.processRecords();
10810 this.queue.length = 0;
10811 this.selectionChanged = false;
10812 }
10813 // Chrome Android, especially in combination with GBoard, not only
10814 // doesn't reliably fire regular key events, but also often
10815 // surrounds the effect of enter or backspace with a bunch of
10816 // composition events that, when interrupted, cause text duplication
10817 // or other kinds of corruption. This hack makes the editor back off
10818 // from handling DOM changes for a moment when such a key is
10819 // detected (via beforeinput or keydown), and then tries to flush
10820 // them or, if that has no effect, dispatches the given key.
10821 delayAndroidKey(key, keyCode) {
10822 var _a;
10823 if (!this.delayedAndroidKey) {
10824 let flush = () => {
10825 let key = this.delayedAndroidKey;
10826 if (key) {
10827 this.clearDelayedAndroidKey();
10828 this.view.inputState.lastKeyCode = key.keyCode;
10829 this.view.inputState.lastKeyTime = Date.now();
10830 let flushed = this.flush();
10831 if (!flushed && key.force)
10832 dispatchKey(this.dom, key.key, key.keyCode);
10833 }
10834 };
10835 this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
10836 }
10837 // Since backspace beforeinput is sometimes signalled spuriously,
10838 // Enter always takes precedence.
10839 if (!this.delayedAndroidKey || key == "Enter")
10840 this.delayedAndroidKey = {
10841 key, keyCode,
10842 // Only run the key handler when no changes are detected if
10843 // this isn't coming right after another change, in which case
10844 // it is probably part of a weird chain of updates, and should
10845 // be ignored if it returns the DOM to its previous state.
10846 force: this.lastChange < Date.now() - 50 || !!((_a = this.delayedAndroidKey) === null || _a === void 0 ? void 0 : _a.force)
10847 };
10848 }
10849 clearDelayedAndroidKey() {
10850 this.win.cancelAnimationFrame(this.flushingAndroidKey);
10851 this.delayedAndroidKey = null;
10852 this.flushingAndroidKey = -1;
10853 }
10854 flushSoon() {
10855 if (this.delayedFlush < 0)
10856 this.delayedFlush = this.view.win.requestAnimationFrame(() => { this.delayedFlush = -1; this.flush(); });
10857 }
10858 forceFlush() {
10859 if (this.delayedFlush >= 0) {
10860 this.view.win.cancelAnimationFrame(this.delayedFlush);
10861 this.delayedFlush = -1;
10862 }
10863 this.flush();
10864 }
10865 pendingRecords() {
10866 for (let mut of this.observer.takeRecords())
10867 this.queue.push(mut);
10868 return this.queue;
10869 }
10870 processRecords() {
10871 let records = this.pendingRecords();
10872 if (records.length)
10873 this.queue = [];
10874 let from = -1, to = -1, typeOver = false;
10875 for (let record of records) {
10876 let range = this.readMutation(record);
10877 if (!range)
10878 continue;
10879 if (range.typeOver)
10880 typeOver = true;
10881 if (from == -1) {
10882 ({ from, to } = range);
10883 }
10884 else {
10885 from = Math.min(range.from, from);
10886 to = Math.max(range.to, to);
10887 }
10888 }
10889 return { from, to, typeOver };
10890 }
10891 readChange() {
10892 let { from, to, typeOver } = this.processRecords();
10893 let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
10894 if (from < 0 && !newSel)
10895 return null;
10896 if (from > -1)
10897 this.lastChange = Date.now();
10898 this.view.inputState.lastFocusTime = 0;
10899 this.selectionChanged = false;
10900 let change = new DOMChange(this.view, from, to, typeOver);
10901 this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null };
10902 return change;
10903 }
10904 // Apply pending changes, if any
10905 flush(readSelection = true) {
10906 // Completely hold off flushing when pending keys are set—the code
10907 // managing those will make sure processRecords is called and the
10908 // view is resynchronized after
10909 if (this.delayedFlush >= 0 || this.delayedAndroidKey)
10910 return false;
10911 if (readSelection)
10912 this.readSelectionRange();
10913 let domChange = this.readChange();
10914 if (!domChange) {
10915 this.view.requestMeasure();
10916 return false;
10917 }
10918 let startState = this.view.state;
10919 let handled = applyDOMChange(this.view, domChange);
10920 // The view wasn't updated
10921 if (this.view.state == startState)
10922 this.view.update([]);
10923 return handled;
10924 }
10925 readMutation(rec) {
10926 let cView = this.view.docView.nearest(rec.target);
10927 if (!cView || cView.ignoreMutation(rec))
10928 return null;
10929 cView.markDirty(rec.type == "attributes");
10930 if (rec.type == "attributes")
10931 cView.flags |= 4 /* ViewFlag.AttrsDirty */;
10932 if (rec.type == "childList") {
10933 let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
10934 let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
10935 return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
10936 to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };
10937 }
10938 else if (rec.type == "characterData") {
10939 return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
10940 }
10941 else {
10942 return null;
10943 }
10944 }
10945 setWindow(win) {
10946 if (win != this.win) {
10947 this.removeWindowListeners(this.win);
10948 this.win = win;
10949 this.addWindowListeners(this.win);
10950 }
10951 }
10952 addWindowListeners(win) {
10953 win.addEventListener("resize", this.onResize);
10954 win.addEventListener("beforeprint", this.onPrint);
10955 win.addEventListener("scroll", this.onScroll);
10956 win.document.addEventListener("selectionchange", this.onSelectionChange);
10957 }
10958 removeWindowListeners(win) {
10959 win.removeEventListener("scroll", this.onScroll);
10960 win.removeEventListener("resize", this.onResize);
10961 win.removeEventListener("beforeprint", this.onPrint);
10962 win.document.removeEventListener("selectionchange", this.onSelectionChange);
10963 }
10964 destroy() {
10965 var _a, _b, _c;
10966 this.stop();
10967 (_a = this.intersection) === null || _a === void 0 ? void 0 : _a.disconnect();
10968 (_b = this.gapIntersection) === null || _b === void 0 ? void 0 : _b.disconnect();
10969 (_c = this.resizeScroll) === null || _c === void 0 ? void 0 : _c.disconnect();
10970 for (let dom of this.scrollTargets)
10971 dom.removeEventListener("scroll", this.onScroll);
10972 this.removeWindowListeners(this.win);
10973 clearTimeout(this.parentCheck);
10974 clearTimeout(this.resizeTimeout);
10975 this.win.cancelAnimationFrame(this.delayedFlush);
10976 this.win.cancelAnimationFrame(this.flushingAndroidKey);
10977 }
10978 }
10979 function findChild(cView, dom, dir) {
10980 while (dom) {
10981 let curView = ContentView.get(dom);
10982 if (curView && curView.parent == cView)
10983 return curView;
10984 let parent = dom.parentNode;
10985 dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
10986 }
10987 return null;
10988 }
10989 // Used to work around a Safari Selection/shadow DOM bug (#414)
10990 function safariSelectionRangeHack(view) {
10991 let found = null;
10992 // Because Safari (at least in 2018-2021) doesn't provide regular
10993 // access to the selection inside a shadowroot, we have to perform a
10994 // ridiculous hack to get at it—using `execCommand` to trigger a
10995 // `beforeInput` event so that we can read the target range from the
10996 // event.
10997 function read(event) {
10998 event.preventDefault();
10999 event.stopImmediatePropagation();
11000 found = event.getTargetRanges()[0];
11001 }
11002 view.contentDOM.addEventListener("beforeinput", read, true);
11003 view.dom.ownerDocument.execCommand("indent");
11004 view.contentDOM.removeEventListener("beforeinput", read, true);
11005 if (!found)
11006 return null;
11007 let anchorNode = found.startContainer, anchorOffset = found.startOffset;
11008 let focusNode = found.endContainer, focusOffset = found.endOffset;
11009 let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
11010 // Since such a range doesn't distinguish between anchor and head,
11011 // use a heuristic that flips it around if its end matches the
11012 // current anchor.
11013 if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset))
11014 [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
11015 return { anchorNode, anchorOffset, focusNode, focusOffset };
11016 }
11017
11018 // The editor's update state machine looks something like this:
11019 //
11020 // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle
11021 // ↑ ↓
11022 // Updating (measure)
11023 //
11024 // The difference between 'Idle' and 'Idle (unchecked)' lies in
11025 // whether a layout check has been scheduled. A regular update through
11026 // the `update` method updates the DOM in a write-only fashion, and
11027 // relies on a check (scheduled with `requestAnimationFrame`) to make
11028 // sure everything is where it should be and the viewport covers the
11029 // visible code. That check continues to measure and then optionally
11030 // update until it reaches a coherent state.
11031 /**
11032 An editor view represents the editor's user interface. It holds
11033 the editable DOM surface, and possibly other elements such as the
11034 line number gutter. It handles events and dispatches state
11035 transactions for editing actions.
11036 */
11037 class EditorView {
11038 /**
11039 The current editor state.
11040 */
11041 get state() { return this.viewState.state; }
11042 /**
11043 To be able to display large documents without consuming too much
11044 memory or overloading the browser, CodeMirror only draws the
11045 code that is visible (plus a margin around it) to the DOM. This
11046 property tells you the extent of the current drawn viewport, in
11047 document positions.
11048 */
11049 get viewport() { return this.viewState.viewport; }
11050 /**
11051 When there are, for example, large collapsed ranges in the
11052 viewport, its size can be a lot bigger than the actual visible
11053 content. Thus, if you are doing something like styling the
11054 content in the viewport, it is preferable to only do so for
11055 these ranges, which are the subset of the viewport that is
11056 actually drawn.
11057 */
11058 get visibleRanges() { return this.viewState.visibleRanges; }
11059 /**
11060 Returns false when the editor is entirely scrolled out of view
11061 or otherwise hidden.
11062 */
11063 get inView() { return this.viewState.inView; }
11064 /**
11065 Indicates whether the user is currently composing text via
11066 [IME](https://en.wikipedia.org/wiki/Input_method), and at least
11067 one change has been made in the current composition.
11068 */
11069 get composing() { return this.inputState.composing > 0; }
11070 /**
11071 Indicates whether the user is currently in composing state. Note
11072 that on some platforms, like Android, this will be the case a
11073 lot, since just putting the cursor on a word starts a
11074 composition there.
11075 */
11076 get compositionStarted() { return this.inputState.composing >= 0; }
11077 /**
11078 The document or shadow root that the view lives in.
11079 */
11080 get root() { return this._root; }
11081 /**
11082 @internal
11083 */
11084 get win() { return this.dom.ownerDocument.defaultView || window; }
11085 /**
11086 Construct a new view. You'll want to either provide a `parent`
11087 option, or put `view.dom` into your document after creating a
11088 view, so that the user can see the editor.
11089 */
11090 constructor(config = {}) {
11091 this.plugins = [];
11092 this.pluginMap = new Map;
11093 this.editorAttrs = {};
11094 this.contentAttrs = {};
11095 this.bidiCache = [];
11096 this.destroyed = false;
11097 /**
11098 @internal
11099 */
11100 this.updateState = 2 /* UpdateState.Updating */;
11101 /**
11102 @internal
11103 */
11104 this.measureScheduled = -1;
11105 /**
11106 @internal
11107 */
11108 this.measureRequests = [];
11109 this.contentDOM = document.createElement("div");
11110 this.scrollDOM = document.createElement("div");
11111 this.scrollDOM.tabIndex = -1;
11112 this.scrollDOM.className = "cm-scroller";
11113 this.scrollDOM.appendChild(this.contentDOM);
11114 this.announceDOM = document.createElement("div");
11115 this.announceDOM.className = "cm-announced";
11116 this.announceDOM.setAttribute("aria-live", "polite");
11117 this.dom = document.createElement("div");
11118 this.dom.appendChild(this.announceDOM);
11119 this.dom.appendChild(this.scrollDOM);
11120 let { dispatch } = config;
11121 this.dispatchTransactions = config.dispatchTransactions ||
11122 (dispatch && ((trs) => trs.forEach(tr => dispatch(tr, this)))) ||
11123 ((trs) => this.update(trs));
11124 this.dispatch = this.dispatch.bind(this);
11125 this._root = (config.root || getRoot(config.parent) || document);
11126 this.viewState = new ViewState(config.state || EditorState.create(config));
11127 if (config.scrollTo && config.scrollTo.is(scrollIntoView))
11128 this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state);
11129 this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));
11130 for (let plugin of this.plugins)
11131 plugin.update(this);
11132 this.observer = new DOMObserver(this);
11133 this.inputState = new InputState(this);
11134 this.inputState.ensureHandlers(this.plugins);
11135 this.docView = new DocView(this);
11136 this.mountStyles();
11137 this.updateAttrs();
11138 this.updateState = 0 /* UpdateState.Idle */;
11139 this.requestMeasure();
11140 if (config.parent)
11141 config.parent.appendChild(this.dom);
11142 }
11143 dispatch(...input) {
11144 let trs = input.length == 1 && input[0] instanceof Transaction ? input
11145 : input.length == 1 && Array.isArray(input[0]) ? input[0]
11146 : [this.state.update(...input)];
11147 this.dispatchTransactions(trs, this);
11148 }
11149 /**
11150 Update the view for the given array of transactions. This will
11151 update the visible document and selection to match the state
11152 produced by the transactions, and notify view plugins of the
11153 change. You should usually call
11154 [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
11155 as a primitive.
11156 */
11157 update(transactions) {
11158 if (this.updateState != 0 /* UpdateState.Idle */)
11159 throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
11160 let redrawn = false, attrsChanged = false, update;
11161 let state = this.state;
11162 for (let tr of transactions) {
11163 if (tr.startState != state)
11164 throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
11165 state = tr.state;
11166 }
11167 if (this.destroyed) {
11168 this.viewState.state = state;
11169 return;
11170 }
11171 let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null;
11172 if (transactions.some(tr => tr.annotation(isFocusChange))) {
11173 this.inputState.notifiedFocused = focus;
11174 // If a focus-change transaction is being dispatched, set this update flag.
11175 focusFlag = 1 /* UpdateFlag.Focus */;
11176 }
11177 else if (focus != this.inputState.notifiedFocused) {
11178 this.inputState.notifiedFocused = focus;
11179 // Schedule a separate focus transaction if necessary, otherwise
11180 // add a flag to this update
11181 dispatchFocus = focusChangeTransaction(state, focus);
11182 if (!dispatchFocus)
11183 focusFlag = 1 /* UpdateFlag.Focus */;
11184 }
11185 // If there was a pending DOM change, eagerly read it and try to
11186 // apply it after the given transactions.
11187 let pendingKey = this.observer.delayedAndroidKey, domChange = null;
11188 if (pendingKey) {
11189 this.observer.clearDelayedAndroidKey();
11190 domChange = this.observer.readChange();
11191 // Only try to apply DOM changes if the transactions didn't
11192 // change the doc or selection.
11193 if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection))
11194 domChange = null;
11195 }
11196 else {
11197 this.observer.clear();
11198 }
11199 // When the phrases change, redraw the editor
11200 if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases))
11201 return this.setState(state);
11202 update = ViewUpdate.create(this, state, transactions);
11203 update.flags |= focusFlag;
11204 let scrollTarget = this.viewState.scrollTarget;
11205 try {
11206 this.updateState = 2 /* UpdateState.Updating */;
11207 for (let tr of transactions) {
11208 if (scrollTarget)
11209 scrollTarget = scrollTarget.map(tr.changes);
11210 if (tr.scrollIntoView) {
11211 let { main } = tr.state.selection;
11212 scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
11213 }
11214 for (let e of tr.effects)
11215 if (e.is(scrollIntoView))
11216 scrollTarget = e.value.clip(this.state);
11217 }
11218 this.viewState.update(update, scrollTarget);
11219 this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
11220 if (!update.empty) {
11221 this.updatePlugins(update);
11222 this.inputState.update(update);
11223 }
11224 redrawn = this.docView.update(update);
11225 if (this.state.facet(styleModule) != this.styleModules)
11226 this.mountStyles();
11227 attrsChanged = this.updateAttrs();
11228 this.showAnnouncements(transactions);
11229 this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
11230 }
11231 finally {
11232 this.updateState = 0 /* UpdateState.Idle */;
11233 }
11234 if (update.startState.facet(theme) != update.state.facet(theme))
11235 this.viewState.mustMeasureContent = true;
11236 if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent)
11237 this.requestMeasure();
11238 if (!update.empty)
11239 for (let listener of this.state.facet(updateListener)) {
11240 try {
11241 listener(update);
11242 }
11243 catch (e) {
11244 logException(this.state, e, "update listener");
11245 }
11246 }
11247 if (dispatchFocus || domChange)
11248 Promise.resolve().then(() => {
11249 if (dispatchFocus && this.state == dispatchFocus.startState)
11250 this.dispatch(dispatchFocus);
11251 if (domChange) {
11252 if (!applyDOMChange(this, domChange) && pendingKey.force)
11253 dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
11254 }
11255 });
11256 }
11257 /**
11258 Reset the view to the given state. (This will cause the entire
11259 document to be redrawn and all view plugins to be reinitialized,
11260 so you should probably only use it when the new state isn't
11261 derived from the old state. Otherwise, use
11262 [`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
11263 */
11264 setState(newState) {
11265 if (this.updateState != 0 /* UpdateState.Idle */)
11266 throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
11267 if (this.destroyed) {
11268 this.viewState.state = newState;
11269 return;
11270 }
11271 this.updateState = 2 /* UpdateState.Updating */;
11272 let hadFocus = this.hasFocus;
11273 try {
11274 for (let plugin of this.plugins)
11275 plugin.destroy(this);
11276 this.viewState = new ViewState(newState);
11277 this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));
11278 this.pluginMap.clear();
11279 for (let plugin of this.plugins)
11280 plugin.update(this);
11281 this.docView.destroy();
11282 this.docView = new DocView(this);
11283 this.inputState.ensureHandlers(this.plugins);
11284 this.mountStyles();
11285 this.updateAttrs();
11286 this.bidiCache = [];
11287 }
11288 finally {
11289 this.updateState = 0 /* UpdateState.Idle */;
11290 }
11291 if (hadFocus)
11292 this.focus();
11293 this.requestMeasure();
11294 }
11295 updatePlugins(update) {
11296 let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
11297 if (prevSpecs != specs) {
11298 let newPlugins = [];
11299 for (let spec of specs) {
11300 let found = prevSpecs.indexOf(spec);
11301 if (found < 0) {
11302 newPlugins.push(new PluginInstance(spec));
11303 }
11304 else {
11305 let plugin = this.plugins[found];
11306 plugin.mustUpdate = update;
11307 newPlugins.push(plugin);
11308 }
11309 }
11310 for (let plugin of this.plugins)
11311 if (plugin.mustUpdate != update)
11312 plugin.destroy(this);
11313 this.plugins = newPlugins;
11314 this.pluginMap.clear();
11315 }
11316 else {
11317 for (let p of this.plugins)
11318 p.mustUpdate = update;
11319 }
11320 for (let i = 0; i < this.plugins.length; i++)
11321 this.plugins[i].update(this);
11322 if (prevSpecs != specs)
11323 this.inputState.ensureHandlers(this.plugins);
11324 }
11325 /**
11326 @internal
11327 */
11328 measure(flush = true) {
11329 if (this.destroyed)
11330 return;
11331 if (this.measureScheduled > -1)
11332 this.win.cancelAnimationFrame(this.measureScheduled);
11333 if (this.observer.delayedAndroidKey) {
11334 this.measureScheduled = -1;
11335 this.requestMeasure();
11336 return;
11337 }
11338 this.measureScheduled = 0; // Prevent requestMeasure calls from scheduling another animation frame
11339 if (flush)
11340 this.observer.forceFlush();
11341 let updated = null;
11342 let sDOM = this.scrollDOM, scrollTop = sDOM.scrollTop * this.scaleY;
11343 let { scrollAnchorPos, scrollAnchorHeight } = this.viewState;
11344 if (Math.abs(scrollTop - this.viewState.scrollTop) > 1)
11345 scrollAnchorHeight = -1;
11346 this.viewState.scrollAnchorHeight = -1;
11347 try {
11348 for (let i = 0;; i++) {
11349 if (scrollAnchorHeight < 0) {
11350 if (isScrolledToBottom(sDOM)) {
11351 scrollAnchorPos = -1;
11352 scrollAnchorHeight = this.viewState.heightMap.height;
11353 }
11354 else {
11355 let block = this.viewState.scrollAnchorAt(scrollTop);
11356 scrollAnchorPos = block.from;
11357 scrollAnchorHeight = block.top;
11358 }
11359 }
11360 this.updateState = 1 /* UpdateState.Measuring */;
11361 let changed = this.viewState.measure(this);
11362 if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null)
11363 break;
11364 if (i > 5) {
11365 console.warn(this.measureRequests.length
11366 ? "Measure loop restarted more than 5 times"
11367 : "Viewport failed to stabilize");
11368 break;
11369 }
11370 let measuring = [];
11371 // Only run measure requests in this cycle when the viewport didn't change
11372 if (!(changed & 4 /* UpdateFlag.Viewport */))
11373 [this.measureRequests, measuring] = [measuring, this.measureRequests];
11374 let measured = measuring.map(m => {
11375 try {
11376 return m.read(this);
11377 }
11378 catch (e) {
11379 logException(this.state, e);
11380 return BadMeasure;
11381 }
11382 });
11383 let update = ViewUpdate.create(this, this.state, []), redrawn = false;
11384 update.flags |= changed;
11385 if (!updated)
11386 updated = update;
11387 else
11388 updated.flags |= changed;
11389 this.updateState = 2 /* UpdateState.Updating */;
11390 if (!update.empty) {
11391 this.updatePlugins(update);
11392 this.inputState.update(update);
11393 this.updateAttrs();
11394 redrawn = this.docView.update(update);
11395 }
11396 for (let i = 0; i < measuring.length; i++)
11397 if (measured[i] != BadMeasure) {
11398 try {
11399 let m = measuring[i];
11400 if (m.write)
11401 m.write(measured[i], this);
11402 }
11403 catch (e) {
11404 logException(this.state, e);
11405 }
11406 }
11407 if (redrawn)
11408 this.docView.updateSelection(true);
11409 if (!update.viewportChanged && this.measureRequests.length == 0) {
11410 if (this.viewState.editorHeight) {
11411 if (this.viewState.scrollTarget) {
11412 this.docView.scrollIntoView(this.viewState.scrollTarget);
11413 this.viewState.scrollTarget = null;
11414 scrollAnchorHeight = -1;
11415 continue;
11416 }
11417 else {
11418 let newAnchorHeight = scrollAnchorPos < 0 ? this.viewState.heightMap.height :
11419 this.viewState.lineBlockAt(scrollAnchorPos).top;
11420 let diff = newAnchorHeight - scrollAnchorHeight;
11421 if (diff > 1 || diff < -1) {
11422 scrollTop = scrollTop + diff;
11423 sDOM.scrollTop = scrollTop / this.scaleY;
11424 scrollAnchorHeight = -1;
11425 continue;
11426 }
11427 }
11428 }
11429 break;
11430 }
11431 }
11432 }
11433 finally {
11434 this.updateState = 0 /* UpdateState.Idle */;
11435 this.measureScheduled = -1;
11436 }
11437 if (updated && !updated.empty)
11438 for (let listener of this.state.facet(updateListener))
11439 listener(updated);
11440 }
11441 /**
11442 Get the CSS classes for the currently active editor themes.
11443 */
11444 get themeClasses() {
11445 return baseThemeID + " " +
11446 (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " +
11447 this.state.facet(theme);
11448 }
11449 updateAttrs() {
11450 let editorAttrs = attrsFromFacet(this, editorAttributes, {
11451 class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
11452 });
11453 let contentAttrs = {
11454 spellcheck: "false",
11455 autocorrect: "off",
11456 autocapitalize: "off",
11457 translate: "no",
11458 contenteditable: !this.state.facet(editable) ? "false" : "true",
11459 class: "cm-content",
11460 style: `${browser.tabSize}: ${this.state.tabSize}`,
11461 role: "textbox",
11462 "aria-multiline": "true"
11463 };
11464 if (this.state.readOnly)
11465 contentAttrs["aria-readonly"] = "true";
11466 attrsFromFacet(this, contentAttributes, contentAttrs);
11467 let changed = this.observer.ignore(() => {
11468 let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
11469 let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
11470 return changedContent || changedEditor;
11471 });
11472 this.editorAttrs = editorAttrs;
11473 this.contentAttrs = contentAttrs;
11474 return changed;
11475 }
11476 showAnnouncements(trs) {
11477 let first = true;
11478 for (let tr of trs)
11479 for (let effect of tr.effects)
11480 if (effect.is(EditorView.announce)) {
11481 if (first)
11482 this.announceDOM.textContent = "";
11483 first = false;
11484 let div = this.announceDOM.appendChild(document.createElement("div"));
11485 div.textContent = effect.value;
11486 }
11487 }
11488 mountStyles() {
11489 this.styleModules = this.state.facet(styleModule);
11490 let nonce = this.state.facet(EditorView.cspNonce);
11491 StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$2).reverse(), nonce ? { nonce } : undefined);
11492 }
11493 readMeasured() {
11494 if (this.updateState == 2 /* UpdateState.Updating */)
11495 throw new Error("Reading the editor layout isn't allowed during an update");
11496 if (this.updateState == 0 /* UpdateState.Idle */ && this.measureScheduled > -1)
11497 this.measure(false);
11498 }
11499 /**
11500 Schedule a layout measurement, optionally providing callbacks to
11501 do custom DOM measuring followed by a DOM write phase. Using
11502 this is preferable reading DOM layout directly from, for
11503 example, an event handler, because it'll make sure measuring and
11504 drawing done by other components is synchronized, avoiding
11505 unnecessary DOM layout computations.
11506 */
11507 requestMeasure(request) {
11508 if (this.measureScheduled < 0)
11509 this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
11510 if (request) {
11511 if (this.measureRequests.indexOf(request) > -1)
11512 return;
11513 if (request.key != null)
11514 for (let i = 0; i < this.measureRequests.length; i++) {
11515 if (this.measureRequests[i].key === request.key) {
11516 this.measureRequests[i] = request;
11517 return;
11518 }
11519 }
11520 this.measureRequests.push(request);
11521 }
11522 }
11523 /**
11524 Get the value of a specific plugin, if present. Note that
11525 plugins that crash can be dropped from a view, so even when you
11526 know you registered a given plugin, it is recommended to check
11527 the return value of this method.
11528 */
11529 plugin(plugin) {
11530 let known = this.pluginMap.get(plugin);
11531 if (known === undefined || known && known.spec != plugin)
11532 this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);
11533 return known && known.update(this).value;
11534 }
11535 /**
11536 The top position of the document, in screen coordinates. This
11537 may be negative when the editor is scrolled down. Points
11538 directly to the top of the first line, not above the padding.
11539 */
11540 get documentTop() {
11541 return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
11542 }
11543 /**
11544 Reports the padding above and below the document.
11545 */
11546 get documentPadding() {
11547 return { top: this.viewState.paddingTop, bottom: this.viewState.paddingBottom };
11548 }
11549 /**
11550 If the editor is transformed with CSS, this provides the scale
11551 along the X axis. Otherwise, it will just be 1. Note that
11552 transforms other than translation and scaling are not supported.
11553 */
11554 get scaleX() { return this.viewState.scaleX; }
11555 /**
11556 Provide the CSS transformed scale along the Y axis.
11557 */
11558 get scaleY() { return this.viewState.scaleY; }
11559 /**
11560 Find the text line or block widget at the given vertical
11561 position (which is interpreted as relative to the [top of the
11562 document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
11563 */
11564 elementAtHeight(height) {
11565 this.readMeasured();
11566 return this.viewState.elementAtHeight(height);
11567 }
11568 /**
11569 Find the line block (see
11570 [`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
11571 height, again interpreted relative to the [top of the
11572 document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
11573 */
11574 lineBlockAtHeight(height) {
11575 this.readMeasured();
11576 return this.viewState.lineBlockAtHeight(height);
11577 }
11578 /**
11579 Get the extent and vertical position of all [line
11580 blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
11581 are relative to the [top of the
11582 document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
11583 */
11584 get viewportLineBlocks() {
11585 return this.viewState.viewportLines;
11586 }
11587 /**
11588 Find the line block around the given document position. A line
11589 block is a range delimited on both sides by either a
11590 non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the
11591 start/end of the document. It will usually just hold a line of
11592 text, but may be broken into multiple textblocks by block
11593 widgets.
11594 */
11595 lineBlockAt(pos) {
11596 return this.viewState.lineBlockAt(pos);
11597 }
11598 /**
11599 The editor's total content height.
11600 */
11601 get contentHeight() {
11602 return this.viewState.contentHeight;
11603 }
11604 /**
11605 Move a cursor position by [grapheme
11606 cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
11607 the motion is away from the line start, or towards it. In
11608 bidirectional text, the line is traversed in visual order, using
11609 the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
11610 When the start position was the last one on the line, the
11611 returned position will be across the line break. If there is no
11612 further line, the original position is returned.
11613
11614 By default, this method moves over a single cluster. The
11615 optional `by` argument can be used to move across more. It will
11616 be called with the first cluster as argument, and should return
11617 a predicate that determines, for each subsequent cluster,
11618 whether it should also be moved over.
11619 */
11620 moveByChar(start, forward, by) {
11621 return skipAtoms(this, start, moveByChar(this, start, forward, by));
11622 }
11623 /**
11624 Move a cursor position across the next group of either
11625 [letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
11626 non-whitespace characters.
11627 */
11628 moveByGroup(start, forward) {
11629 return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));
11630 }
11631 /**
11632 Move to the next line boundary in the given direction. If
11633 `includeWrap` is true, line wrapping is on, and there is a
11634 further wrap point on the current line, the wrap point will be
11635 returned. Otherwise this function will return the start or end
11636 of the line.
11637 */
11638 moveToLineBoundary(start, forward, includeWrap = true) {
11639 return moveToLineBoundary(this, start, forward, includeWrap);
11640 }
11641 /**
11642 Move a cursor position vertically. When `distance` isn't given,
11643 it defaults to moving to the next line (including wrapped
11644 lines). Otherwise, `distance` should provide a positive distance
11645 in pixels.
11646
11647 When `start` has a
11648 [`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
11649 motion will use that as a target horizontal position. Otherwise,
11650 the cursor's own horizontal position is used. The returned
11651 cursor will have its goal column set to whichever column was
11652 used.
11653 */
11654 moveVertically(start, forward, distance) {
11655 return skipAtoms(this, start, moveVertically(this, start, forward, distance));
11656 }
11657 /**
11658 Find the DOM parent node and offset (child offset if `node` is
11659 an element, character offset when it is a text node) at the
11660 given document position.
11661
11662 Note that for positions that aren't currently in
11663 `visibleRanges`, the resulting DOM position isn't necessarily
11664 meaningful (it may just point before or after a placeholder
11665 element).
11666 */
11667 domAtPos(pos) {
11668 return this.docView.domAtPos(pos);
11669 }
11670 /**
11671 Find the document position at the given DOM node. Can be useful
11672 for associating positions with DOM events. Will raise an error
11673 when `node` isn't part of the editor content.
11674 */
11675 posAtDOM(node, offset = 0) {
11676 return this.docView.posFromDOM(node, offset);
11677 }
11678 posAtCoords(coords, precise = true) {
11679 this.readMeasured();
11680 return posAtCoords(this, coords, precise);
11681 }
11682 /**
11683 Get the screen coordinates at the given document position.
11684 `side` determines whether the coordinates are based on the
11685 element before (-1) or after (1) the position (if no element is
11686 available on the given side, the method will transparently use
11687 another strategy to get reasonable coordinates).
11688 */
11689 coordsAtPos(pos, side = 1) {
11690 this.readMeasured();
11691 let rect = this.docView.coordsAt(pos, side);
11692 if (!rect || rect.left == rect.right)
11693 return rect;
11694 let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
11695 let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
11696 return flattenRect(rect, (span.dir == exports.Direction.LTR) == (side > 0));
11697 }
11698 /**
11699 Return the rectangle around a given character. If `pos` does not
11700 point in front of a character that is in the viewport and
11701 rendered (i.e. not replaced, not a line break), this will return
11702 null. For space characters that are a line wrap point, this will
11703 return the position before the line break.
11704 */
11705 coordsForChar(pos) {
11706 this.readMeasured();
11707 return this.docView.coordsForChar(pos);
11708 }
11709 /**
11710 The default width of a character in the editor. May not
11711 accurately reflect the width of all characters (given variable
11712 width fonts or styling of invididual ranges).
11713 */
11714 get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }
11715 /**
11716 The default height of a line in the editor. May not be accurate
11717 for all lines.
11718 */
11719 get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }
11720 /**
11721 The text direction
11722 ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
11723 CSS property) of the editor's content element.
11724 */
11725 get textDirection() { return this.viewState.defaultTextDirection; }
11726 /**
11727 Find the text direction of the block at the given position, as
11728 assigned by CSS. If
11729 [`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
11730 isn't enabled, or the given position is outside of the viewport,
11731 this will always return the same as
11732 [`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
11733 this may trigger a DOM layout.
11734 */
11735 textDirectionAt(pos) {
11736 let perLine = this.state.facet(perLineTextDirection);
11737 if (!perLine || pos < this.viewport.from || pos > this.viewport.to)
11738 return this.textDirection;
11739 this.readMeasured();
11740 return this.docView.textDirectionAt(pos);
11741 }
11742 /**
11743 Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
11744 (as determined by the
11745 [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
11746 CSS property of its content element).
11747 */
11748 get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }
11749 /**
11750 Returns the bidirectional text structure of the given line
11751 (which should be in the current document) as an array of span
11752 objects. The order of these spans matches the [text
11753 direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
11754 left-to-right, the leftmost spans come first, otherwise the
11755 rightmost spans come first.
11756 */
11757 bidiSpans(line) {
11758 if (line.length > MaxBidiLine)
11759 return trivialOrder(line.length);
11760 let dir = this.textDirectionAt(line.from), isolates;
11761 for (let entry of this.bidiCache) {
11762 if (entry.from == line.from && entry.dir == dir &&
11763 (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line.from, line.to))))
11764 return entry.order;
11765 }
11766 if (!isolates)
11767 isolates = getIsolatedRanges(this, line.from, line.to);
11768 let order = computeOrder(line.text, dir, isolates);
11769 this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
11770 return order;
11771 }
11772 /**
11773 Check whether the editor has focus.
11774 */
11775 get hasFocus() {
11776 var _a;
11777 // Safari return false for hasFocus when the context menu is open
11778 // or closing, which leads us to ignore selection changes from the
11779 // context menu because it looks like the editor isn't focused.
11780 // This kludges around that.
11781 return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a = this.inputState) === null || _a === void 0 ? void 0 : _a.lastContextMenu) > Date.now() - 3e4) &&
11782 this.root.activeElement == this.contentDOM;
11783 }
11784 /**
11785 Put focus on the editor.
11786 */
11787 focus() {
11788 this.observer.ignore(() => {
11789 focusPreventScroll(this.contentDOM);
11790 this.docView.updateSelection();
11791 });
11792 }
11793 /**
11794 Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
11795 necessary when moving the editor's existing DOM to a new window or shadow root.
11796 */
11797 setRoot(root) {
11798 if (this._root != root) {
11799 this._root = root;
11800 this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
11801 this.mountStyles();
11802 }
11803 }
11804 /**
11805 Clean up this editor view, removing its element from the
11806 document, unregistering event handlers, and notifying
11807 plugins. The view instance can no longer be used after
11808 calling this.
11809 */
11810 destroy() {
11811 for (let plugin of this.plugins)
11812 plugin.destroy(this);
11813 this.plugins = [];
11814 this.inputState.destroy();
11815 this.docView.destroy();
11816 this.dom.remove();
11817 this.observer.destroy();
11818 if (this.measureScheduled > -1)
11819 this.win.cancelAnimationFrame(this.measureScheduled);
11820 this.destroyed = true;
11821 }
11822 /**
11823 Returns an effect that can be
11824 [added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
11825 cause it to scroll the given position or range into view.
11826 */
11827 static scrollIntoView(pos, options = {}) {
11828 return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
11829 }
11830 /**
11831 Return an effect that resets the editor to its current (at the
11832 time this method was called) scroll position. Note that this
11833 only affects the editor's own scrollable element, not parents.
11834 See also
11835 [`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
11836
11837 The effect should be used with a document identical to the one
11838 it was created for. Failing to do so is not an error, but may
11839 not scroll to the expected position. You can
11840 [map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
11841 */
11842 scrollSnapshot() {
11843 let { scrollTop, scrollLeft } = this.scrollDOM;
11844 let ref = this.viewState.scrollAnchorAt(scrollTop);
11845 return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, true));
11846 }
11847 /**
11848 Returns an extension that can be used to add DOM event handlers.
11849 The value should be an object mapping event names to handler
11850 functions. For any given event, such functions are ordered by
11851 extension precedence, and the first handler to return true will
11852 be assumed to have handled that event, and no other handlers or
11853 built-in behavior will be activated for it. These are registered
11854 on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
11855 for `scroll` handlers, which will be called any time the
11856 editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
11857 its parent nodes is scrolled.
11858 */
11859 static domEventHandlers(handlers) {
11860 return ViewPlugin.define(() => ({}), { eventHandlers: handlers });
11861 }
11862 /**
11863 Create an extension that registers DOM event observers. Contrary
11864 to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
11865 observers can't be prevented from running by a higher-precedence
11866 handler returning true. They also don't prevent other handlers
11867 and observers from running when they return true, and should not
11868 call `preventDefault`.
11869 */
11870 static domEventObservers(observers) {
11871 return ViewPlugin.define(() => ({}), { eventObservers: observers });
11872 }
11873 /**
11874 Create a theme extension. The first argument can be a
11875 [`style-mod`](https://github.com/marijnh/style-mod#documentation)
11876 style spec providing the styles for the theme. These will be
11877 prefixed with a generated class for the style.
11878
11879 Because the selectors will be prefixed with a scope class, rule
11880 that directly match the editor's [wrapper
11881 element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
11882 added—need to be explicitly differentiated by adding an `&` to
11883 the selector for that element—for example
11884 `&.cm-focused`.
11885
11886 When `dark` is set to true, the theme will be marked as dark,
11887 which will cause the `&dark` rules from [base
11888 themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
11889 `&light` when a light theme is active).
11890 */
11891 static theme(spec, options) {
11892 let prefix = StyleModule.newName();
11893 let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
11894 if (options && options.dark)
11895 result.push(darkTheme.of(true));
11896 return result;
11897 }
11898 /**
11899 Create an extension that adds styles to the base theme. Like
11900 with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
11901 place of the editor wrapper element when directly targeting
11902 that. You can also use `&dark` or `&light` instead to only
11903 target editors with a dark or light theme.
11904 */
11905 static baseTheme(spec) {
11906 return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
11907 }
11908 /**
11909 Retrieve an editor view instance from the view's DOM
11910 representation.
11911 */
11912 static findFromDOM(dom) {
11913 var _a;
11914 let content = dom.querySelector(".cm-content");
11915 let cView = content && ContentView.get(content) || ContentView.get(dom);
11916 return ((_a = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a === void 0 ? void 0 : _a.view) || null;
11917 }
11918 }
11919 /**
11920 Facet to add a [style
11921 module](https://github.com/marijnh/style-mod#documentation) to
11922 an editor view. The view will ensure that the module is
11923 mounted in its [document
11924 root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
11925 */
11926 EditorView.styleModule = styleModule;
11927 /**
11928 An input handler can override the way changes to the editable
11929 DOM content are handled. Handlers are passed the document
11930 positions between which the change was found, and the new
11931 content. When one returns true, no further input handlers are
11932 called and the default behavior is prevented.
11933
11934 The `insert` argument can be used to get the default transaction
11935 that would be applied for this input. This can be useful when
11936 dispatching the custom behavior as a separate transaction.
11937 */
11938 EditorView.inputHandler = inputHandler;
11939 /**
11940 This facet can be used to provide functions that create effects
11941 to be dispatched when the editor's focus state changes.
11942 */
11943 EditorView.focusChangeEffect = focusChangeEffect;
11944 /**
11945 By default, the editor assumes all its content has the same
11946 [text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
11947 value to make it read the text direction of every (rendered)
11948 line separately.
11949 */
11950 EditorView.perLineTextDirection = perLineTextDirection;
11951 /**
11952 Allows you to provide a function that should be called when the
11953 library catches an exception from an extension (mostly from view
11954 plugins, but may be used by other extensions to route exceptions
11955 from user-code-provided callbacks). This is mostly useful for
11956 debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
11957 */
11958 EditorView.exceptionSink = exceptionSink;
11959 /**
11960 A facet that can be used to register a function to be called
11961 every time the view updates.
11962 */
11963 EditorView.updateListener = updateListener;
11964 /**
11965 Facet that controls whether the editor content DOM is editable.
11966 When its highest-precedence value is `false`, the element will
11967 not have its `contenteditable` attribute set. (Note that this
11968 doesn't affect API calls that change the editor content, even
11969 when those are bound to keys or buttons. See the
11970 [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
11971 */
11972 EditorView.editable = editable;
11973 /**
11974 Allows you to influence the way mouse selection happens. The
11975 functions in this facet will be called for a `mousedown` event
11976 on the editor, and can return an object that overrides the way a
11977 selection is computed from that mouse click or drag.
11978 */
11979 EditorView.mouseSelectionStyle = mouseSelectionStyle;
11980 /**
11981 Facet used to configure whether a given selection drag event
11982 should move or copy the selection. The given predicate will be
11983 called with the `mousedown` event, and can return `true` when
11984 the drag should move the content.
11985 */
11986 EditorView.dragMovesSelection = dragMovesSelection$1;
11987 /**
11988 Facet used to configure whether a given selecting click adds a
11989 new range to the existing selection or replaces it entirely. The
11990 default behavior is to check `event.metaKey` on macOS, and
11991 `event.ctrlKey` elsewhere.
11992 */
11993 EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
11994 /**
11995 A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
11996 are shown in the view. Decorations can be provided in two
11997 ways—directly, or via a function that takes an editor view.
11998
11999 Only decoration sets provided directly are allowed to influence
12000 the editor's vertical layout structure. The ones provided as
12001 functions are called _after_ the new viewport has been computed,
12002 and thus **must not** introduce block widgets or replacing
12003 decorations that cover line breaks.
12004
12005 If you want decorated ranges to behave like atomic units for
12006 cursor motion and deletion purposes, also provide the range set
12007 containing the decorations to
12008 [`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
12009 */
12010 EditorView.decorations = decorations;
12011 /**
12012 Used to provide ranges that should be treated as atoms as far as
12013 cursor motion is concerned. This causes methods like
12014 [`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
12015 [`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
12016 commands built on top of them) to skip across such regions when
12017 a selection endpoint would enter them. This does _not_ prevent
12018 direct programmatic [selection
12019 updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
12020 regions.
12021 */
12022 EditorView.atomicRanges = atomicRanges;
12023 /**
12024 When range decorations add a `unicode-bidi: isolate` style, they
12025 should also include a
12026 [`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
12027 in their decoration spec, and be exposed through this facet, so
12028 that the editor can compute the proper text order. (Other values
12029 for `unicode-bidi`, except of course `normal`, are not
12030 supported.)
12031 */
12032 EditorView.bidiIsolatedRanges = bidiIsolatedRanges;
12033 /**
12034 Facet that allows extensions to provide additional scroll
12035 margins (space around the sides of the scrolling element that
12036 should be considered invisible). This can be useful when the
12037 plugin introduces elements that cover part of that element (for
12038 example a horizontally fixed gutter).
12039 */
12040 EditorView.scrollMargins = scrollMargins;
12041 /**
12042 This facet records whether a dark theme is active. The extension
12043 returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
12044 includes an instance of this when the `dark` option is set to
12045 true.
12046 */
12047 EditorView.darkTheme = darkTheme;
12048 /**
12049 Provides a Content Security Policy nonce to use when creating
12050 the style sheets for the editor. Holds the empty string when no
12051 nonce has been provided.
12052 */
12053 EditorView.cspNonce = /*@__PURE__*/Facet.define({ combine: values => values.length ? values[0] : "" });
12054 /**
12055 Facet that provides additional DOM attributes for the editor's
12056 editable DOM element.
12057 */
12058 EditorView.contentAttributes = contentAttributes;
12059 /**
12060 Facet that provides DOM attributes for the editor's outer
12061 element.
12062 */
12063 EditorView.editorAttributes = editorAttributes;
12064 /**
12065 An extension that enables line wrapping in the editor (by
12066 setting CSS `white-space` to `pre-wrap` in the content).
12067 */
12068 EditorView.lineWrapping = /*@__PURE__*/EditorView.contentAttributes.of({ "class": "cm-lineWrapping" });
12069 /**
12070 State effect used to include screen reader announcements in a
12071 transaction. These will be added to the DOM in a visually hidden
12072 element with `aria-live="polite"` set, and should be used to
12073 describe effects that are visually obvious but may not be
12074 noticed by screen reader users (such as moving to the next
12075 search match).
12076 */
12077 EditorView.announce = /*@__PURE__*/StateEffect.define();
12078 // Maximum line length for which we compute accurate bidi info
12079 const MaxBidiLine = 4096;
12080 const BadMeasure = {};
12081 class CachedOrder {
12082 constructor(from, to, dir, isolates, fresh, order) {
12083 this.from = from;
12084 this.to = to;
12085 this.dir = dir;
12086 this.isolates = isolates;
12087 this.fresh = fresh;
12088 this.order = order;
12089 }
12090 static update(cache, changes) {
12091 if (changes.empty && !cache.some(c => c.fresh))
12092 return cache;
12093 let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : exports.Direction.LTR;
12094 for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
12095 let entry = cache[i];
12096 if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
12097 result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
12098 }
12099 return result;
12100 }
12101 }
12102 function attrsFromFacet(view, facet, base) {
12103 for (let sources = view.state.facet(facet), i = sources.length - 1; i >= 0; i--) {
12104 let source = sources[i], value = typeof source == "function" ? source(view) : source;
12105 if (value)
12106 combineAttrs(value, base);
12107 }
12108 return base;
12109 }
12110
12111 const currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
12112 function normalizeKeyName(name, platform) {
12113 const parts = name.split(/-(?!$)/);
12114 let result = parts[parts.length - 1];
12115 if (result == "Space")
12116 result = " ";
12117 let alt, ctrl, shift, meta;
12118 for (let i = 0; i < parts.length - 1; ++i) {
12119 const mod = parts[i];
12120 if (/^(cmd|meta|m)$/i.test(mod))
12121 meta = true;
12122 else if (/^a(lt)?$/i.test(mod))
12123 alt = true;
12124 else if (/^(c|ctrl|control)$/i.test(mod))
12125 ctrl = true;
12126 else if (/^s(hift)?$/i.test(mod))
12127 shift = true;
12128 else if (/^mod$/i.test(mod)) {
12129 if (platform == "mac")
12130 meta = true;
12131 else
12132 ctrl = true;
12133 }
12134 else
12135 throw new Error("Unrecognized modifier name: " + mod);
12136 }
12137 if (alt)
12138 result = "Alt-" + result;
12139 if (ctrl)
12140 result = "Ctrl-" + result;
12141 if (meta)
12142 result = "Meta-" + result;
12143 if (shift)
12144 result = "Shift-" + result;
12145 return result;
12146 }
12147 function modifiers(name, event, shift) {
12148 if (event.altKey)
12149 name = "Alt-" + name;
12150 if (event.ctrlKey)
12151 name = "Ctrl-" + name;
12152 if (event.metaKey)
12153 name = "Meta-" + name;
12154 if (shift !== false && event.shiftKey)
12155 name = "Shift-" + name;
12156 return name;
12157 }
12158 const handleKeyEvents = /*@__PURE__*/Prec.default(/*@__PURE__*/EditorView.domEventHandlers({
12159 keydown(event, view) {
12160 return runHandlers(getKeymap(view.state), event, view, "editor");
12161 }
12162 }));
12163 /**
12164 Facet used for registering keymaps.
12165
12166 You can add multiple keymaps to an editor. Their priorities
12167 determine their precedence (the ones specified early or with high
12168 priority get checked first). When a handler has returned `true`
12169 for a given key, no further handlers are called.
12170 */
12171 const keymap = /*@__PURE__*/Facet.define({ enables: handleKeyEvents });
12172 const Keymaps = /*@__PURE__*/new WeakMap();
12173 // This is hidden behind an indirection, rather than directly computed
12174 // by the facet, to keep internal types out of the facet's type.
12175 function getKeymap(state) {
12176 let bindings = state.facet(keymap);
12177 let map = Keymaps.get(bindings);
12178 if (!map)
12179 Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
12180 return map;
12181 }
12182 /**
12183 Run the key handlers registered for a given scope. The event
12184 object should be a `"keydown"` event. Returns true if any of the
12185 handlers handled it.
12186 */
12187 function runScopeHandlers(view, event, scope) {
12188 return runHandlers(getKeymap(view.state), event, view, scope);
12189 }
12190 let storedPrefix = null;
12191 const PrefixTimeout = 4000;
12192 function buildKeymap(bindings, platform = currentPlatform) {
12193 let bound = Object.create(null);
12194 let isPrefix = Object.create(null);
12195 let checkPrefix = (name, is) => {
12196 let current = isPrefix[name];
12197 if (current == null)
12198 isPrefix[name] = is;
12199 else if (current != is)
12200 throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix");
12201 };
12202 let add = (scope, key, command, preventDefault, stopPropagation) => {
12203 var _a, _b;
12204 let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12205 let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
12206 for (let i = 1; i < parts.length; i++) {
12207 let prefix = parts.slice(0, i).join(" ");
12208 checkPrefix(prefix, true);
12209 if (!scopeObj[prefix])
12210 scopeObj[prefix] = {
12211 preventDefault: true,
12212 stopPropagation: false,
12213 run: [(view) => {
12214 let ourObj = storedPrefix = { view, prefix, scope };
12215 setTimeout(() => { if (storedPrefix == ourObj)
12216 storedPrefix = null; }, PrefixTimeout);
12217 return true;
12218 }]
12219 };
12220 }
12221 let full = parts.join(" ");
12222 checkPrefix(full, false);
12223 let binding = scopeObj[full] || (scopeObj[full] = {
12224 preventDefault: false,
12225 stopPropagation: false,
12226 run: ((_b = (_a = scopeObj._any) === null || _a === void 0 ? void 0 : _a.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
12227 });
12228 if (command)
12229 binding.run.push(command);
12230 if (preventDefault)
12231 binding.preventDefault = true;
12232 if (stopPropagation)
12233 binding.stopPropagation = true;
12234 };
12235 for (let b of bindings) {
12236 let scopes = b.scope ? b.scope.split(" ") : ["editor"];
12237 if (b.any)
12238 for (let scope of scopes) {
12239 let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
12240 if (!scopeObj._any)
12241 scopeObj._any = { preventDefault: false, stopPropagation: false, run: [] };
12242 for (let key in scopeObj)
12243 scopeObj[key].run.push(b.any);
12244 }
12245 let name = b[platform] || b.key;
12246 if (!name)
12247 continue;
12248 for (let scope of scopes) {
12249 add(scope, name, b.run, b.preventDefault, b.stopPropagation);
12250 if (b.shift)
12251 add(scope, "Shift-" + name, b.shift, b.preventDefault, b.stopPropagation);
12252 }
12253 }
12254 return bound;
12255 }
12256 function runHandlers(map, event, view, scope) {
12257 let name = keyName(event);
12258 let charCode = codePointAt(name, 0), isChar = codePointSize(charCode) == name.length && name != " ";
12259 let prefix = "", handled = false, prevented = false, stopPropagation = false;
12260 if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
12261 prefix = storedPrefix.prefix + " ";
12262 if (modifierCodes.indexOf(event.keyCode) < 0) {
12263 prevented = true;
12264 storedPrefix = null;
12265 }
12266 }
12267 let ran = new Set;
12268 let runFor = (binding) => {
12269 if (binding) {
12270 for (let cmd of binding.run)
12271 if (!ran.has(cmd)) {
12272 ran.add(cmd);
12273 if (cmd(view, event)) {
12274 if (binding.stopPropagation)
12275 stopPropagation = true;
12276 return true;
12277 }
12278 }
12279 if (binding.preventDefault) {
12280 if (binding.stopPropagation)
12281 stopPropagation = true;
12282 prevented = true;
12283 }
12284 }
12285 return false;
12286 };
12287 let scopeObj = map[scope], baseName, shiftName;
12288 if (scopeObj) {
12289 if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)])) {
12290 handled = true;
12291 }
12292 else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) &&
12293 // Ctrl-Alt may be used for AltGr on Windows
12294 !(browser.windows && event.ctrlKey && event.altKey) &&
12295 (baseName = base[event.keyCode]) && baseName != name) {
12296 if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) {
12297 handled = true;
12298 }
12299 else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name && shiftName != baseName &&
12300 runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) {
12301 handled = true;
12302 }
12303 }
12304 else if (isChar && event.shiftKey &&
12305 runFor(scopeObj[prefix + modifiers(name, event, true)])) {
12306 handled = true;
12307 }
12308 if (!handled && runFor(scopeObj._any))
12309 handled = true;
12310 }
12311 if (prevented)
12312 handled = true;
12313 if (handled && stopPropagation)
12314 event.stopPropagation();
12315 return handled;
12316 }
12317
12318 /**
12319 Implementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates
12320 a rectangle at a given set of coordinates.
12321 */
12322 class RectangleMarker {
12323 /**
12324 Create a marker with the given class and dimensions. If `width`
12325 is null, the DOM element will get no width style.
12326 */
12327 constructor(className,
12328 /**
12329 The left position of the marker (in pixels, document-relative).
12330 */
12331 left,
12332 /**
12333 The top position of the marker.
12334 */
12335 top,
12336 /**
12337 The width of the marker, or null if it shouldn't get a width assigned.
12338 */
12339 width,
12340 /**
12341 The height of the marker.
12342 */
12343 height) {
12344 this.className = className;
12345 this.left = left;
12346 this.top = top;
12347 this.width = width;
12348 this.height = height;
12349 }
12350 draw() {
12351 let elt = document.createElement("div");
12352 elt.className = this.className;
12353 this.adjust(elt);
12354 return elt;
12355 }
12356 update(elt, prev) {
12357 if (prev.className != this.className)
12358 return false;
12359 this.adjust(elt);
12360 return true;
12361 }
12362 adjust(elt) {
12363 elt.style.left = this.left + "px";
12364 elt.style.top = this.top + "px";
12365 if (this.width != null)
12366 elt.style.width = this.width + "px";
12367 elt.style.height = this.height + "px";
12368 }
12369 eq(p) {
12370 return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&
12371 this.className == p.className;
12372 }
12373 /**
12374 Create a set of rectangles for the given selection range,
12375 assigning them theclass`className`. Will create a single
12376 rectangle for empty ranges, and a set of selection-style
12377 rectangles covering the range's content (in a bidi-aware
12378 way) for non-empty ones.
12379 */
12380 static forRange(view, className, range) {
12381 if (range.empty) {
12382 let pos = view.coordsAtPos(range.head, range.assoc || 1);
12383 if (!pos)
12384 return [];
12385 let base = getBase(view);
12386 return [new RectangleMarker(className, pos.left - base.left, pos.top - base.top, null, pos.bottom - pos.top)];
12387 }
12388 else {
12389 return rectanglesForRange(view, className, range);
12390 }
12391 }
12392 }
12393 function getBase(view) {
12394 let rect = view.scrollDOM.getBoundingClientRect();
12395 let left = view.textDirection == exports.Direction.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX;
12396 return { left: left - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY };
12397 }
12398 function wrappedLine(view, pos, inside) {
12399 let range = EditorSelection.cursor(pos);
12400 return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from),
12401 to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from),
12402 type: exports.BlockType.Text };
12403 }
12404 function rectanglesForRange(view, className, range) {
12405 if (range.to <= view.viewport.from || range.from >= view.viewport.to)
12406 return [];
12407 let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
12408 let ltr = view.textDirection == exports.Direction.LTR;
12409 let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);
12410 let lineElt = content.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt);
12411 let leftSide = contentRect.left +
12412 (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
12413 let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
12414 let startBlock = blockAt(view, from), endBlock = blockAt(view, to);
12415 let visualStart = startBlock.type == exports.BlockType.Text ? startBlock : null;
12416 let visualEnd = endBlock.type == exports.BlockType.Text ? endBlock : null;
12417 if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks))
12418 visualStart = wrappedLine(view, from, visualStart);
12419 if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks))
12420 visualEnd = wrappedLine(view, to, visualEnd);
12421 if (visualStart && visualEnd && visualStart.from == visualEnd.from) {
12422 return pieces(drawForLine(range.from, range.to, visualStart));
12423 }
12424 else {
12425 let top = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
12426 let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
12427 let between = [];
12428 if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) ||
12429 startBlock.widgetLineBreaks > 1 && top.bottom + view.defaultLineHeight / 2 < bottom.top)
12430 between.push(piece(leftSide, top.bottom, rightSide, bottom.top));
12431 else if (top.bottom < bottom.top && view.elementAtHeight((top.bottom + bottom.top) / 2).type == exports.BlockType.Text)
12432 top.bottom = bottom.top = (top.bottom + bottom.top) / 2;
12433 return pieces(top).concat(between).concat(pieces(bottom));
12434 }
12435 function piece(left, top, right, bottom) {
12436 return new RectangleMarker(className, left - base.left, top - base.top - 0.01 /* C.Epsilon */, right - left, bottom - top + 0.01 /* C.Epsilon */);
12437 }
12438 function pieces({ top, bottom, horizontal }) {
12439 let pieces = [];
12440 for (let i = 0; i < horizontal.length; i += 2)
12441 pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));
12442 return pieces;
12443 }
12444 // Gets passed from/to in line-local positions
12445 function drawForLine(from, to, line) {
12446 let top = 1e9, bottom = -1e9, horizontal = [];
12447 function addSpan(from, fromOpen, to, toOpen, dir) {
12448 // Passing 2/-2 is a kludge to force the view to return
12449 // coordinates on the proper side of block widgets, since
12450 // normalizing the side there, though appropriate for most
12451 // coordsAtPos queries, would break selection drawing.
12452 let fromCoords = view.coordsAtPos(from, (from == line.to ? -2 : 2));
12453 let toCoords = view.coordsAtPos(to, (to == line.from ? 2 : -2));
12454 if (!fromCoords || !toCoords)
12455 return;
12456 top = Math.min(fromCoords.top, toCoords.top, top);
12457 bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
12458 if (dir == exports.Direction.LTR)
12459 horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
12460 else
12461 horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
12462 }
12463 let start = from !== null && from !== void 0 ? from : line.from, end = to !== null && to !== void 0 ? to : line.to;
12464 // Split the range by visible range and document line
12465 for (let r of view.visibleRanges)
12466 if (r.to > start && r.from < end) {
12467 for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
12468 let docLine = view.state.doc.lineAt(pos);
12469 for (let span of view.bidiSpans(docLine)) {
12470 let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
12471 if (spanFrom >= endPos)
12472 break;
12473 if (spanTo > pos)
12474 addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);
12475 }
12476 pos = docLine.to + 1;
12477 if (pos >= endPos)
12478 break;
12479 }
12480 }
12481 if (horizontal.length == 0)
12482 addSpan(start, from == null, end, to == null, view.textDirection);
12483 return { top, bottom, horizontal };
12484 }
12485 function drawForWidget(block, top) {
12486 let y = contentRect.top + (top ? block.top : block.bottom);
12487 return { top: y, bottom: y, horizontal: [] };
12488 }
12489 }
12490 function sameMarker(a, b) {
12491 return a.constructor == b.constructor && a.eq(b);
12492 }
12493 class LayerView {
12494 constructor(view, layer) {
12495 this.view = view;
12496 this.layer = layer;
12497 this.drawn = [];
12498 this.scaleX = 1;
12499 this.scaleY = 1;
12500 this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) };
12501 this.dom = view.scrollDOM.appendChild(document.createElement("div"));
12502 this.dom.classList.add("cm-layer");
12503 if (layer.above)
12504 this.dom.classList.add("cm-layer-above");
12505 if (layer.class)
12506 this.dom.classList.add(layer.class);
12507 this.scale();
12508 this.dom.setAttribute("aria-hidden", "true");
12509 this.setOrder(view.state);
12510 view.requestMeasure(this.measureReq);
12511 if (layer.mount)
12512 layer.mount(this.dom, view);
12513 }
12514 update(update) {
12515 if (update.startState.facet(layerOrder) != update.state.facet(layerOrder))
12516 this.setOrder(update.state);
12517 if (this.layer.update(update, this.dom) || update.geometryChanged) {
12518 this.scale();
12519 update.view.requestMeasure(this.measureReq);
12520 }
12521 }
12522 setOrder(state) {
12523 let pos = 0, order = state.facet(layerOrder);
12524 while (pos < order.length && order[pos] != this.layer)
12525 pos++;
12526 this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
12527 }
12528 measure() {
12529 return this.layer.markers(this.view);
12530 }
12531 scale() {
12532 let { scaleX, scaleY } = this.view;
12533 if (scaleX != this.scaleX || scaleY != this.scaleY) {
12534 this.scaleX = scaleX;
12535 this.scaleY = scaleY;
12536 this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
12537 }
12538 }
12539 draw(markers) {
12540 if (markers.length != this.drawn.length || markers.some((p, i) => !sameMarker(p, this.drawn[i]))) {
12541 let old = this.dom.firstChild, oldI = 0;
12542 for (let marker of markers) {
12543 if (marker.update && old && marker.constructor && this.drawn[oldI].constructor &&
12544 marker.update(old, this.drawn[oldI])) {
12545 old = old.nextSibling;
12546 oldI++;
12547 }
12548 else {
12549 this.dom.insertBefore(marker.draw(), old);
12550 }
12551 }
12552 while (old) {
12553 let next = old.nextSibling;
12554 old.remove();
12555 old = next;
12556 }
12557 this.drawn = markers;
12558 }
12559 }
12560 destroy() {
12561 if (this.layer.destroy)
12562 this.layer.destroy(this.dom, this.view);
12563 this.dom.remove();
12564 }
12565 }
12566 const layerOrder = /*@__PURE__*/Facet.define();
12567 /**
12568 Define a layer.
12569 */
12570 function layer(config) {
12571 return [
12572 ViewPlugin.define(v => new LayerView(v, config)),
12573 layerOrder.of(config)
12574 ];
12575 }
12576
12577 const CanHidePrimary = !browser.ios; // FIXME test IE
12578 const selectionConfig = /*@__PURE__*/Facet.define({
12579 combine(configs) {
12580 return combineConfig(configs, {
12581 cursorBlinkRate: 1200,
12582 drawRangeCursor: true
12583 }, {
12584 cursorBlinkRate: (a, b) => Math.min(a, b),
12585 drawRangeCursor: (a, b) => a || b
12586 });
12587 }
12588 });
12589 /**
12590 Returns an extension that hides the browser's native selection and
12591 cursor, replacing the selection with a background behind the text
12592 (with the `cm-selectionBackground` class), and the
12593 cursors with elements overlaid over the code (using
12594 `cm-cursor-primary` and `cm-cursor-secondary`).
12595
12596 This allows the editor to display secondary selection ranges, and
12597 tends to produce a type of selection more in line with that users
12598 expect in a text editor (the native selection styling will often
12599 leave gaps between lines and won't fill the horizontal space after
12600 a line when the selection continues past it).
12601
12602 It does have a performance cost, in that it requires an extra DOM
12603 layout cycle for many updates (the selection is drawn based on DOM
12604 layout information that's only available after laying out the
12605 content).
12606 */
12607 function drawSelection(config = {}) {
12608 return [
12609 selectionConfig.of(config),
12610 cursorLayer,
12611 selectionLayer,
12612 hideNativeSelection,
12613 nativeSelectionHidden.of(true)
12614 ];
12615 }
12616 /**
12617 Retrieve the [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) configuration
12618 for this state. (Note that this will return a set of defaults even
12619 if `drawSelection` isn't enabled.)
12620 */
12621 function getDrawSelectionConfig(state) {
12622 return state.facet(selectionConfig);
12623 }
12624 function configChanged(update) {
12625 return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
12626 }
12627 const cursorLayer = /*@__PURE__*/layer({
12628 above: true,
12629 markers(view) {
12630 let { state } = view, conf = state.facet(selectionConfig);
12631 let cursors = [];
12632 for (let r of state.selection.ranges) {
12633 let prim = r == state.selection.main;
12634 if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
12635 let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
12636 let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
12637 for (let piece of RectangleMarker.forRange(view, className, cursor))
12638 cursors.push(piece);
12639 }
12640 }
12641 return cursors;
12642 },
12643 update(update, dom) {
12644 if (update.transactions.some(tr => tr.selection))
12645 dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
12646 let confChange = configChanged(update);
12647 if (confChange)
12648 setBlinkRate(update.state, dom);
12649 return update.docChanged || update.selectionSet || confChange;
12650 },
12651 mount(dom, view) {
12652 setBlinkRate(view.state, dom);
12653 },
12654 class: "cm-cursorLayer"
12655 });
12656 function setBlinkRate(state, dom) {
12657 dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
12658 }
12659 const selectionLayer = /*@__PURE__*/layer({
12660 above: false,
12661 markers(view) {
12662 return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r))
12663 .reduce((a, b) => a.concat(b));
12664 },
12665 update(update, dom) {
12666 return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
12667 },
12668 class: "cm-selectionLayer"
12669 });
12670 const themeSpec = {
12671 ".cm-line": {
12672 "& ::selection": { backgroundColor: "transparent !important" },
12673 "&::selection": { backgroundColor: "transparent !important" }
12674 }
12675 };
12676 if (CanHidePrimary) {
12677 themeSpec[".cm-line"].caretColor = "transparent !important";
12678 themeSpec[".cm-content"] = { caretColor: "transparent !important" };
12679 }
12680 const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.theme(themeSpec));
12681
12682 const setDropCursorPos = /*@__PURE__*/StateEffect.define({
12683 map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos); }
12684 });
12685 const dropCursorPos = /*@__PURE__*/StateField.define({
12686 create() { return null; },
12687 update(pos, tr) {
12688 if (pos != null)
12689 pos = tr.changes.mapPos(pos);
12690 return tr.effects.reduce((pos, e) => e.is(setDropCursorPos) ? e.value : pos, pos);
12691 }
12692 });
12693 const drawDropCursor = /*@__PURE__*/ViewPlugin.fromClass(class {
12694 constructor(view) {
12695 this.view = view;
12696 this.cursor = null;
12697 this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) };
12698 }
12699 update(update) {
12700 var _a;
12701 let cursorPos = update.state.field(dropCursorPos);
12702 if (cursorPos == null) {
12703 if (this.cursor != null) {
12704 (_a = this.cursor) === null || _a === void 0 ? void 0 : _a.remove();
12705 this.cursor = null;
12706 }
12707 }
12708 else {
12709 if (!this.cursor) {
12710 this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
12711 this.cursor.className = "cm-dropCursor";
12712 }
12713 if (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged)
12714 this.view.requestMeasure(this.measureReq);
12715 }
12716 }
12717 readPos() {
12718 let { view } = this;
12719 let pos = view.state.field(dropCursorPos);
12720 let rect = pos != null && view.coordsAtPos(pos);
12721 if (!rect)
12722 return null;
12723 let outer = view.scrollDOM.getBoundingClientRect();
12724 return {
12725 left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
12726 top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
12727 height: rect.bottom - rect.top
12728 };
12729 }
12730 drawCursor(pos) {
12731 if (this.cursor) {
12732 let { scaleX, scaleY } = this.view;
12733 if (pos) {
12734 this.cursor.style.left = pos.left / scaleX + "px";
12735 this.cursor.style.top = pos.top / scaleY + "px";
12736 this.cursor.style.height = pos.height / scaleY + "px";
12737 }
12738 else {
12739 this.cursor.style.left = "-100000px";
12740 }
12741 }
12742 }
12743 destroy() {
12744 if (this.cursor)
12745 this.cursor.remove();
12746 }
12747 setDropPos(pos) {
12748 if (this.view.state.field(dropCursorPos) != pos)
12749 this.view.dispatch({ effects: setDropCursorPos.of(pos) });
12750 }
12751 }, {
12752 eventObservers: {
12753 dragover(event) {
12754 this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY }));
12755 },
12756 dragleave(event) {
12757 if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget))
12758 this.setDropPos(null);
12759 },
12760 dragend() {
12761 this.setDropPos(null);
12762 },
12763 drop() {
12764 this.setDropPos(null);
12765 }
12766 }
12767 });
12768 /**
12769 Draws a cursor at the current drop position when something is
12770 dragged over the editor.
12771 */
12772 function dropCursor() {
12773 return [dropCursorPos, drawDropCursor];
12774 }
12775
12776 function iterMatches(doc, re, from, to, f) {
12777 re.lastIndex = 0;
12778 for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
12779 if (!cursor.lineBreak)
12780 while (m = re.exec(cursor.value))
12781 f(pos + m.index, m);
12782 }
12783 }
12784 function matchRanges(view, maxLength) {
12785 let visible = view.visibleRanges;
12786 if (visible.length == 1 && visible[0].from == view.viewport.from &&
12787 visible[0].to == view.viewport.to)
12788 return visible;
12789 let result = [];
12790 for (let { from, to } of visible) {
12791 from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
12792 to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
12793 if (result.length && result[result.length - 1].to >= from)
12794 result[result.length - 1].to = to;
12795 else
12796 result.push({ from, to });
12797 }
12798 return result;
12799 }
12800 /**
12801 Helper class used to make it easier to maintain decorations on
12802 visible code that matches a given regular expression. To be used
12803 in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object
12804 represent a matching configuration.
12805 */
12806 class MatchDecorator {
12807 /**
12808 Create a decorator.
12809 */
12810 constructor(config) {
12811 const { regexp, decoration, decorate, boundary, maxLength = 1000 } = config;
12812 if (!regexp.global)
12813 throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
12814 this.regexp = regexp;
12815 if (decorate) {
12816 this.addMatch = (match, view, from, add) => decorate(add, from, from + match[0].length, match, view);
12817 }
12818 else if (typeof decoration == "function") {
12819 this.addMatch = (match, view, from, add) => {
12820 let deco = decoration(match, view, from);
12821 if (deco)
12822 add(from, from + match[0].length, deco);
12823 };
12824 }
12825 else if (decoration) {
12826 this.addMatch = (match, _view, from, add) => add(from, from + match[0].length, decoration);
12827 }
12828 else {
12829 throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
12830 }
12831 this.boundary = boundary;
12832 this.maxLength = maxLength;
12833 }
12834 /**
12835 Compute the full set of decorations for matches in the given
12836 view's viewport. You'll want to call this when initializing your
12837 plugin.
12838 */
12839 createDeco(view) {
12840 let build = new RangeSetBuilder(), add = build.add.bind(build);
12841 for (let { from, to } of matchRanges(view, this.maxLength))
12842 iterMatches(view.state.doc, this.regexp, from, to, (from, m) => this.addMatch(m, view, from, add));
12843 return build.finish();
12844 }
12845 /**
12846 Update a set of decorations for a view update. `deco` _must_ be
12847 the set of decorations produced by _this_ `MatchDecorator` for
12848 the view state before the update.
12849 */
12850 updateDeco(update, deco) {
12851 let changeFrom = 1e9, changeTo = -1;
12852 if (update.docChanged)
12853 update.changes.iterChanges((_f, _t, from, to) => {
12854 if (to > update.view.viewport.from && from < update.view.viewport.to) {
12855 changeFrom = Math.min(from, changeFrom);
12856 changeTo = Math.max(to, changeTo);
12857 }
12858 });
12859 if (update.viewportChanged || changeTo - changeFrom > 1000)
12860 return this.createDeco(update.view);
12861 if (changeTo > -1)
12862 return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
12863 return deco;
12864 }
12865 updateRange(view, deco, updateFrom, updateTo) {
12866 for (let r of view.visibleRanges) {
12867 let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
12868 if (to > from) {
12869 let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
12870 let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
12871 if (this.boundary) {
12872 for (; from > fromLine.from; from--)
12873 if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
12874 start = from;
12875 break;
12876 }
12877 for (; to < toLine.to; to++)
12878 if (this.boundary.test(toLine.text[to - toLine.from])) {
12879 end = to;
12880 break;
12881 }
12882 }
12883 let ranges = [], m;
12884 let add = (from, to, deco) => ranges.push(deco.range(from, to));
12885 if (fromLine == toLine) {
12886 this.regexp.lastIndex = start - fromLine.from;
12887 while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from)
12888 this.addMatch(m, view, m.index + fromLine.from, add);
12889 }
12890 else {
12891 iterMatches(view.state.doc, this.regexp, start, end, (from, m) => this.addMatch(m, view, from, add));
12892 }
12893 deco = deco.update({ filterFrom: start, filterTo: end, filter: (from, to) => from < start || to > end, add: ranges });
12894 }
12895 }
12896 return deco;
12897 }
12898 }
12899
12900 const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
12901 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);
12902 const Names = {
12903 0: "null",
12904 7: "bell",
12905 8: "backspace",
12906 10: "newline",
12907 11: "vertical tab",
12908 13: "carriage return",
12909 27: "escape",
12910 8203: "zero width space",
12911 8204: "zero width non-joiner",
12912 8205: "zero width joiner",
12913 8206: "left-to-right mark",
12914 8207: "right-to-left mark",
12915 8232: "line separator",
12916 8237: "left-to-right override",
12917 8238: "right-to-left override",
12918 8294: "left-to-right isolate",
12919 8295: "right-to-left isolate",
12920 8297: "pop directional isolate",
12921 8233: "paragraph separator",
12922 65279: "zero width no-break space",
12923 65532: "object replacement"
12924 };
12925 let _supportsTabSize = null;
12926 function supportsTabSize() {
12927 var _a;
12928 if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
12929 let styles = document.body.style;
12930 _supportsTabSize = ((_a = styles.tabSize) !== null && _a !== void 0 ? _a : styles.MozTabSize) != null;
12931 }
12932 return _supportsTabSize || false;
12933 }
12934 const specialCharConfig = /*@__PURE__*/Facet.define({
12935 combine(configs) {
12936 let config = combineConfig(configs, {
12937 render: null,
12938 specialChars: Specials,
12939 addSpecialChars: null
12940 });
12941 if (config.replaceTabs = !supportsTabSize())
12942 config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport);
12943 if (config.addSpecialChars)
12944 config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport);
12945 return config;
12946 }
12947 });
12948 /**
12949 Returns an extension that installs highlighting of special
12950 characters.
12951 */
12952 function highlightSpecialChars(
12953 /**
12954 Configuration options.
12955 */
12956 config = {}) {
12957 return [specialCharConfig.of(config), specialCharPlugin()];
12958 }
12959 let _plugin = null;
12960 function specialCharPlugin() {
12961 return _plugin || (_plugin = ViewPlugin.fromClass(class {
12962 constructor(view) {
12963 this.view = view;
12964 this.decorations = Decoration.none;
12965 this.decorationCache = Object.create(null);
12966 this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
12967 this.decorations = this.decorator.createDeco(view);
12968 }
12969 makeDecorator(conf) {
12970 return new MatchDecorator({
12971 regexp: conf.specialChars,
12972 decoration: (m, view, pos) => {
12973 let { doc } = view.state;
12974 let code = codePointAt(m[0], 0);
12975 if (code == 9) {
12976 let line = doc.lineAt(pos);
12977 let size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from);
12978 return Decoration.replace({
12979 widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth / this.view.scaleX)
12980 });
12981 }
12982 return this.decorationCache[code] ||
12983 (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
12984 },
12985 boundary: conf.replaceTabs ? undefined : /[^]/
12986 });
12987 }
12988 update(update) {
12989 let conf = update.state.facet(specialCharConfig);
12990 if (update.startState.facet(specialCharConfig) != conf) {
12991 this.decorator = this.makeDecorator(conf);
12992 this.decorations = this.decorator.createDeco(update.view);
12993 }
12994 else {
12995 this.decorations = this.decorator.updateDeco(update, this.decorations);
12996 }
12997 }
12998 }, {
12999 decorations: v => v.decorations
13000 }));
13001 }
13002 const DefaultPlaceholder = "\u2022";
13003 // Assigns placeholder characters from the Control Pictures block to
13004 // ASCII control characters
13005 function placeholder$1(code) {
13006 if (code >= 32)
13007 return DefaultPlaceholder;
13008 if (code == 10)
13009 return "\u2424";
13010 return String.fromCharCode(9216 + code);
13011 }
13012 class SpecialCharWidget extends WidgetType {
13013 constructor(options, code) {
13014 super();
13015 this.options = options;
13016 this.code = code;
13017 }
13018 eq(other) { return other.code == this.code; }
13019 toDOM(view) {
13020 let ph = placeholder$1(this.code);
13021 let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
13022 let custom = this.options.render && this.options.render(this.code, desc, ph);
13023 if (custom)
13024 return custom;
13025 let span = document.createElement("span");
13026 span.textContent = ph;
13027 span.title = desc;
13028 span.setAttribute("aria-label", desc);
13029 span.className = "cm-specialChar";
13030 return span;
13031 }
13032 ignoreEvent() { return false; }
13033 }
13034 class TabWidget extends WidgetType {
13035 constructor(width) {
13036 super();
13037 this.width = width;
13038 }
13039 eq(other) { return other.width == this.width; }
13040 toDOM() {
13041 let span = document.createElement("span");
13042 span.textContent = "\t";
13043 span.className = "cm-tab";
13044 span.style.width = this.width + "px";
13045 return span;
13046 }
13047 ignoreEvent() { return false; }
13048 }
13049
13050 const plugin = /*@__PURE__*/ViewPlugin.fromClass(class {
13051 constructor() {
13052 this.height = 1000;
13053 this.attrs = { style: "padding-bottom: 1000px" };
13054 }
13055 update(update) {
13056 let { view } = update;
13057 let height = view.viewState.editorHeight * view.scaleY -
13058 view.defaultLineHeight - view.documentPadding.top - 0.5;
13059 if (height >= 0 && height != this.height) {
13060 this.height = height;
13061 this.attrs = { style: `padding-bottom: ${height}px` };
13062 }
13063 }
13064 });
13065 /**
13066 Returns an extension that makes sure the content has a bottom
13067 margin equivalent to the height of the editor, minus one line
13068 height, so that every line in the document can be scrolled to the
13069 top of the editor.
13070
13071 This is only meaningful when the editor is scrollable, and should
13072 not be enabled in editors that take the size of their content.
13073 */
13074 function scrollPastEnd() {
13075 return [plugin, contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.attrs) || null; })];
13076 }
13077
13078 /**
13079 Mark lines that have a cursor on them with the `"cm-activeLine"`
13080 DOM class.
13081 */
13082 function highlightActiveLine() {
13083 return activeLineHighlighter;
13084 }
13085 const lineDeco = /*@__PURE__*/Decoration.line({ class: "cm-activeLine" });
13086 const activeLineHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
13087 constructor(view) {
13088 this.decorations = this.getDeco(view);
13089 }
13090 update(update) {
13091 if (update.docChanged || update.selectionSet)
13092 this.decorations = this.getDeco(update.view);
13093 }
13094 getDeco(view) {
13095 let lastLineStart = -1, deco = [];
13096 for (let r of view.state.selection.ranges) {
13097 let line = view.lineBlockAt(r.head);
13098 if (line.from > lastLineStart) {
13099 deco.push(lineDeco.range(line.from));
13100 lastLineStart = line.from;
13101 }
13102 }
13103 return Decoration.set(deco);
13104 }
13105 }, {
13106 decorations: v => v.decorations
13107 });
13108
13109 class Placeholder extends WidgetType {
13110 constructor(content) {
13111 super();
13112 this.content = content;
13113 }
13114 toDOM() {
13115 let wrap = document.createElement("span");
13116 wrap.className = "cm-placeholder";
13117 wrap.style.pointerEvents = "none";
13118 wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : this.content);
13119 if (typeof this.content == "string")
13120 wrap.setAttribute("aria-label", "placeholder " + this.content);
13121 else
13122 wrap.setAttribute("aria-hidden", "true");
13123 return wrap;
13124 }
13125 coordsAt(dom) {
13126 let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : [];
13127 if (!rects.length)
13128 return null;
13129 let style = window.getComputedStyle(dom.parentNode);
13130 let rect = flattenRect(rects[0], style.direction != "rtl");
13131 let lineHeight = parseInt(style.lineHeight);
13132 if (rect.bottom - rect.top > lineHeight * 1.5)
13133 return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight };
13134 return rect;
13135 }
13136 ignoreEvent() { return false; }
13137 }
13138 /**
13139 Extension that enables a placeholder—a piece of example content
13140 to show when the editor is empty.
13141 */
13142 function placeholder(content) {
13143 return ViewPlugin.fromClass(class {
13144 constructor(view) {
13145 this.view = view;
13146 this.placeholder = content
13147 ? Decoration.set([Decoration.widget({ widget: new Placeholder(content), side: 1 }).range(0)])
13148 : Decoration.none;
13149 }
13150 get decorations() { return this.view.state.doc.length ? Decoration.none : this.placeholder; }
13151 }, { decorations: v => v.decorations });
13152 }
13153
13154 // Don't compute precise column positions for line offsets above this
13155 // (since it could get expensive). Assume offset==column for them.
13156 const MaxOff = 2000;
13157 function rectangleFor(state, a, b) {
13158 let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
13159 let ranges = [];
13160 if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
13161 let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
13162 for (let i = startLine; i <= endLine; i++) {
13163 let line = state.doc.line(i);
13164 if (line.length <= endOff)
13165 ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
13166 }
13167 }
13168 else {
13169 let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
13170 for (let i = startLine; i <= endLine; i++) {
13171 let line = state.doc.line(i);
13172 let start = findColumn(line.text, startCol, state.tabSize, true);
13173 if (start < 0) {
13174 ranges.push(EditorSelection.cursor(line.to));
13175 }
13176 else {
13177 let end = findColumn(line.text, endCol, state.tabSize);
13178 ranges.push(EditorSelection.range(line.from + start, line.from + end));
13179 }
13180 }
13181 }
13182 return ranges;
13183 }
13184 function absoluteColumn(view, x) {
13185 let ref = view.coordsAtPos(view.viewport.from);
13186 return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;
13187 }
13188 function getPos(view, event) {
13189 let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
13190 let line = view.state.doc.lineAt(offset), off = offset - line.from;
13191 let col = off > MaxOff ? -1
13192 : off == line.length ? absoluteColumn(view, event.clientX)
13193 : countColumn(line.text, view.state.tabSize, offset - line.from);
13194 return { line: line.number, col, off };
13195 }
13196 function rectangleSelectionStyle(view, event) {
13197 let start = getPos(view, event), startSel = view.state.selection;
13198 if (!start)
13199 return null;
13200 return {
13201 update(update) {
13202 if (update.docChanged) {
13203 let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);
13204 let newLine = update.state.doc.lineAt(newStart);
13205 start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
13206 startSel = startSel.map(update.changes);
13207 }
13208 },
13209 get(event, _extend, multiple) {
13210 let cur = getPos(view, event);
13211 if (!cur)
13212 return startSel;
13213 let ranges = rectangleFor(view.state, start, cur);
13214 if (!ranges.length)
13215 return startSel;
13216 if (multiple)
13217 return EditorSelection.create(ranges.concat(startSel.ranges));
13218 else
13219 return EditorSelection.create(ranges);
13220 }
13221 };
13222 }
13223 /**
13224 Create an extension that enables rectangular selections. By
13225 default, it will react to left mouse drag with the Alt key held
13226 down. When such a selection occurs, the text within the rectangle
13227 that was dragged over will be selected, as one selection
13228 [range](https://codemirror.net/6/docs/ref/#state.SelectionRange) per line.
13229 */
13230 function rectangularSelection(options) {
13231 let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);
13232 return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);
13233 }
13234 const keys = {
13235 Alt: [18, e => !!e.altKey],
13236 Control: [17, e => !!e.ctrlKey],
13237 Shift: [16, e => !!e.shiftKey],
13238 Meta: [91, e => !!e.metaKey]
13239 };
13240 const showCrosshair = { style: "cursor: crosshair" };
13241 /**
13242 Returns an extension that turns the pointer cursor into a
13243 crosshair when a given modifier key, defaulting to Alt, is held
13244 down. Can serve as a visual hint that rectangular selection is
13245 going to happen when paired with
13246 [`rectangularSelection`](https://codemirror.net/6/docs/ref/#view.rectangularSelection).
13247 */
13248 function crosshairCursor(options = {}) {
13249 let [code, getter] = keys[options.key || "Alt"];
13250 let plugin = ViewPlugin.fromClass(class {
13251 constructor(view) {
13252 this.view = view;
13253 this.isDown = false;
13254 }
13255 set(isDown) {
13256 if (this.isDown != isDown) {
13257 this.isDown = isDown;
13258 this.view.update([]);
13259 }
13260 }
13261 }, {
13262 eventObservers: {
13263 keydown(e) {
13264 this.set(e.keyCode == code || getter(e));
13265 },
13266 keyup(e) {
13267 if (e.keyCode == code || !getter(e))
13268 this.set(false);
13269 },
13270 mousemove(e) {
13271 this.set(getter(e));
13272 }
13273 }
13274 });
13275 return [
13276 plugin,
13277 EditorView.contentAttributes.of(view => { var _a; return ((_a = view.plugin(plugin)) === null || _a === void 0 ? void 0 : _a.isDown) ? showCrosshair : null; })
13278 ];
13279 }
13280
13281 const Outside = "-10000px";
13282 class TooltipViewManager {
13283 constructor(view, facet, createTooltipView) {
13284 this.facet = facet;
13285 this.createTooltipView = createTooltipView;
13286 this.input = view.state.facet(facet);
13287 this.tooltips = this.input.filter(t => t);
13288 this.tooltipViews = this.tooltips.map(createTooltipView);
13289 }
13290 update(update, above) {
13291 var _a;
13292 let input = update.state.facet(this.facet);
13293 let tooltips = input.filter(x => x);
13294 if (input === this.input) {
13295 for (let t of this.tooltipViews)
13296 if (t.update)
13297 t.update(update);
13298 return false;
13299 }
13300 let tooltipViews = [], newAbove = above ? [] : null;
13301 for (let i = 0; i < tooltips.length; i++) {
13302 let tip = tooltips[i], known = -1;
13303 if (!tip)
13304 continue;
13305 for (let i = 0; i < this.tooltips.length; i++) {
13306 let other = this.tooltips[i];
13307 if (other && other.create == tip.create)
13308 known = i;
13309 }
13310 if (known < 0) {
13311 tooltipViews[i] = this.createTooltipView(tip);
13312 if (newAbove)
13313 newAbove[i] = !!tip.above;
13314 }
13315 else {
13316 let tooltipView = tooltipViews[i] = this.tooltipViews[known];
13317 if (newAbove)
13318 newAbove[i] = above[known];
13319 if (tooltipView.update)
13320 tooltipView.update(update);
13321 }
13322 }
13323 for (let t of this.tooltipViews)
13324 if (tooltipViews.indexOf(t) < 0) {
13325 t.dom.remove();
13326 (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
13327 }
13328 if (above) {
13329 newAbove.forEach((val, i) => above[i] = val);
13330 above.length = newAbove.length;
13331 }
13332 this.input = input;
13333 this.tooltips = tooltips;
13334 this.tooltipViews = tooltipViews;
13335 return true;
13336 }
13337 }
13338 /**
13339 Creates an extension that configures tooltip behavior.
13340 */
13341 function tooltips(config = {}) {
13342 return tooltipConfig.of(config);
13343 }
13344 function windowSpace(view) {
13345 let { win } = view;
13346 return { top: 0, left: 0, bottom: win.innerHeight, right: win.innerWidth };
13347 }
13348 const tooltipConfig = /*@__PURE__*/Facet.define({
13349 combine: values => {
13350 var _a, _b, _c;
13351 return ({
13352 position: browser.ios ? "absolute" : ((_a = values.find(conf => conf.position)) === null || _a === void 0 ? void 0 : _a.position) || "fixed",
13353 parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
13354 tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace,
13355 });
13356 }
13357 });
13358 const knownHeight = /*@__PURE__*/new WeakMap();
13359 const tooltipPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
13360 constructor(view) {
13361 this.view = view;
13362 this.above = [];
13363 this.inView = true;
13364 this.madeAbsolute = false;
13365 this.lastTransaction = 0;
13366 this.measureTimeout = -1;
13367 let config = view.state.facet(tooltipConfig);
13368 this.position = config.position;
13369 this.parent = config.parent;
13370 this.classes = view.themeClasses;
13371 this.createContainer();
13372 this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
13373 this.manager = new TooltipViewManager(view, showTooltip, t => this.createTooltip(t));
13374 this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => {
13375 if (Date.now() > this.lastTransaction - 50 &&
13376 entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1)
13377 this.measureSoon();
13378 }, { threshold: [1] }) : null;
13379 this.observeIntersection();
13380 view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
13381 this.maybeMeasure();
13382 }
13383 createContainer() {
13384 if (this.parent) {
13385 this.container = document.createElement("div");
13386 this.container.style.position = "relative";
13387 this.container.className = this.view.themeClasses;
13388 this.parent.appendChild(this.container);
13389 }
13390 else {
13391 this.container = this.view.dom;
13392 }
13393 }
13394 observeIntersection() {
13395 if (this.intersectionObserver) {
13396 this.intersectionObserver.disconnect();
13397 for (let tooltip of this.manager.tooltipViews)
13398 this.intersectionObserver.observe(tooltip.dom);
13399 }
13400 }
13401 measureSoon() {
13402 if (this.measureTimeout < 0)
13403 this.measureTimeout = setTimeout(() => {
13404 this.measureTimeout = -1;
13405 this.maybeMeasure();
13406 }, 50);
13407 }
13408 update(update) {
13409 if (update.transactions.length)
13410 this.lastTransaction = Date.now();
13411 let updated = this.manager.update(update, this.above);
13412 if (updated)
13413 this.observeIntersection();
13414 let shouldMeasure = updated || update.geometryChanged;
13415 let newConfig = update.state.facet(tooltipConfig);
13416 if (newConfig.position != this.position && !this.madeAbsolute) {
13417 this.position = newConfig.position;
13418 for (let t of this.manager.tooltipViews)
13419 t.dom.style.position = this.position;
13420 shouldMeasure = true;
13421 }
13422 if (newConfig.parent != this.parent) {
13423 if (this.parent)
13424 this.container.remove();
13425 this.parent = newConfig.parent;
13426 this.createContainer();
13427 for (let t of this.manager.tooltipViews)
13428 this.container.appendChild(t.dom);
13429 shouldMeasure = true;
13430 }
13431 else if (this.parent && this.view.themeClasses != this.classes) {
13432 this.classes = this.container.className = this.view.themeClasses;
13433 }
13434 if (shouldMeasure)
13435 this.maybeMeasure();
13436 }
13437 createTooltip(tooltip) {
13438 let tooltipView = tooltip.create(this.view);
13439 tooltipView.dom.classList.add("cm-tooltip");
13440 if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
13441 let arrow = document.createElement("div");
13442 arrow.className = "cm-tooltip-arrow";
13443 tooltipView.dom.appendChild(arrow);
13444 }
13445 tooltipView.dom.style.position = this.position;
13446 tooltipView.dom.style.top = Outside;
13447 tooltipView.dom.style.left = "0px";
13448 this.container.appendChild(tooltipView.dom);
13449 if (tooltipView.mount)
13450 tooltipView.mount(this.view);
13451 return tooltipView;
13452 }
13453 destroy() {
13454 var _a, _b;
13455 this.view.win.removeEventListener("resize", this.measureSoon);
13456 for (let tooltipView of this.manager.tooltipViews) {
13457 tooltipView.dom.remove();
13458 (_a = tooltipView.destroy) === null || _a === void 0 ? void 0 : _a.call(tooltipView);
13459 }
13460 if (this.parent)
13461 this.container.remove();
13462 (_b = this.intersectionObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
13463 clearTimeout(this.measureTimeout);
13464 }
13465 readMeasure() {
13466 let editor = this.view.dom.getBoundingClientRect();
13467 let scaleX = 1, scaleY = 1, makeAbsolute = false;
13468 if (this.position == "fixed" && this.manager.tooltipViews.length) {
13469 let { dom } = this.manager.tooltipViews[0];
13470 if (browser.gecko) {
13471 // Firefox sets the element's `offsetParent` to the
13472 // transformed element when a transform interferes with fixed
13473 // positioning.
13474 makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;
13475 }
13476 else {
13477 // On other browsers, we have to awkwardly try and use other
13478 // information to detect a transform.
13479 if (this.view.scaleX != 1 || this.view.scaleY != 1) {
13480 makeAbsolute = true;
13481 }
13482 else if (dom.style.top == Outside && dom.style.left == "0px") {
13483 let rect = dom.getBoundingClientRect();
13484 makeAbsolute = Math.abs(rect.top + 10000) > 1 || Math.abs(rect.left) > 1;
13485 }
13486 }
13487 }
13488 if (makeAbsolute || this.position == "absolute") {
13489 if (this.parent) {
13490 let rect = this.parent.getBoundingClientRect();
13491 if (rect.width && rect.height) {
13492 scaleX = rect.width / this.parent.offsetWidth;
13493 scaleY = rect.height / this.parent.offsetHeight;
13494 }
13495 }
13496 else {
13497 ({ scaleX, scaleY } = this.view.viewState);
13498 }
13499 }
13500 return {
13501 editor,
13502 parent: this.parent ? this.container.getBoundingClientRect() : editor,
13503 pos: this.manager.tooltips.map((t, i) => {
13504 let tv = this.manager.tooltipViews[i];
13505 return tv.getCoords ? tv.getCoords(t.pos) : this.view.coordsAtPos(t.pos);
13506 }),
13507 size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
13508 space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
13509 scaleX, scaleY, makeAbsolute
13510 };
13511 }
13512 writeMeasure(measured) {
13513 var _a;
13514 if (measured.makeAbsolute) {
13515 this.madeAbsolute = true;
13516 this.position = "absolute";
13517 for (let t of this.manager.tooltipViews)
13518 t.dom.style.position = "absolute";
13519 }
13520 let { editor, space, scaleX, scaleY } = measured;
13521 let others = [];
13522 for (let i = 0; i < this.manager.tooltips.length; i++) {
13523 let tooltip = this.manager.tooltips[i], tView = this.manager.tooltipViews[i], { dom } = tView;
13524 let pos = measured.pos[i], size = measured.size[i];
13525 // Hide tooltips that are outside of the editor.
13526 if (!pos || pos.bottom <= Math.max(editor.top, space.top) ||
13527 pos.top >= Math.min(editor.bottom, space.bottom) ||
13528 pos.right < Math.max(editor.left, space.left) - .1 ||
13529 pos.left > Math.min(editor.right, space.right) + .1) {
13530 dom.style.top = Outside;
13531 continue;
13532 }
13533 let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
13534 let arrowHeight = arrow ? 7 /* Arrow.Size */ : 0;
13535 let width = size.right - size.left, height = (_a = knownHeight.get(tView)) !== null && _a !== void 0 ? _a : size.bottom - size.top;
13536 let offset = tView.offset || noOffset, ltr = this.view.textDirection == exports.Direction.LTR;
13537 let left = size.width > space.right - space.left ? (ltr ? space.left : space.right - size.width)
13538 : ltr ? Math.min(pos.left - (arrow ? 14 /* Arrow.Offset */ : 0) + offset.x, space.right - width)
13539 : Math.max(space.left, pos.left - width + (arrow ? 14 /* Arrow.Offset */ : 0) - offset.x);
13540 let above = this.above[i];
13541 if (!tooltip.strictSide && (above
13542 ? pos.top - (size.bottom - size.top) - offset.y < space.top
13543 : pos.bottom + (size.bottom - size.top) + offset.y > space.bottom) &&
13544 above == (space.bottom - pos.bottom > pos.top - space.top))
13545 above = this.above[i] = !above;
13546 let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight;
13547 if (spaceVert < height && tView.resize !== false) {
13548 if (spaceVert < this.view.defaultLineHeight) {
13549 dom.style.top = Outside;
13550 continue;
13551 }
13552 knownHeight.set(tView, height);
13553 dom.style.height = (height = spaceVert) / scaleY + "px";
13554 }
13555 else if (dom.style.height) {
13556 dom.style.height = "";
13557 }
13558 let top = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
13559 let right = left + width;
13560 if (tView.overlap !== true)
13561 for (let r of others)
13562 if (r.left < right && r.right > left && r.top < top + height && r.bottom > top)
13563 top = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;
13564 if (this.position == "absolute") {
13565 dom.style.top = (top - measured.parent.top) / scaleY + "px";
13566 dom.style.left = (left - measured.parent.left) / scaleX + "px";
13567 }
13568 else {
13569 dom.style.top = top / scaleY + "px";
13570 dom.style.left = left / scaleX + "px";
13571 }
13572 if (arrow) {
13573 let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 /* Arrow.Offset */ - 7 /* Arrow.Size */);
13574 arrow.style.left = arrowLeft / scaleX + "px";
13575 }
13576 if (tView.overlap !== true)
13577 others.push({ left, top, right, bottom: top + height });
13578 dom.classList.toggle("cm-tooltip-above", above);
13579 dom.classList.toggle("cm-tooltip-below", !above);
13580 if (tView.positioned)
13581 tView.positioned(measured.space);
13582 }
13583 }
13584 maybeMeasure() {
13585 if (this.manager.tooltips.length) {
13586 if (this.view.inView)
13587 this.view.requestMeasure(this.measureReq);
13588 if (this.inView != this.view.inView) {
13589 this.inView = this.view.inView;
13590 if (!this.inView)
13591 for (let tv of this.manager.tooltipViews)
13592 tv.dom.style.top = Outside;
13593 }
13594 }
13595 }
13596 }, {
13597 eventObservers: {
13598 scroll() { this.maybeMeasure(); }
13599 }
13600 });
13601 const baseTheme$3 = /*@__PURE__*/EditorView.baseTheme({
13602 ".cm-tooltip": {
13603 zIndex: 100,
13604 boxSizing: "border-box"
13605 },
13606 "&light .cm-tooltip": {
13607 border: "1px solid #bbb",
13608 backgroundColor: "#f5f5f5"
13609 },
13610 "&light .cm-tooltip-section:not(:first-child)": {
13611 borderTop: "1px solid #bbb",
13612 },
13613 "&dark .cm-tooltip": {
13614 backgroundColor: "#333338",
13615 color: "white"
13616 },
13617 ".cm-tooltip-arrow": {
13618 height: `${7 /* Arrow.Size */}px`,
13619 width: `${7 /* Arrow.Size */ * 2}px`,
13620 position: "absolute",
13621 zIndex: -1,
13622 overflow: "hidden",
13623 "&:before, &:after": {
13624 content: "''",
13625 position: "absolute",
13626 width: 0,
13627 height: 0,
13628 borderLeft: `${7 /* Arrow.Size */}px solid transparent`,
13629 borderRight: `${7 /* Arrow.Size */}px solid transparent`,
13630 },
13631 ".cm-tooltip-above &": {
13632 bottom: `-${7 /* Arrow.Size */}px`,
13633 "&:before": {
13634 borderTop: `${7 /* Arrow.Size */}px solid #bbb`,
13635 },
13636 "&:after": {
13637 borderTop: `${7 /* Arrow.Size */}px solid #f5f5f5`,
13638 bottom: "1px"
13639 }
13640 },
13641 ".cm-tooltip-below &": {
13642 top: `-${7 /* Arrow.Size */}px`,
13643 "&:before": {
13644 borderBottom: `${7 /* Arrow.Size */}px solid #bbb`,
13645 },
13646 "&:after": {
13647 borderBottom: `${7 /* Arrow.Size */}px solid #f5f5f5`,
13648 top: "1px"
13649 }
13650 },
13651 },
13652 "&dark .cm-tooltip .cm-tooltip-arrow": {
13653 "&:before": {
13654 borderTopColor: "#333338",
13655 borderBottomColor: "#333338"
13656 },
13657 "&:after": {
13658 borderTopColor: "transparent",
13659 borderBottomColor: "transparent"
13660 }
13661 }
13662 });
13663 const noOffset = { x: 0, y: 0 };
13664 /**
13665 Facet to which an extension can add a value to show a tooltip.
13666 */
13667 const showTooltip = /*@__PURE__*/Facet.define({
13668 enables: [tooltipPlugin, baseTheme$3]
13669 });
13670 const showHoverTooltip = /*@__PURE__*/Facet.define();
13671 class HoverTooltipHost {
13672 // Needs to be static so that host tooltip instances always match
13673 static create(view) {
13674 return new HoverTooltipHost(view);
13675 }
13676 constructor(view) {
13677 this.view = view;
13678 this.mounted = false;
13679 this.dom = document.createElement("div");
13680 this.dom.classList.add("cm-tooltip-hover");
13681 this.manager = new TooltipViewManager(view, showHoverTooltip, t => this.createHostedView(t));
13682 }
13683 createHostedView(tooltip) {
13684 let hostedView = tooltip.create(this.view);
13685 hostedView.dom.classList.add("cm-tooltip-section");
13686 this.dom.appendChild(hostedView.dom);
13687 if (this.mounted && hostedView.mount)
13688 hostedView.mount(this.view);
13689 return hostedView;
13690 }
13691 mount(view) {
13692 for (let hostedView of this.manager.tooltipViews) {
13693 if (hostedView.mount)
13694 hostedView.mount(view);
13695 }
13696 this.mounted = true;
13697 }
13698 positioned(space) {
13699 for (let hostedView of this.manager.tooltipViews) {
13700 if (hostedView.positioned)
13701 hostedView.positioned(space);
13702 }
13703 }
13704 update(update) {
13705 this.manager.update(update);
13706 }
13707 destroy() {
13708 var _a;
13709 for (let t of this.manager.tooltipViews)
13710 (_a = t.destroy) === null || _a === void 0 ? void 0 : _a.call(t);
13711 }
13712 passProp(name) {
13713 let value = undefined;
13714 for (let view of this.manager.tooltipViews) {
13715 let given = view[name];
13716 if (given !== undefined) {
13717 if (value === undefined)
13718 value = given;
13719 else if (value !== given)
13720 return undefined;
13721 }
13722 }
13723 return value;
13724 }
13725 get offset() { return this.passProp("offset"); }
13726 get getCoords() { return this.passProp("getCoords"); }
13727 get overlap() { return this.passProp("overlap"); }
13728 get resize() { return this.passProp("resize"); }
13729 }
13730 const showHoverTooltipHost = /*@__PURE__*/showTooltip.compute([showHoverTooltip], state => {
13731 let tooltips = state.facet(showHoverTooltip).filter(t => t);
13732 if (tooltips.length === 0)
13733 return null;
13734 return {
13735 pos: Math.min(...tooltips.map(t => t.pos)),
13736 end: Math.max(...tooltips.map(t => { var _a; return (_a = t.end) !== null && _a !== void 0 ? _a : t.pos; })),
13737 create: HoverTooltipHost.create,
13738 above: tooltips[0].above,
13739 arrow: tooltips.some(t => t.arrow),
13740 };
13741 });
13742 class HoverPlugin {
13743 constructor(view, source, field, setHover, hoverTime) {
13744 this.view = view;
13745 this.source = source;
13746 this.field = field;
13747 this.setHover = setHover;
13748 this.hoverTime = hoverTime;
13749 this.hoverTimeout = -1;
13750 this.restartTimeout = -1;
13751 this.pending = null;
13752 this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 };
13753 this.checkHover = this.checkHover.bind(this);
13754 view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
13755 view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
13756 }
13757 update() {
13758 if (this.pending) {
13759 this.pending = null;
13760 clearTimeout(this.restartTimeout);
13761 this.restartTimeout = setTimeout(() => this.startHover(), 20);
13762 }
13763 }
13764 get active() {
13765 return this.view.state.field(this.field);
13766 }
13767 checkHover() {
13768 this.hoverTimeout = -1;
13769 if (this.active)
13770 return;
13771 let hovered = Date.now() - this.lastMove.time;
13772 if (hovered < this.hoverTime)
13773 this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);
13774 else
13775 this.startHover();
13776 }
13777 startHover() {
13778 clearTimeout(this.restartTimeout);
13779 let { view, lastMove } = this;
13780 let desc = view.docView.nearest(lastMove.target);
13781 if (!desc)
13782 return;
13783 let pos, side = 1;
13784 if (desc instanceof WidgetView) {
13785 pos = desc.posAtStart;
13786 }
13787 else {
13788 pos = view.posAtCoords(lastMove);
13789 if (pos == null)
13790 return;
13791 let posCoords = view.coordsAtPos(pos);
13792 if (!posCoords ||
13793 lastMove.y < posCoords.top || lastMove.y > posCoords.bottom ||
13794 lastMove.x < posCoords.left - view.defaultCharacterWidth ||
13795 lastMove.x > posCoords.right + view.defaultCharacterWidth)
13796 return;
13797 let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
13798 let rtl = bidi && bidi.dir == exports.Direction.RTL ? -1 : 1;
13799 side = (lastMove.x < posCoords.left ? -rtl : rtl);
13800 }
13801 let open = this.source(view, pos, side);
13802 if (open === null || open === void 0 ? void 0 : open.then) {
13803 let pending = this.pending = { pos };
13804 open.then(result => {
13805 if (this.pending == pending) {
13806 this.pending = null;
13807 if (result)
13808 view.dispatch({ effects: this.setHover.of(result) });
13809 }
13810 }, e => logException(view.state, e, "hover tooltip"));
13811 }
13812 else if (open) {
13813 view.dispatch({ effects: this.setHover.of(open) });
13814 }
13815 }
13816 get tooltip() {
13817 let plugin = this.view.plugin(tooltipPlugin);
13818 let index = plugin ? plugin.manager.tooltips.findIndex(t => t.create == HoverTooltipHost.create) : -1;
13819 return index > -1 ? plugin.manager.tooltipViews[index] : null;
13820 }
13821 mousemove(event) {
13822 var _a;
13823 this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() };
13824 if (this.hoverTimeout < 0)
13825 this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
13826 let { active, tooltip } = this;
13827 if (active && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
13828 let { pos } = active || this.pending, end = (_a = active === null || active === void 0 ? void 0 : active.end) !== null && _a !== void 0 ? _a : pos;
13829 if ((pos == end ? this.view.posAtCoords(this.lastMove) != pos
13830 : !isOverRange(this.view, pos, end, event.clientX, event.clientY))) {
13831 this.view.dispatch({ effects: this.setHover.of(null) });
13832 this.pending = null;
13833 }
13834 }
13835 }
13836 mouseleave(event) {
13837 clearTimeout(this.hoverTimeout);
13838 this.hoverTimeout = -1;
13839 let { active } = this;
13840 if (active) {
13841 let { tooltip } = this;
13842 let inTooltip = tooltip && tooltip.dom.contains(event.relatedTarget);
13843 if (!inTooltip)
13844 this.view.dispatch({ effects: this.setHover.of(null) });
13845 else
13846 this.watchTooltipLeave(tooltip.dom);
13847 }
13848 }
13849 watchTooltipLeave(tooltip) {
13850 let watch = (event) => {
13851 tooltip.removeEventListener("mouseleave", watch);
13852 if (this.active && !this.view.dom.contains(event.relatedTarget))
13853 this.view.dispatch({ effects: this.setHover.of(null) });
13854 };
13855 tooltip.addEventListener("mouseleave", watch);
13856 }
13857 destroy() {
13858 clearTimeout(this.hoverTimeout);
13859 this.view.dom.removeEventListener("mouseleave", this.mouseleave);
13860 this.view.dom.removeEventListener("mousemove", this.mousemove);
13861 }
13862 }
13863 const tooltipMargin = 4;
13864 function isInTooltip(tooltip, event) {
13865 let rect = tooltip.getBoundingClientRect();
13866 return event.clientX >= rect.left - tooltipMargin && event.clientX <= rect.right + tooltipMargin &&
13867 event.clientY >= rect.top - tooltipMargin && event.clientY <= rect.bottom + tooltipMargin;
13868 }
13869 function isOverRange(view, from, to, x, y, margin) {
13870 let rect = view.scrollDOM.getBoundingClientRect();
13871 let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
13872 if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y)
13873 return false;
13874 let pos = view.posAtCoords({ x, y }, false);
13875 return pos >= from && pos <= to;
13876 }
13877 /**
13878 Set up a hover tooltip, which shows up when the pointer hovers
13879 over ranges of text. The callback is called when the mouse hovers
13880 over the document text. It should, if there is a tooltip
13881 associated with position `pos`, return the tooltip description
13882 (either directly or in a promise). The `side` argument indicates
13883 on which side of the position the pointer is—it will be -1 if the
13884 pointer is before the position, 1 if after the position.
13885
13886 Note that all hover tooltips are hosted within a single tooltip
13887 container element. This allows multiple tooltips over the same
13888 range to be "merged" together without overlapping.
13889 */
13890 function hoverTooltip(source, options = {}) {
13891 let setHover = StateEffect.define();
13892 let hoverState = StateField.define({
13893 create() { return null; },
13894 update(value, tr) {
13895 if (value && (options.hideOnChange && (tr.docChanged || tr.selection) ||
13896 options.hideOn && options.hideOn(tr, value)))
13897 return null;
13898 if (value && tr.docChanged) {
13899 let newPos = tr.changes.mapPos(value.pos, -1, exports.MapMode.TrackDel);
13900 if (newPos == null)
13901 return null;
13902 let copy = Object.assign(Object.create(null), value);
13903 copy.pos = newPos;
13904 if (value.end != null)
13905 copy.end = tr.changes.mapPos(value.end);
13906 value = copy;
13907 }
13908 for (let effect of tr.effects) {
13909 if (effect.is(setHover))
13910 value = effect.value;
13911 if (effect.is(closeHoverTooltipEffect))
13912 value = null;
13913 }
13914 return value;
13915 },
13916 provide: f => showHoverTooltip.from(f)
13917 });
13918 return [
13919 hoverState,
13920 ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300 /* Hover.Time */)),
13921 showHoverTooltipHost
13922 ];
13923 }
13924 /**
13925 Get the active tooltip view for a given tooltip, if available.
13926 */
13927 function getTooltip(view, tooltip) {
13928 let plugin = view.plugin(tooltipPlugin);
13929 if (!plugin)
13930 return null;
13931 let found = plugin.manager.tooltips.indexOf(tooltip);
13932 return found < 0 ? null : plugin.manager.tooltipViews[found];
13933 }
13934 /**
13935 Returns true if any hover tooltips are currently active.
13936 */
13937 function hasHoverTooltips(state) {
13938 return state.facet(showHoverTooltip).some(x => x);
13939 }
13940 const closeHoverTooltipEffect = /*@__PURE__*/StateEffect.define();
13941 /**
13942 Transaction effect that closes all hover tooltips.
13943 */
13944 const closeHoverTooltips = /*@__PURE__*/closeHoverTooltipEffect.of(null);
13945 /**
13946 Tell the tooltip extension to recompute the position of the active
13947 tooltips. This can be useful when something happens (such as a
13948 re-positioning or CSS change affecting the editor) that could
13949 invalidate the existing tooltip positions.
13950 */
13951 function repositionTooltips(view) {
13952 let plugin = view.plugin(tooltipPlugin);
13953 if (plugin)
13954 plugin.maybeMeasure();
13955 }
13956
13957 const panelConfig = /*@__PURE__*/Facet.define({
13958 combine(configs) {
13959 let topContainer, bottomContainer;
13960 for (let c of configs) {
13961 topContainer = topContainer || c.topContainer;
13962 bottomContainer = bottomContainer || c.bottomContainer;
13963 }
13964 return { topContainer, bottomContainer };
13965 }
13966 });
13967 /**
13968 Configures the panel-managing extension.
13969 */
13970 function panels(config) {
13971 return config ? [panelConfig.of(config)] : [];
13972 }
13973 /**
13974 Get the active panel created by the given constructor, if any.
13975 This can be useful when you need access to your panels' DOM
13976 structure.
13977 */
13978 function getPanel(view, panel) {
13979 let plugin = view.plugin(panelPlugin);
13980 let index = plugin ? plugin.specs.indexOf(panel) : -1;
13981 return index > -1 ? plugin.panels[index] : null;
13982 }
13983 const panelPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
13984 constructor(view) {
13985 this.input = view.state.facet(showPanel);
13986 this.specs = this.input.filter(s => s);
13987 this.panels = this.specs.map(spec => spec(view));
13988 let conf = view.state.facet(panelConfig);
13989 this.top = new PanelGroup(view, true, conf.topContainer);
13990 this.bottom = new PanelGroup(view, false, conf.bottomContainer);
13991 this.top.sync(this.panels.filter(p => p.top));
13992 this.bottom.sync(this.panels.filter(p => !p.top));
13993 for (let p of this.panels) {
13994 p.dom.classList.add("cm-panel");
13995 if (p.mount)
13996 p.mount();
13997 }
13998 }
13999 update(update) {
14000 let conf = update.state.facet(panelConfig);
14001 if (this.top.container != conf.topContainer) {
14002 this.top.sync([]);
14003 this.top = new PanelGroup(update.view, true, conf.topContainer);
14004 }
14005 if (this.bottom.container != conf.bottomContainer) {
14006 this.bottom.sync([]);
14007 this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
14008 }
14009 this.top.syncClasses();
14010 this.bottom.syncClasses();
14011 let input = update.state.facet(showPanel);
14012 if (input != this.input) {
14013 let specs = input.filter(x => x);
14014 let panels = [], top = [], bottom = [], mount = [];
14015 for (let spec of specs) {
14016 let known = this.specs.indexOf(spec), panel;
14017 if (known < 0) {
14018 panel = spec(update.view);
14019 mount.push(panel);
14020 }
14021 else {
14022 panel = this.panels[known];
14023 if (panel.update)
14024 panel.update(update);
14025 }
14026 panels.push(panel);
14027 (panel.top ? top : bottom).push(panel);
14028 }
14029 this.specs = specs;
14030 this.panels = panels;
14031 this.top.sync(top);
14032 this.bottom.sync(bottom);
14033 for (let p of mount) {
14034 p.dom.classList.add("cm-panel");
14035 if (p.mount)
14036 p.mount();
14037 }
14038 }
14039 else {
14040 for (let p of this.panels)
14041 if (p.update)
14042 p.update(update);
14043 }
14044 }
14045 destroy() {
14046 this.top.sync([]);
14047 this.bottom.sync([]);
14048 }
14049 }, {
14050 provide: plugin => EditorView.scrollMargins.of(view => {
14051 let value = view.plugin(plugin);
14052 return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() };
14053 })
14054 });
14055 class PanelGroup {
14056 constructor(view, top, container) {
14057 this.view = view;
14058 this.top = top;
14059 this.container = container;
14060 this.dom = undefined;
14061 this.classes = "";
14062 this.panels = [];
14063 this.syncClasses();
14064 }
14065 sync(panels) {
14066 for (let p of this.panels)
14067 if (p.destroy && panels.indexOf(p) < 0)
14068 p.destroy();
14069 this.panels = panels;
14070 this.syncDOM();
14071 }
14072 syncDOM() {
14073 if (this.panels.length == 0) {
14074 if (this.dom) {
14075 this.dom.remove();
14076 this.dom = undefined;
14077 }
14078 return;
14079 }
14080 if (!this.dom) {
14081 this.dom = document.createElement("div");
14082 this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
14083 this.dom.style[this.top ? "top" : "bottom"] = "0";
14084 let parent = this.container || this.view.dom;
14085 parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
14086 }
14087 let curDOM = this.dom.firstChild;
14088 for (let panel of this.panels) {
14089 if (panel.dom.parentNode == this.dom) {
14090 while (curDOM != panel.dom)
14091 curDOM = rm(curDOM);
14092 curDOM = curDOM.nextSibling;
14093 }
14094 else {
14095 this.dom.insertBefore(panel.dom, curDOM);
14096 }
14097 }
14098 while (curDOM)
14099 curDOM = rm(curDOM);
14100 }
14101 scrollMargin() {
14102 return !this.dom || this.container ? 0
14103 : Math.max(0, this.top ?
14104 this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) :
14105 Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
14106 }
14107 syncClasses() {
14108 if (!this.container || this.classes == this.view.themeClasses)
14109 return;
14110 for (let cls of this.classes.split(" "))
14111 if (cls)
14112 this.container.classList.remove(cls);
14113 for (let cls of (this.classes = this.view.themeClasses).split(" "))
14114 if (cls)
14115 this.container.classList.add(cls);
14116 }
14117 }
14118 function rm(node) {
14119 let next = node.nextSibling;
14120 node.remove();
14121 return next;
14122 }
14123 /**
14124 Opening a panel is done by providing a constructor function for
14125 the panel through this facet. (The panel is closed again when its
14126 constructor is no longer provided.) Values of `null` are ignored.
14127 */
14128 const showPanel = /*@__PURE__*/Facet.define({
14129 enables: panelPlugin
14130 });
14131
14132 /**
14133 A gutter marker represents a bit of information attached to a line
14134 in a specific gutter. Your own custom markers have to extend this
14135 class.
14136 */
14137 class GutterMarker extends RangeValue {
14138 /**
14139 @internal
14140 */
14141 compare(other) {
14142 return this == other || this.constructor == other.constructor && this.eq(other);
14143 }
14144 /**
14145 Compare this marker to another marker of the same type.
14146 */
14147 eq(other) { return false; }
14148 /**
14149 Called if the marker has a `toDOM` method and its representation
14150 was removed from a gutter.
14151 */
14152 destroy(dom) { }
14153 }
14154 GutterMarker.prototype.elementClass = "";
14155 GutterMarker.prototype.toDOM = undefined;
14156 GutterMarker.prototype.mapMode = exports.MapMode.TrackBefore;
14157 GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
14158 GutterMarker.prototype.point = true;
14159 /**
14160 Facet used to add a class to all gutter elements for a given line.
14161 Markers given to this facet should _only_ define an
14162 [`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a
14163 [`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear
14164 in all gutters for the line).
14165 */
14166 const gutterLineClass = /*@__PURE__*/Facet.define();
14167 const defaults = {
14168 class: "",
14169 renderEmptyElements: false,
14170 elementStyle: "",
14171 markers: () => RangeSet.empty,
14172 lineMarker: () => null,
14173 widgetMarker: () => null,
14174 lineMarkerChange: null,
14175 initialSpacer: null,
14176 updateSpacer: null,
14177 domEventHandlers: {}
14178 };
14179 const activeGutters = /*@__PURE__*/Facet.define();
14180 /**
14181 Define an editor gutter. The order in which the gutters appear is
14182 determined by their extension priority.
14183 */
14184 function gutter(config) {
14185 return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config))];
14186 }
14187 const unfixGutters = /*@__PURE__*/Facet.define({
14188 combine: values => values.some(x => x)
14189 });
14190 /**
14191 The gutter-drawing plugin is automatically enabled when you add a
14192 gutter, but you can use this function to explicitly configure it.
14193
14194 Unless `fixed` is explicitly set to `false`, the gutters are
14195 fixed, meaning they don't scroll along with the content
14196 horizontally (except on Internet Explorer, which doesn't support
14197 CSS [`position:
14198 sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
14199 */
14200 function gutters(config) {
14201 let result = [
14202 gutterView,
14203 ];
14204 if (config && config.fixed === false)
14205 result.push(unfixGutters.of(true));
14206 return result;
14207 }
14208 const gutterView = /*@__PURE__*/ViewPlugin.fromClass(class {
14209 constructor(view) {
14210 this.view = view;
14211 this.prevViewport = view.viewport;
14212 this.dom = document.createElement("div");
14213 this.dom.className = "cm-gutters";
14214 this.dom.setAttribute("aria-hidden", "true");
14215 this.dom.style.minHeight = (this.view.contentHeight / this.view.scaleY) + "px";
14216 this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
14217 for (let gutter of this.gutters)
14218 this.dom.appendChild(gutter.dom);
14219 this.fixed = !view.state.facet(unfixGutters);
14220 if (this.fixed) {
14221 // FIXME IE11 fallback, which doesn't support position: sticky,
14222 // by using position: relative + event handlers that realign the
14223 // gutter (or just force fixed=false on IE11?)
14224 this.dom.style.position = "sticky";
14225 }
14226 this.syncGutters(false);
14227 view.scrollDOM.insertBefore(this.dom, view.contentDOM);
14228 }
14229 update(update) {
14230 if (this.updateGutters(update)) {
14231 // Detach during sync when the viewport changed significantly
14232 // (such as during scrolling), since for large updates that is
14233 // faster.
14234 let vpA = this.prevViewport, vpB = update.view.viewport;
14235 let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
14236 this.syncGutters(vpOverlap < (vpB.to - vpB.from) * 0.8);
14237 }
14238 if (update.geometryChanged)
14239 this.dom.style.minHeight = this.view.contentHeight + "px";
14240 if (this.view.state.facet(unfixGutters) != !this.fixed) {
14241 this.fixed = !this.fixed;
14242 this.dom.style.position = this.fixed ? "sticky" : "";
14243 }
14244 this.prevViewport = update.view.viewport;
14245 }
14246 syncGutters(detach) {
14247 let after = this.dom.nextSibling;
14248 if (detach)
14249 this.dom.remove();
14250 let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
14251 let classSet = [];
14252 let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport, -this.view.documentPadding.top));
14253 for (let line of this.view.viewportLineBlocks) {
14254 if (classSet.length)
14255 classSet = [];
14256 if (Array.isArray(line.type)) {
14257 let first = true;
14258 for (let b of line.type) {
14259 if (b.type == exports.BlockType.Text && first) {
14260 advanceCursor(lineClasses, classSet, b.from);
14261 for (let cx of contexts)
14262 cx.line(this.view, b, classSet);
14263 first = false;
14264 }
14265 else if (b.widget) {
14266 for (let cx of contexts)
14267 cx.widget(this.view, b);
14268 }
14269 }
14270 }
14271 else if (line.type == exports.BlockType.Text) {
14272 advanceCursor(lineClasses, classSet, line.from);
14273 for (let cx of contexts)
14274 cx.line(this.view, line, classSet);
14275 }
14276 else if (line.widget) {
14277 for (let cx of contexts)
14278 cx.widget(this.view, line);
14279 }
14280 }
14281 for (let cx of contexts)
14282 cx.finish();
14283 if (detach)
14284 this.view.scrollDOM.insertBefore(this.dom, after);
14285 }
14286 updateGutters(update) {
14287 let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);
14288 let change = update.docChanged || update.heightChanged || update.viewportChanged ||
14289 !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);
14290 if (prev == cur) {
14291 for (let gutter of this.gutters)
14292 if (gutter.update(update))
14293 change = true;
14294 }
14295 else {
14296 change = true;
14297 let gutters = [];
14298 for (let conf of cur) {
14299 let known = prev.indexOf(conf);
14300 if (known < 0) {
14301 gutters.push(new SingleGutterView(this.view, conf));
14302 }
14303 else {
14304 this.gutters[known].update(update);
14305 gutters.push(this.gutters[known]);
14306 }
14307 }
14308 for (let g of this.gutters) {
14309 g.dom.remove();
14310 if (gutters.indexOf(g) < 0)
14311 g.destroy();
14312 }
14313 for (let g of gutters)
14314 this.dom.appendChild(g.dom);
14315 this.gutters = gutters;
14316 }
14317 return change;
14318 }
14319 destroy() {
14320 for (let view of this.gutters)
14321 view.destroy();
14322 this.dom.remove();
14323 }
14324 }, {
14325 provide: plugin => EditorView.scrollMargins.of(view => {
14326 let value = view.plugin(plugin);
14327 if (!value || value.gutters.length == 0 || !value.fixed)
14328 return null;
14329 return view.textDirection == exports.Direction.LTR
14330 ? { left: value.dom.offsetWidth * view.scaleX }
14331 : { right: value.dom.offsetWidth * view.scaleX };
14332 })
14333 });
14334 function asArray(val) { return (Array.isArray(val) ? val : [val]); }
14335 function advanceCursor(cursor, collect, pos) {
14336 while (cursor.value && cursor.from <= pos) {
14337 if (cursor.from == pos)
14338 collect.push(cursor.value);
14339 cursor.next();
14340 }
14341 }
14342 class UpdateContext {
14343 constructor(gutter, viewport, height) {
14344 this.gutter = gutter;
14345 this.height = height;
14346 this.i = 0;
14347 this.cursor = RangeSet.iter(gutter.markers, viewport.from);
14348 }
14349 addElement(view, block, markers) {
14350 let { gutter } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY;
14351 if (this.i == gutter.elements.length) {
14352 let newElt = new GutterElement(view, height, above, markers);
14353 gutter.elements.push(newElt);
14354 gutter.dom.appendChild(newElt.dom);
14355 }
14356 else {
14357 gutter.elements[this.i].update(view, height, above, markers);
14358 }
14359 this.height = block.bottom;
14360 this.i++;
14361 }
14362 line(view, line, extraMarkers) {
14363 let localMarkers = [];
14364 advanceCursor(this.cursor, localMarkers, line.from);
14365 if (extraMarkers.length)
14366 localMarkers = localMarkers.concat(extraMarkers);
14367 let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
14368 if (forLine)
14369 localMarkers.unshift(forLine);
14370 let gutter = this.gutter;
14371 if (localMarkers.length == 0 && !gutter.config.renderEmptyElements)
14372 return;
14373 this.addElement(view, line, localMarkers);
14374 }
14375 widget(view, block) {
14376 let marker = this.gutter.config.widgetMarker(view, block.widget, block);
14377 if (marker)
14378 this.addElement(view, block, [marker]);
14379 }
14380 finish() {
14381 let gutter = this.gutter;
14382 while (gutter.elements.length > this.i) {
14383 let last = gutter.elements.pop();
14384 gutter.dom.removeChild(last.dom);
14385 last.destroy();
14386 }
14387 }
14388 }
14389 class SingleGutterView {
14390 constructor(view, config) {
14391 this.view = view;
14392 this.config = config;
14393 this.elements = [];
14394 this.spacer = null;
14395 this.dom = document.createElement("div");
14396 this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
14397 for (let prop in config.domEventHandlers) {
14398 this.dom.addEventListener(prop, (event) => {
14399 let target = event.target, y;
14400 if (target != this.dom && this.dom.contains(target)) {
14401 while (target.parentNode != this.dom)
14402 target = target.parentNode;
14403 let rect = target.getBoundingClientRect();
14404 y = (rect.top + rect.bottom) / 2;
14405 }
14406 else {
14407 y = event.clientY;
14408 }
14409 let line = view.lineBlockAtHeight(y - view.documentTop);
14410 if (config.domEventHandlers[prop](view, line, event))
14411 event.preventDefault();
14412 });
14413 }
14414 this.markers = asArray(config.markers(view));
14415 if (config.initialSpacer) {
14416 this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]);
14417 this.dom.appendChild(this.spacer.dom);
14418 this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
14419 }
14420 }
14421 update(update) {
14422 let prevMarkers = this.markers;
14423 this.markers = asArray(this.config.markers(update.view));
14424 if (this.spacer && this.config.updateSpacer) {
14425 let updated = this.config.updateSpacer(this.spacer.markers[0], update);
14426 if (updated != this.spacer.markers[0])
14427 this.spacer.update(update.view, 0, 0, [updated]);
14428 }
14429 let vp = update.view.viewport;
14430 return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) ||
14431 (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);
14432 }
14433 destroy() {
14434 for (let elt of this.elements)
14435 elt.destroy();
14436 }
14437 }
14438 class GutterElement {
14439 constructor(view, height, above, markers) {
14440 this.height = -1;
14441 this.above = 0;
14442 this.markers = [];
14443 this.dom = document.createElement("div");
14444 this.dom.className = "cm-gutterElement";
14445 this.update(view, height, above, markers);
14446 }
14447 update(view, height, above, markers) {
14448 if (this.height != height) {
14449 this.height = height;
14450 this.dom.style.height = height + "px";
14451 }
14452 if (this.above != above)
14453 this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
14454 if (!sameMarkers(this.markers, markers))
14455 this.setMarkers(view, markers);
14456 }
14457 setMarkers(view, markers) {
14458 let cls = "cm-gutterElement", domPos = this.dom.firstChild;
14459 for (let iNew = 0, iOld = 0;;) {
14460 let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = false;
14461 if (marker) {
14462 let c = marker.elementClass;
14463 if (c)
14464 cls += " " + c;
14465 for (let i = iOld; i < this.markers.length; i++)
14466 if (this.markers[i].compare(marker)) {
14467 skipTo = i;
14468 matched = true;
14469 break;
14470 }
14471 }
14472 else {
14473 skipTo = this.markers.length;
14474 }
14475 while (iOld < skipTo) {
14476 let next = this.markers[iOld++];
14477 if (next.toDOM) {
14478 next.destroy(domPos);
14479 let after = domPos.nextSibling;
14480 domPos.remove();
14481 domPos = after;
14482 }
14483 }
14484 if (!marker)
14485 break;
14486 if (marker.toDOM) {
14487 if (matched)
14488 domPos = domPos.nextSibling;
14489 else
14490 this.dom.insertBefore(marker.toDOM(view), domPos);
14491 }
14492 if (matched)
14493 iOld++;
14494 }
14495 this.dom.className = cls;
14496 this.markers = markers;
14497 }
14498 destroy() {
14499 this.setMarkers(null, []); // First argument not used unless creating markers
14500 }
14501 }
14502 function sameMarkers(a, b) {
14503 if (a.length != b.length)
14504 return false;
14505 for (let i = 0; i < a.length; i++)
14506 if (!a[i].compare(b[i]))
14507 return false;
14508 return true;
14509 }
14510 /**
14511 Facet used to provide markers to the line number gutter.
14512 */
14513 const lineNumberMarkers = /*@__PURE__*/Facet.define();
14514 const lineNumberConfig = /*@__PURE__*/Facet.define({
14515 combine(values) {
14516 return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
14517 domEventHandlers(a, b) {
14518 let result = Object.assign({}, a);
14519 for (let event in b) {
14520 let exists = result[event], add = b[event];
14521 result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;
14522 }
14523 return result;
14524 }
14525 });
14526 }
14527 });
14528 class NumberMarker extends GutterMarker {
14529 constructor(number) {
14530 super();
14531 this.number = number;
14532 }
14533 eq(other) { return this.number == other.number; }
14534 toDOM() { return document.createTextNode(this.number); }
14535 }
14536 function formatNumber(view, number) {
14537 return view.state.facet(lineNumberConfig).formatNumber(number, view.state);
14538 }
14539 const lineNumberGutter = /*@__PURE__*/activeGutters.compute([lineNumberConfig], state => ({
14540 class: "cm-lineNumbers",
14541 renderEmptyElements: false,
14542 markers(view) { return view.state.facet(lineNumberMarkers); },
14543 lineMarker(view, line, others) {
14544 if (others.some(m => m.toDOM))
14545 return null;
14546 return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
14547 },
14548 widgetMarker: () => null,
14549 lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),
14550 initialSpacer(view) {
14551 return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
14552 },
14553 updateSpacer(spacer, update) {
14554 let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));
14555 return max == spacer.number ? spacer : new NumberMarker(max);
14556 },
14557 domEventHandlers: state.facet(lineNumberConfig).domEventHandlers
14558 }));
14559 /**
14560 Create a line number gutter extension.
14561 */
14562 function lineNumbers(config = {}) {
14563 return [
14564 lineNumberConfig.of(config),
14565 gutters(),
14566 lineNumberGutter
14567 ];
14568 }
14569 function maxLineNumber(lines) {
14570 let last = 9;
14571 while (last < lines)
14572 last = last * 10 + 9;
14573 return last;
14574 }
14575 const activeLineGutterMarker = /*@__PURE__*/new class extends GutterMarker {
14576 constructor() {
14577 super(...arguments);
14578 this.elementClass = "cm-activeLineGutter";
14579 }
14580 };
14581 const activeLineGutterHighlighter = /*@__PURE__*/gutterLineClass.compute(["selection"], state => {
14582 let marks = [], last = -1;
14583 for (let range of state.selection.ranges) {
14584 let linePos = state.doc.lineAt(range.head).from;
14585 if (linePos > last) {
14586 last = linePos;
14587 marks.push(activeLineGutterMarker.range(linePos));
14588 }
14589 }
14590 return RangeSet.of(marks);
14591 });
14592 /**
14593 Returns an extension that adds a `cm-activeLineGutter` class to
14594 all gutter elements on the [active
14595 line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
14596 */
14597 function highlightActiveLineGutter() {
14598 return activeLineGutterHighlighter;
14599 }
14600
14601 const WhitespaceDeco = /*@__PURE__*/new Map();
14602 function getWhitespaceDeco(space) {
14603 let deco = WhitespaceDeco.get(space);
14604 if (!deco)
14605 WhitespaceDeco.set(space, deco = Decoration.mark({
14606 attributes: space === "\t" ? {
14607 class: "cm-highlightTab",
14608 } : {
14609 class: "cm-highlightSpace",
14610 "data-display": space.replace(/ /g, "·")
14611 }
14612 }));
14613 return deco;
14614 }
14615 function matcher(decorator) {
14616 return ViewPlugin.define(view => ({
14617 decorations: decorator.createDeco(view),
14618 update(u) {
14619 this.decorations = decorator.updateDeco(u, this.decorations);
14620 },
14621 }), {
14622 decorations: v => v.decorations
14623 });
14624 }
14625 const whitespaceHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({
14626 regexp: /\t| +/g,
14627 decoration: match => getWhitespaceDeco(match[0]),
14628 boundary: /\S/,
14629 }));
14630 /**
14631 Returns an extension that highlights whitespace, adding a
14632 `cm-highlightSpace` class to stretches of spaces, and a
14633 `cm-highlightTab` class to individual tab characters. By default,
14634 the former are shown as faint dots, and the latter as arrows.
14635 */
14636 function highlightWhitespace() {
14637 return whitespaceHighlighter;
14638 }
14639 const trailingHighlighter = /*@__PURE__*/matcher(/*@__PURE__*/new MatchDecorator({
14640 regexp: /\s+$/g,
14641 decoration: /*@__PURE__*/Decoration.mark({ class: "cm-trailingSpace" }),
14642 boundary: /\S/,
14643 }));
14644 /**
14645 Returns an extension that adds a `cm-trailingSpace` class to all
14646 trailing whitespace.
14647 */
14648 function highlightTrailingWhitespace() {
14649 return trailingHighlighter;
14650 }
14651
14652 /**
14653 @internal
14654 */
14655 const __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType: QueryType$1, ChangedRange, computeOrder, moveVisually };
14656
14657 /**
14658 The default maximum length of a `TreeBuffer` node.
14659 */
14660 const DefaultBufferLength = 1024;
14661 let nextPropID = 0;
14662 class Range {
14663 constructor(from, to) {
14664 this.from = from;
14665 this.to = to;
14666 }
14667 }
14668 /**
14669 Each [node type](#common.NodeType) or [individual tree](#common.Tree)
14670 can have metadata associated with it in props. Instances of this
14671 class represent prop names.
14672 */
14673 class NodeProp {
14674 /**
14675 Create a new node prop type.
14676 */
14677 constructor(config = {}) {
14678 this.id = nextPropID++;
14679 this.perNode = !!config.perNode;
14680 this.deserialize = config.deserialize || (() => {
14681 throw new Error("This node type doesn't define a deserialize function");
14682 });
14683 }
14684 /**
14685 This is meant to be used with
14686 [`NodeSet.extend`](#common.NodeSet.extend) or
14687 [`LRParser.configure`](#lr.ParserConfig.props) to compute
14688 prop values for each node type in the set. Takes a [match
14689 object](#common.NodeType^match) or function that returns undefined
14690 if the node type doesn't get this prop, and the prop's value if
14691 it does.
14692 */
14693 add(match) {
14694 if (this.perNode)
14695 throw new RangeError("Can't add per-node props to node types");
14696 if (typeof match != "function")
14697 match = NodeType.match(match);
14698 return (type) => {
14699 let result = match(type);
14700 return result === undefined ? null : [this, result];
14701 };
14702 }
14703 }
14704 /**
14705 Prop that is used to describe matching delimiters. For opening
14706 delimiters, this holds an array of node names (written as a
14707 space-separated string when declaring this prop in a grammar)
14708 for the node types of closing delimiters that match it.
14709 */
14710 NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
14711 /**
14712 The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
14713 attached to closing delimiters, holding an array of node names
14714 of types of matching opening delimiters.
14715 */
14716 NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
14717 /**
14718 Used to assign node types to groups (for example, all node
14719 types that represent an expression could be tagged with an
14720 `"Expression"` group).
14721 */
14722 NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
14723 /**
14724 Attached to nodes to indicate these should be
14725 [displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
14726 in a bidirectional text isolate, so that direction-neutral
14727 characters on their sides don't incorrectly get associated with
14728 surrounding text. You'll generally want to set this for nodes
14729 that contain arbitrary text, like strings and comments, and for
14730 nodes that appear _inside_ arbitrary text, like HTML tags. When
14731 not given a value, in a grammar declaration, defaults to
14732 `"auto"`.
14733 */
14734 NodeProp.isolate = new NodeProp({ deserialize: value => {
14735 if (value && value != "rtl" && value != "ltr" && value != "auto")
14736 throw new RangeError("Invalid value for isolate: " + value);
14737 return value || "auto";
14738 } });
14739 /**
14740 The hash of the [context](#lr.ContextTracker.constructor)
14741 that the node was parsed in, if any. Used to limit reuse of
14742 contextual nodes.
14743 */
14744 NodeProp.contextHash = new NodeProp({ perNode: true });
14745 /**
14746 The distance beyond the end of the node that the tokenizer
14747 looked ahead for any of the tokens inside the node. (The LR
14748 parser only stores this when it is larger than 25, for
14749 efficiency reasons.)
14750 */
14751 NodeProp.lookAhead = new NodeProp({ perNode: true });
14752 /**
14753 This per-node prop is used to replace a given node, or part of a
14754 node, with another tree. This is useful to include trees from
14755 different languages in mixed-language parsers.
14756 */
14757 NodeProp.mounted = new NodeProp({ perNode: true });
14758 /**
14759 A mounted tree, which can be [stored](#common.NodeProp^mounted) on
14760 a tree node to indicate that parts of its content are
14761 represented by another tree.
14762 */
14763 class MountedTree {
14764 constructor(
14765 /**
14766 The inner tree.
14767 */
14768 tree,
14769 /**
14770 If this is null, this tree replaces the entire node (it will
14771 be included in the regular iteration instead of its host
14772 node). If not, only the given ranges are considered to be
14773 covered by this tree. This is used for trees that are mixed in
14774 a way that isn't strictly hierarchical. Such mounted trees are
14775 only entered by [`resolveInner`](#common.Tree.resolveInner)
14776 and [`enter`](#common.SyntaxNode.enter).
14777 */
14778 overlay,
14779 /**
14780 The parser used to create this subtree.
14781 */
14782 parser) {
14783 this.tree = tree;
14784 this.overlay = overlay;
14785 this.parser = parser;
14786 }
14787 /**
14788 @internal
14789 */
14790 static get(tree) {
14791 return tree && tree.props && tree.props[NodeProp.mounted.id];
14792 }
14793 }
14794 const noProps = Object.create(null);
14795 /**
14796 Each node in a syntax tree has a node type associated with it.
14797 */
14798 class NodeType {
14799 /**
14800 @internal
14801 */
14802 constructor(
14803 /**
14804 The name of the node type. Not necessarily unique, but if the
14805 grammar was written properly, different node types with the
14806 same name within a node set should play the same semantic
14807 role.
14808 */
14809 name,
14810 /**
14811 @internal
14812 */
14813 props,
14814 /**
14815 The id of this node in its set. Corresponds to the term ids
14816 used in the parser.
14817 */
14818 id,
14819 /**
14820 @internal
14821 */
14822 flags = 0) {
14823 this.name = name;
14824 this.props = props;
14825 this.id = id;
14826 this.flags = flags;
14827 }
14828 /**
14829 Define a node type.
14830 */
14831 static define(spec) {
14832 let props = spec.props && spec.props.length ? Object.create(null) : noProps;
14833 let flags = (spec.top ? 1 /* NodeFlag.Top */ : 0) | (spec.skipped ? 2 /* NodeFlag.Skipped */ : 0) |
14834 (spec.error ? 4 /* NodeFlag.Error */ : 0) | (spec.name == null ? 8 /* NodeFlag.Anonymous */ : 0);
14835 let type = new NodeType(spec.name || "", props, spec.id, flags);
14836 if (spec.props)
14837 for (let src of spec.props) {
14838 if (!Array.isArray(src))
14839 src = src(type);
14840 if (src) {
14841 if (src[0].perNode)
14842 throw new RangeError("Can't store a per-node prop on a node type");
14843 props[src[0].id] = src[1];
14844 }
14845 }
14846 return type;
14847 }
14848 /**
14849 Retrieves a node prop for this type. Will return `undefined` if
14850 the prop isn't present on this node.
14851 */
14852 prop(prop) { return this.props[prop.id]; }
14853 /**
14854 True when this is the top node of a grammar.
14855 */
14856 get isTop() { return (this.flags & 1 /* NodeFlag.Top */) > 0; }
14857 /**
14858 True when this node is produced by a skip rule.
14859 */
14860 get isSkipped() { return (this.flags & 2 /* NodeFlag.Skipped */) > 0; }
14861 /**
14862 Indicates whether this is an error node.
14863 */
14864 get isError() { return (this.flags & 4 /* NodeFlag.Error */) > 0; }
14865 /**
14866 When true, this node type doesn't correspond to a user-declared
14867 named node, for example because it is used to cache repetition.
14868 */
14869 get isAnonymous() { return (this.flags & 8 /* NodeFlag.Anonymous */) > 0; }
14870 /**
14871 Returns true when this node's name or one of its
14872 [groups](#common.NodeProp^group) matches the given string.
14873 */
14874 is(name) {
14875 if (typeof name == 'string') {
14876 if (this.name == name)
14877 return true;
14878 let group = this.prop(NodeProp.group);
14879 return group ? group.indexOf(name) > -1 : false;
14880 }
14881 return this.id == name;
14882 }
14883 /**
14884 Create a function from node types to arbitrary values by
14885 specifying an object whose property names are node or
14886 [group](#common.NodeProp^group) names. Often useful with
14887 [`NodeProp.add`](#common.NodeProp.add). You can put multiple
14888 names, separated by spaces, in a single property name to map
14889 multiple node names to a single value.
14890 */
14891 static match(map) {
14892 let direct = Object.create(null);
14893 for (let prop in map)
14894 for (let name of prop.split(" "))
14895 direct[name] = map[prop];
14896 return (node) => {
14897 for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
14898 let found = direct[i < 0 ? node.name : groups[i]];
14899 if (found)
14900 return found;
14901 }
14902 };
14903 }
14904 }
14905 /**
14906 An empty dummy node type to use when no actual type is available.
14907 */
14908 NodeType.none = new NodeType("", Object.create(null), 0, 8 /* NodeFlag.Anonymous */);
14909 /**
14910 A node set holds a collection of node types. It is used to
14911 compactly represent trees by storing their type ids, rather than a
14912 full pointer to the type object, in a numeric array. Each parser
14913 [has](#lr.LRParser.nodeSet) a node set, and [tree
14914 buffers](#common.TreeBuffer) can only store collections of nodes
14915 from the same set. A set can have a maximum of 2**16 (65536) node
14916 types in it, so that the ids fit into 16-bit typed array slots.
14917 */
14918 class NodeSet {
14919 /**
14920 Create a set with the given types. The `id` property of each
14921 type should correspond to its position within the array.
14922 */
14923 constructor(
14924 /**
14925 The node types in this set, by id.
14926 */
14927 types) {
14928 this.types = types;
14929 for (let i = 0; i < types.length; i++)
14930 if (types[i].id != i)
14931 throw new RangeError("Node type ids should correspond to array positions when creating a node set");
14932 }
14933 /**
14934 Create a copy of this set with some node properties added. The
14935 arguments to this method can be created with
14936 [`NodeProp.add`](#common.NodeProp.add).
14937 */
14938 extend(...props) {
14939 let newTypes = [];
14940 for (let type of this.types) {
14941 let newProps = null;
14942 for (let source of props) {
14943 let add = source(type);
14944 if (add) {
14945 if (!newProps)
14946 newProps = Object.assign({}, type.props);
14947 newProps[add[0].id] = add[1];
14948 }
14949 }
14950 newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
14951 }
14952 return new NodeSet(newTypes);
14953 }
14954 }
14955 const CachedNode = new WeakMap(), CachedInnerNode = new WeakMap();
14956 /**
14957 Options that control iteration. Can be combined with the `|`
14958 operator to enable multiple ones.
14959 */
14960 var IterMode;
14961 (function (IterMode) {
14962 /**
14963 When enabled, iteration will only visit [`Tree`](#common.Tree)
14964 objects, not nodes packed into
14965 [`TreeBuffer`](#common.TreeBuffer)s.
14966 */
14967 IterMode[IterMode["ExcludeBuffers"] = 1] = "ExcludeBuffers";
14968 /**
14969 Enable this to make iteration include anonymous nodes (such as
14970 the nodes that wrap repeated grammar constructs into a balanced
14971 tree).
14972 */
14973 IterMode[IterMode["IncludeAnonymous"] = 2] = "IncludeAnonymous";
14974 /**
14975 By default, regular [mounted](#common.NodeProp^mounted) nodes
14976 replace their base node in iteration. Enable this to ignore them
14977 instead.
14978 */
14979 IterMode[IterMode["IgnoreMounts"] = 4] = "IgnoreMounts";
14980 /**
14981 This option only applies in
14982 [`enter`](#common.SyntaxNode.enter)-style methods. It tells the
14983 library to not enter mounted overlays if one covers the given
14984 position.
14985 */
14986 IterMode[IterMode["IgnoreOverlays"] = 8] = "IgnoreOverlays";
14987 })(IterMode || (IterMode = {}));
14988 /**
14989 A piece of syntax tree. There are two ways to approach these
14990 trees: the way they are actually stored in memory, and the
14991 convenient way.
14992
14993 Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
14994 objects. By packing detail information into `TreeBuffer` leaf
14995 nodes, the representation is made a lot more memory-efficient.
14996
14997 However, when you want to actually work with tree nodes, this
14998 representation is very awkward, so most client code will want to
14999 use the [`TreeCursor`](#common.TreeCursor) or
15000 [`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
15001 a view on some part of this data structure, and can be used to
15002 move around to adjacent nodes.
15003 */
15004 class Tree {
15005 /**
15006 Construct a new tree. See also [`Tree.build`](#common.Tree^build).
15007 */
15008 constructor(
15009 /**
15010 The type of the top node.
15011 */
15012 type,
15013 /**
15014 This node's child nodes.
15015 */
15016 children,
15017 /**
15018 The positions (offsets relative to the start of this tree) of
15019 the children.
15020 */
15021 positions,
15022 /**
15023 The total length of this tree
15024 */
15025 length,
15026 /**
15027 Per-node [node props](#common.NodeProp) to associate with this node.
15028 */
15029 props) {
15030 this.type = type;
15031 this.children = children;
15032 this.positions = positions;
15033 this.length = length;
15034 /**
15035 @internal
15036 */
15037 this.props = null;
15038 if (props && props.length) {
15039 this.props = Object.create(null);
15040 for (let [prop, value] of props)
15041 this.props[typeof prop == "number" ? prop : prop.id] = value;
15042 }
15043 }
15044 /**
15045 @internal
15046 */
15047 toString() {
15048 let mounted = MountedTree.get(this);
15049 if (mounted && !mounted.overlay)
15050 return mounted.tree.toString();
15051 let children = "";
15052 for (let ch of this.children) {
15053 let str = ch.toString();
15054 if (str) {
15055 if (children)
15056 children += ",";
15057 children += str;
15058 }
15059 }
15060 return !this.type.name ? children :
15061 (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
15062 (children.length ? "(" + children + ")" : "");
15063 }
15064 /**
15065 Get a [tree cursor](#common.TreeCursor) positioned at the top of
15066 the tree. Mode can be used to [control](#common.IterMode) which
15067 nodes the cursor visits.
15068 */
15069 cursor(mode = 0) {
15070 return new TreeCursor(this.topNode, mode);
15071 }
15072 /**
15073 Get a [tree cursor](#common.TreeCursor) pointing into this tree
15074 at the given position and side (see
15075 [`moveTo`](#common.TreeCursor.moveTo).
15076 */
15077 cursorAt(pos, side = 0, mode = 0) {
15078 let scope = CachedNode.get(this) || this.topNode;
15079 let cursor = new TreeCursor(scope);
15080 cursor.moveTo(pos, side);
15081 CachedNode.set(this, cursor._tree);
15082 return cursor;
15083 }
15084 /**
15085 Get a [syntax node](#common.SyntaxNode) object for the top of the
15086 tree.
15087 */
15088 get topNode() {
15089 return new TreeNode(this, 0, 0, null);
15090 }
15091 /**
15092 Get the [syntax node](#common.SyntaxNode) at the given position.
15093 If `side` is -1, this will move into nodes that end at the
15094 position. If 1, it'll move into nodes that start at the
15095 position. With 0, it'll only enter nodes that cover the position
15096 from both sides.
15097
15098 Note that this will not enter
15099 [overlays](#common.MountedTree.overlay), and you often want
15100 [`resolveInner`](#common.Tree.resolveInner) instead.
15101 */
15102 resolve(pos, side = 0) {
15103 let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
15104 CachedNode.set(this, node);
15105 return node;
15106 }
15107 /**
15108 Like [`resolve`](#common.Tree.resolve), but will enter
15109 [overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
15110 pointing into the innermost overlaid tree at the given position
15111 (with parent links going through all parent structure, including
15112 the host trees).
15113 */
15114 resolveInner(pos, side = 0) {
15115 let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
15116 CachedInnerNode.set(this, node);
15117 return node;
15118 }
15119 /**
15120 In some situations, it can be useful to iterate through all
15121 nodes around a position, including those in overlays that don't
15122 directly cover the position. This method gives you an iterator
15123 that will produce all nodes, from small to big, around the given
15124 position.
15125 */
15126 resolveStack(pos, side = 0) {
15127 return stackIterator(this, pos, side);
15128 }
15129 /**
15130 Iterate over the tree and its children, calling `enter` for any
15131 node that touches the `from`/`to` region (if given) before
15132 running over such a node's children, and `leave` (if given) when
15133 leaving the node. When `enter` returns `false`, that node will
15134 not have its children iterated over (or `leave` called).
15135 */
15136 iterate(spec) {
15137 let { enter, leave, from = 0, to = this.length } = spec;
15138 let mode = spec.mode || 0, anon = (mode & IterMode.IncludeAnonymous) > 0;
15139 for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
15140 let entered = false;
15141 if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
15142 if (c.firstChild())
15143 continue;
15144 entered = true;
15145 }
15146 for (;;) {
15147 if (entered && leave && (anon || !c.type.isAnonymous))
15148 leave(c);
15149 if (c.nextSibling())
15150 break;
15151 if (!c.parent())
15152 return;
15153 entered = true;
15154 }
15155 }
15156 }
15157 /**
15158 Get the value of the given [node prop](#common.NodeProp) for this
15159 node. Works with both per-node and per-type props.
15160 */
15161 prop(prop) {
15162 return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : undefined;
15163 }
15164 /**
15165 Returns the node's [per-node props](#common.NodeProp.perNode) in a
15166 format that can be passed to the [`Tree`](#common.Tree)
15167 constructor.
15168 */
15169 get propValues() {
15170 let result = [];
15171 if (this.props)
15172 for (let id in this.props)
15173 result.push([+id, this.props[id]]);
15174 return result;
15175 }
15176 /**
15177 Balance the direct children of this tree, producing a copy of
15178 which may have children grouped into subtrees with type
15179 [`NodeType.none`](#common.NodeType^none).
15180 */
15181 balance(config = {}) {
15182 return this.children.length <= 8 /* Balance.BranchFactor */ ? this :
15183 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)));
15184 }
15185 /**
15186 Build a tree from a postfix-ordered buffer of node information,
15187 or a cursor over such a buffer.
15188 */
15189 static build(data) { return buildTree(data); }
15190 }
15191 /**
15192 The empty tree
15193 */
15194 Tree.empty = new Tree(NodeType.none, [], [], 0);
15195 class FlatBufferCursor {
15196 constructor(buffer, index) {
15197 this.buffer = buffer;
15198 this.index = index;
15199 }
15200 get id() { return this.buffer[this.index - 4]; }
15201 get start() { return this.buffer[this.index - 3]; }
15202 get end() { return this.buffer[this.index - 2]; }
15203 get size() { return this.buffer[this.index - 1]; }
15204 get pos() { return this.index; }
15205 next() { this.index -= 4; }
15206 fork() { return new FlatBufferCursor(this.buffer, this.index); }
15207 }
15208 /**
15209 Tree buffers contain (type, start, end, endIndex) quads for each
15210 node. In such a buffer, nodes are stored in prefix order (parents
15211 before children, with the endIndex of the parent indicating which
15212 children belong to it).
15213 */
15214 class TreeBuffer {
15215 /**
15216 Create a tree buffer.
15217 */
15218 constructor(
15219 /**
15220 The buffer's content.
15221 */
15222 buffer,
15223 /**
15224 The total length of the group of nodes in the buffer.
15225 */
15226 length,
15227 /**
15228 The node set used in this buffer.
15229 */
15230 set) {
15231 this.buffer = buffer;
15232 this.length = length;
15233 this.set = set;
15234 }
15235 /**
15236 @internal
15237 */
15238 get type() { return NodeType.none; }
15239 /**
15240 @internal
15241 */
15242 toString() {
15243 let result = [];
15244 for (let index = 0; index < this.buffer.length;) {
15245 result.push(this.childString(index));
15246 index = this.buffer[index + 3];
15247 }
15248 return result.join(",");
15249 }
15250 /**
15251 @internal
15252 */
15253 childString(index) {
15254 let id = this.buffer[index], endIndex = this.buffer[index + 3];
15255 let type = this.set.types[id], result = type.name;
15256 if (/\W/.test(result) && !type.isError)
15257 result = JSON.stringify(result);
15258 index += 4;
15259 if (endIndex == index)
15260 return result;
15261 let children = [];
15262 while (index < endIndex) {
15263 children.push(this.childString(index));
15264 index = this.buffer[index + 3];
15265 }
15266 return result + "(" + children.join(",") + ")";
15267 }
15268 /**
15269 @internal
15270 */
15271 findChild(startIndex, endIndex, dir, pos, side) {
15272 let { buffer } = this, pick = -1;
15273 for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
15274 if (checkSide(side, pos, buffer[i + 1], buffer[i + 2])) {
15275 pick = i;
15276 if (dir > 0)
15277 break;
15278 }
15279 }
15280 return pick;
15281 }
15282 /**
15283 @internal
15284 */
15285 slice(startI, endI, from) {
15286 let b = this.buffer;
15287 let copy = new Uint16Array(endI - startI), len = 0;
15288 for (let i = startI, j = 0; i < endI;) {
15289 copy[j++] = b[i++];
15290 copy[j++] = b[i++] - from;
15291 let to = copy[j++] = b[i++] - from;
15292 copy[j++] = b[i++] - startI;
15293 len = Math.max(len, to);
15294 }
15295 return new TreeBuffer(copy, len, this.set);
15296 }
15297 }
15298 function checkSide(side, pos, from, to) {
15299 switch (side) {
15300 case -2 /* Side.Before */: return from < pos;
15301 case -1 /* Side.AtOrBefore */: return to >= pos && from < pos;
15302 case 0 /* Side.Around */: return from < pos && to > pos;
15303 case 1 /* Side.AtOrAfter */: return from <= pos && to > pos;
15304 case 2 /* Side.After */: return to > pos;
15305 case 4 /* Side.DontCare */: return true;
15306 }
15307 }
15308 function resolveNode(node, pos, side, overlays) {
15309 var _a;
15310 // Move up to a node that actually holds the position, if possible
15311 while (node.from == node.to ||
15312 (side < 1 ? node.from >= pos : node.from > pos) ||
15313 (side > -1 ? node.to <= pos : node.to < pos)) {
15314 let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
15315 if (!parent)
15316 return node;
15317 node = parent;
15318 }
15319 let mode = overlays ? 0 : IterMode.IgnoreOverlays;
15320 // Must go up out of overlays when those do not overlap with pos
15321 if (overlays)
15322 for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) {
15323 if (scan instanceof TreeNode && scan.index < 0 && ((_a = parent.enter(pos, side, mode)) === null || _a === void 0 ? void 0 : _a.from) != scan.from)
15324 node = parent;
15325 }
15326 for (;;) {
15327 let inner = node.enter(pos, side, mode);
15328 if (!inner)
15329 return node;
15330 node = inner;
15331 }
15332 }
15333 class BaseNode {
15334 cursor(mode = 0) { return new TreeCursor(this, mode); }
15335 getChild(type, before = null, after = null) {
15336 let r = getChildren(this, type, before, after);
15337 return r.length ? r[0] : null;
15338 }
15339 getChildren(type, before = null, after = null) {
15340 return getChildren(this, type, before, after);
15341 }
15342 resolve(pos, side = 0) {
15343 return resolveNode(this, pos, side, false);
15344 }
15345 resolveInner(pos, side = 0) {
15346 return resolveNode(this, pos, side, true);
15347 }
15348 matchContext(context) {
15349 return matchNodeContext(this, context);
15350 }
15351 enterUnfinishedNodesBefore(pos) {
15352 let scan = this.childBefore(pos), node = this;
15353 while (scan) {
15354 let last = scan.lastChild;
15355 if (!last || last.to != scan.to)
15356 break;
15357 if (last.type.isError && last.from == last.to) {
15358 node = scan;
15359 scan = last.prevSibling;
15360 }
15361 else {
15362 scan = last;
15363 }
15364 }
15365 return node;
15366 }
15367 get node() { return this; }
15368 get next() { return this.parent; }
15369 }
15370 class TreeNode extends BaseNode {
15371 constructor(_tree, from,
15372 // Index in parent node, set to -1 if the node is not a direct child of _parent.node (overlay)
15373 index, _parent) {
15374 super();
15375 this._tree = _tree;
15376 this.from = from;
15377 this.index = index;
15378 this._parent = _parent;
15379 }
15380 get type() { return this._tree.type; }
15381 get name() { return this._tree.type.name; }
15382 get to() { return this.from + this._tree.length; }
15383 nextChild(i, dir, pos, side, mode = 0) {
15384 for (let parent = this;;) {
15385 for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i != e; i += dir) {
15386 let next = children[i], start = positions[i] + parent.from;
15387 if (!checkSide(side, pos, start, start + next.length))
15388 continue;
15389 if (next instanceof TreeBuffer) {
15390 if (mode & IterMode.ExcludeBuffers)
15391 continue;
15392 let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
15393 if (index > -1)
15394 return new BufferNode(new BufferContext(parent, next, i, start), null, index);
15395 }
15396 else if ((mode & IterMode.IncludeAnonymous) || (!next.type.isAnonymous || hasChild(next))) {
15397 let mounted;
15398 if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay)
15399 return new TreeNode(mounted.tree, start, i, parent);
15400 let inner = new TreeNode(next, start, i, parent);
15401 return (mode & IterMode.IncludeAnonymous) || !inner.type.isAnonymous ? inner
15402 : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
15403 }
15404 }
15405 if ((mode & IterMode.IncludeAnonymous) || !parent.type.isAnonymous)
15406 return null;
15407 if (parent.index >= 0)
15408 i = parent.index + dir;
15409 else
15410 i = dir < 0 ? -1 : parent._parent._tree.children.length;
15411 parent = parent._parent;
15412 if (!parent)
15413 return null;
15414 }
15415 }
15416 get firstChild() { return this.nextChild(0, 1, 0, 4 /* Side.DontCare */); }
15417 get lastChild() { return this.nextChild(this._tree.children.length - 1, -1, 0, 4 /* Side.DontCare */); }
15418 childAfter(pos) { return this.nextChild(0, 1, pos, 2 /* Side.After */); }
15419 childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2 /* Side.Before */); }
15420 enter(pos, side, mode = 0) {
15421 let mounted;
15422 if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
15423 let rPos = pos - this.from;
15424 for (let { from, to } of mounted.overlay) {
15425 if ((side > 0 ? from <= rPos : from < rPos) &&
15426 (side < 0 ? to >= rPos : to > rPos))
15427 return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
15428 }
15429 }
15430 return this.nextChild(0, 1, pos, side, mode);
15431 }
15432 nextSignificantParent() {
15433 let val = this;
15434 while (val.type.isAnonymous && val._parent)
15435 val = val._parent;
15436 return val;
15437 }
15438 get parent() {
15439 return this._parent ? this._parent.nextSignificantParent() : null;
15440 }
15441 get nextSibling() {
15442 return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4 /* Side.DontCare */) : null;
15443 }
15444 get prevSibling() {
15445 return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4 /* Side.DontCare */) : null;
15446 }
15447 get tree() { return this._tree; }
15448 toTree() { return this._tree; }
15449 /**
15450 @internal
15451 */
15452 toString() { return this._tree.toString(); }
15453 }
15454 function getChildren(node, type, before, after) {
15455 let cur = node.cursor(), result = [];
15456 if (!cur.firstChild())
15457 return result;
15458 if (before != null)
15459 while (!cur.type.is(before))
15460 if (!cur.nextSibling())
15461 return result;
15462 for (;;) {
15463 if (after != null && cur.type.is(after))
15464 return result;
15465 if (cur.type.is(type))
15466 result.push(cur.node);
15467 if (!cur.nextSibling())
15468 return after == null ? result : [];
15469 }
15470 }
15471 function matchNodeContext(node, context, i = context.length - 1) {
15472 for (let p = node.parent; i >= 0; p = p.parent) {
15473 if (!p)
15474 return false;
15475 if (!p.type.isAnonymous) {
15476 if (context[i] && context[i] != p.name)
15477 return false;
15478 i--;
15479 }
15480 }
15481 return true;
15482 }
15483 class BufferContext {
15484 constructor(parent, buffer, index, start) {
15485 this.parent = parent;
15486 this.buffer = buffer;
15487 this.index = index;
15488 this.start = start;
15489 }
15490 }
15491 class BufferNode extends BaseNode {
15492 get name() { return this.type.name; }
15493 get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
15494 get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
15495 constructor(context, _parent, index) {
15496 super();
15497 this.context = context;
15498 this._parent = _parent;
15499 this.index = index;
15500 this.type = context.buffer.set.types[context.buffer.buffer[index]];
15501 }
15502 child(dir, pos, side) {
15503 let { buffer } = this.context;
15504 let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
15505 return index < 0 ? null : new BufferNode(this.context, this, index);
15506 }
15507 get firstChild() { return this.child(1, 0, 4 /* Side.DontCare */); }
15508 get lastChild() { return this.child(-1, 0, 4 /* Side.DontCare */); }
15509 childAfter(pos) { return this.child(1, pos, 2 /* Side.After */); }
15510 childBefore(pos) { return this.child(-1, pos, -2 /* Side.Before */); }
15511 enter(pos, side, mode = 0) {
15512 if (mode & IterMode.ExcludeBuffers)
15513 return null;
15514 let { buffer } = this.context;
15515 let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
15516 return index < 0 ? null : new BufferNode(this.context, this, index);
15517 }
15518 get parent() {
15519 return this._parent || this.context.parent.nextSignificantParent();
15520 }
15521 externalSibling(dir) {
15522 return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4 /* Side.DontCare */);
15523 }
15524 get nextSibling() {
15525 let { buffer } = this.context;
15526 let after = buffer.buffer[this.index + 3];
15527 if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
15528 return new BufferNode(this.context, this._parent, after);
15529 return this.externalSibling(1);
15530 }
15531 get prevSibling() {
15532 let { buffer } = this.context;
15533 let parentStart = this._parent ? this._parent.index + 4 : 0;
15534 if (this.index == parentStart)
15535 return this.externalSibling(-1);
15536 return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
15537 }
15538 get tree() { return null; }
15539 toTree() {
15540 let children = [], positions = [];
15541 let { buffer } = this.context;
15542 let startI = this.index + 4, endI = buffer.buffer[this.index + 3];
15543 if (endI > startI) {
15544 let from = buffer.buffer[this.index + 1];
15545 children.push(buffer.slice(startI, endI, from));
15546 positions.push(0);
15547 }
15548 return new Tree(this.type, children, positions, this.to - this.from);
15549 }
15550 /**
15551 @internal
15552 */
15553 toString() { return this.context.buffer.childString(this.index); }
15554 }
15555 function iterStack(heads) {
15556 if (!heads.length)
15557 return null;
15558 let pick = 0, picked = heads[0];
15559 for (let i = 1; i < heads.length; i++) {
15560 let node = heads[i];
15561 if (node.from > picked.from || node.to < picked.to) {
15562 picked = node;
15563 pick = i;
15564 }
15565 }
15566 let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
15567 let newHeads = heads.slice();
15568 if (next)
15569 newHeads[pick] = next;
15570 else
15571 newHeads.splice(pick, 1);
15572 return new StackIterator(newHeads, picked);
15573 }
15574 class StackIterator {
15575 constructor(heads, node) {
15576 this.heads = heads;
15577 this.node = node;
15578 }
15579 get next() { return iterStack(this.heads); }
15580 }
15581 function stackIterator(tree, pos, side) {
15582 let inner = tree.resolveInner(pos, side), layers = null;
15583 for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) {
15584 if (scan.index < 0) { // This is an overlay root
15585 let parent = scan.parent;
15586 (layers || (layers = [inner])).push(parent.resolve(pos, side));
15587 scan = parent;
15588 }
15589 else {
15590 let mount = MountedTree.get(scan.tree);
15591 // Relevant overlay branching off
15592 if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
15593 let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
15594 (layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
15595 }
15596 }
15597 }
15598 return layers ? iterStack(layers) : inner;
15599 }
15600 /**
15601 A tree cursor object focuses on a given node in a syntax tree, and
15602 allows you to move to adjacent nodes.
15603 */
15604 class TreeCursor {
15605 /**
15606 Shorthand for `.type.name`.
15607 */
15608 get name() { return this.type.name; }
15609 /**
15610 @internal
15611 */
15612 constructor(node,
15613 /**
15614 @internal
15615 */
15616 mode = 0) {
15617 this.mode = mode;
15618 /**
15619 @internal
15620 */
15621 this.buffer = null;
15622 this.stack = [];
15623 /**
15624 @internal
15625 */
15626 this.index = 0;
15627 this.bufferNode = null;
15628 if (node instanceof TreeNode) {
15629 this.yieldNode(node);
15630 }
15631 else {
15632 this._tree = node.context.parent;
15633 this.buffer = node.context;
15634 for (let n = node._parent; n; n = n._parent)
15635 this.stack.unshift(n.index);
15636 this.bufferNode = node;
15637 this.yieldBuf(node.index);
15638 }
15639 }
15640 yieldNode(node) {
15641 if (!node)
15642 return false;
15643 this._tree = node;
15644 this.type = node.type;
15645 this.from = node.from;
15646 this.to = node.to;
15647 return true;
15648 }
15649 yieldBuf(index, type) {
15650 this.index = index;
15651 let { start, buffer } = this.buffer;
15652 this.type = type || buffer.set.types[buffer.buffer[index]];
15653 this.from = start + buffer.buffer[index + 1];
15654 this.to = start + buffer.buffer[index + 2];
15655 return true;
15656 }
15657 /**
15658 @internal
15659 */
15660 yield(node) {
15661 if (!node)
15662 return false;
15663 if (node instanceof TreeNode) {
15664 this.buffer = null;
15665 return this.yieldNode(node);
15666 }
15667 this.buffer = node.context;
15668 return this.yieldBuf(node.index, node.type);
15669 }
15670 /**
15671 @internal
15672 */
15673 toString() {
15674 return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
15675 }
15676 /**
15677 @internal
15678 */
15679 enterChild(dir, pos, side) {
15680 if (!this.buffer)
15681 return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
15682 let { buffer } = this.buffer;
15683 let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
15684 if (index < 0)
15685 return false;
15686 this.stack.push(this.index);
15687 return this.yieldBuf(index);
15688 }
15689 /**
15690 Move the cursor to this node's first child. When this returns
15691 false, the node has no child, and the cursor has not been moved.
15692 */
15693 firstChild() { return this.enterChild(1, 0, 4 /* Side.DontCare */); }
15694 /**
15695 Move the cursor to this node's last child.
15696 */
15697 lastChild() { return this.enterChild(-1, 0, 4 /* Side.DontCare */); }
15698 /**
15699 Move the cursor to the first child that ends after `pos`.
15700 */
15701 childAfter(pos) { return this.enterChild(1, pos, 2 /* Side.After */); }
15702 /**
15703 Move to the last child that starts before `pos`.
15704 */
15705 childBefore(pos) { return this.enterChild(-1, pos, -2 /* Side.Before */); }
15706 /**
15707 Move the cursor to the child around `pos`. If side is -1 the
15708 child may end at that position, when 1 it may start there. This
15709 will also enter [overlaid](#common.MountedTree.overlay)
15710 [mounted](#common.NodeProp^mounted) trees unless `overlays` is
15711 set to false.
15712 */
15713 enter(pos, side, mode = this.mode) {
15714 if (!this.buffer)
15715 return this.yield(this._tree.enter(pos, side, mode));
15716 return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
15717 }
15718 /**
15719 Move to the node's parent node, if this isn't the top node.
15720 */
15721 parent() {
15722 if (!this.buffer)
15723 return this.yieldNode((this.mode & IterMode.IncludeAnonymous) ? this._tree._parent : this._tree.parent);
15724 if (this.stack.length)
15725 return this.yieldBuf(this.stack.pop());
15726 let parent = (this.mode & IterMode.IncludeAnonymous) ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
15727 this.buffer = null;
15728 return this.yieldNode(parent);
15729 }
15730 /**
15731 @internal
15732 */
15733 sibling(dir) {
15734 if (!this.buffer)
15735 return !this._tree._parent ? false
15736 : this.yield(this._tree.index < 0 ? null
15737 : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode));
15738 let { buffer } = this.buffer, d = this.stack.length - 1;
15739 if (dir < 0) {
15740 let parentStart = d < 0 ? 0 : this.stack[d] + 4;
15741 if (this.index != parentStart)
15742 return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4 /* Side.DontCare */));
15743 }
15744 else {
15745 let after = buffer.buffer[this.index + 3];
15746 if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
15747 return this.yieldBuf(after);
15748 }
15749 return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4 /* Side.DontCare */, this.mode)) : false;
15750 }
15751 /**
15752 Move to this node's next sibling, if any.
15753 */
15754 nextSibling() { return this.sibling(1); }
15755 /**
15756 Move to this node's previous sibling, if any.
15757 */
15758 prevSibling() { return this.sibling(-1); }
15759 atLastNode(dir) {
15760 let index, parent, { buffer } = this;
15761 if (buffer) {
15762 if (dir > 0) {
15763 if (this.index < buffer.buffer.buffer.length)
15764 return false;
15765 }
15766 else {
15767 for (let i = 0; i < this.index; i++)
15768 if (buffer.buffer.buffer[i + 3] < this.index)
15769 return false;
15770 }
15771 ({ index, parent } = buffer);
15772 }
15773 else {
15774 ({ index, _parent: parent } = this._tree);
15775 }
15776 for (; parent; { index, _parent: parent } = parent) {
15777 if (index > -1)
15778 for (let i = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i != e; i += dir) {
15779 let child = parent._tree.children[i];
15780 if ((this.mode & IterMode.IncludeAnonymous) ||
15781 child instanceof TreeBuffer ||
15782 !child.type.isAnonymous ||
15783 hasChild(child))
15784 return false;
15785 }
15786 }
15787 return true;
15788 }
15789 move(dir, enter) {
15790 if (enter && this.enterChild(dir, 0, 4 /* Side.DontCare */))
15791 return true;
15792 for (;;) {
15793 if (this.sibling(dir))
15794 return true;
15795 if (this.atLastNode(dir) || !this.parent())
15796 return false;
15797 }
15798 }
15799 /**
15800 Move to the next node in a
15801 [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
15802 traversal, going from a node to its first child or, if the
15803 current node is empty or `enter` is false, its next sibling or
15804 the next sibling of the first parent node that has one.
15805 */
15806 next(enter = true) { return this.move(1, enter); }
15807 /**
15808 Move to the next node in a last-to-first pre-order traveral. A
15809 node is followed by its last child or, if it has none, its
15810 previous sibling or the previous sibling of the first parent
15811 node that has one.
15812 */
15813 prev(enter = true) { return this.move(-1, enter); }
15814 /**
15815 Move the cursor to the innermost node that covers `pos`. If
15816 `side` is -1, it will enter nodes that end at `pos`. If it is 1,
15817 it will enter nodes that start at `pos`.
15818 */
15819 moveTo(pos, side = 0) {
15820 // Move up to a node that actually holds the position, if possible
15821 while (this.from == this.to ||
15822 (side < 1 ? this.from >= pos : this.from > pos) ||
15823 (side > -1 ? this.to <= pos : this.to < pos))
15824 if (!this.parent())
15825 break;
15826 // Then scan down into child nodes as far as possible
15827 while (this.enterChild(1, pos, side)) { }
15828 return this;
15829 }
15830 /**
15831 Get a [syntax node](#common.SyntaxNode) at the cursor's current
15832 position.
15833 */
15834 get node() {
15835 if (!this.buffer)
15836 return this._tree;
15837 let cache = this.bufferNode, result = null, depth = 0;
15838 if (cache && cache.context == this.buffer) {
15839 scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
15840 for (let c = cache; c; c = c._parent)
15841 if (c.index == index) {
15842 if (index == this.index)
15843 return c;
15844 result = c;
15845 depth = d + 1;
15846 break scan;
15847 }
15848 index = this.stack[--d];
15849 }
15850 }
15851 for (let i = depth; i < this.stack.length; i++)
15852 result = new BufferNode(this.buffer, result, this.stack[i]);
15853 return this.bufferNode = new BufferNode(this.buffer, result, this.index);
15854 }
15855 /**
15856 Get the [tree](#common.Tree) that represents the current node, if
15857 any. Will return null when the node is in a [tree
15858 buffer](#common.TreeBuffer).
15859 */
15860 get tree() {
15861 return this.buffer ? null : this._tree._tree;
15862 }
15863 /**
15864 Iterate over the current node and all its descendants, calling
15865 `enter` when entering a node and `leave`, if given, when leaving
15866 one. When `enter` returns `false`, any children of that node are
15867 skipped, and `leave` isn't called for it.
15868 */
15869 iterate(enter, leave) {
15870 for (let depth = 0;;) {
15871 let mustLeave = false;
15872 if (this.type.isAnonymous || enter(this) !== false) {
15873 if (this.firstChild()) {
15874 depth++;
15875 continue;
15876 }
15877 if (!this.type.isAnonymous)
15878 mustLeave = true;
15879 }
15880 for (;;) {
15881 if (mustLeave && leave)
15882 leave(this);
15883 mustLeave = this.type.isAnonymous;
15884 if (this.nextSibling())
15885 break;
15886 if (!depth)
15887 return;
15888 this.parent();
15889 depth--;
15890 mustLeave = true;
15891 }
15892 }
15893 }
15894 /**
15895 Test whether the current node matches a given context—a sequence
15896 of direct parent node names. Empty strings in the context array
15897 are treated as wildcards.
15898 */
15899 matchContext(context) {
15900 if (!this.buffer)
15901 return matchNodeContext(this.node, context);
15902 let { buffer } = this.buffer, { types } = buffer.set;
15903 for (let i = context.length - 1, d = this.stack.length - 1; i >= 0; d--) {
15904 if (d < 0)
15905 return matchNodeContext(this.node, context, i);
15906 let type = types[buffer.buffer[this.stack[d]]];
15907 if (!type.isAnonymous) {
15908 if (context[i] && context[i] != type.name)
15909 return false;
15910 i--;
15911 }
15912 }
15913 return true;
15914 }
15915 }
15916 function hasChild(tree) {
15917 return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
15918 }
15919 function buildTree(data) {
15920 var _a;
15921 let { buffer, nodeSet, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
15922 let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
15923 let types = nodeSet.types;
15924 let contextHash = 0, lookAhead = 0;
15925 function takeNode(parentStart, minPos, children, positions, inRepeat, depth) {
15926 let { id, start, end, size } = cursor;
15927 let lookAheadAtStart = lookAhead;
15928 while (size < 0) {
15929 cursor.next();
15930 if (size == -1 /* SpecialRecord.Reuse */) {
15931 let node = reused[id];
15932 children.push(node);
15933 positions.push(start - parentStart);
15934 return;
15935 }
15936 else if (size == -3 /* SpecialRecord.ContextChange */) { // Context change
15937 contextHash = id;
15938 return;
15939 }
15940 else if (size == -4 /* SpecialRecord.LookAhead */) {
15941 lookAhead = id;
15942 return;
15943 }
15944 else {
15945 throw new RangeError(`Unrecognized record size: ${size}`);
15946 }
15947 }
15948 let type = types[id], node, buffer;
15949 let startPos = start - parentStart;
15950 if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
15951 // Small enough for a buffer, and no reused nodes inside
15952 let data = new Uint16Array(buffer.size - buffer.skip);
15953 let endPos = cursor.pos - buffer.size, index = data.length;
15954 while (cursor.pos > endPos)
15955 index = copyToBuffer(buffer.start, data, index);
15956 node = new TreeBuffer(data, end - buffer.start, nodeSet);
15957 startPos = buffer.start - parentStart;
15958 }
15959 else { // Make it a node
15960 let endPos = cursor.pos - size;
15961 cursor.next();
15962 let localChildren = [], localPositions = [];
15963 let localInRepeat = id >= minRepeatType ? id : -1;
15964 let lastGroup = 0, lastEnd = end;
15965 while (cursor.pos > endPos) {
15966 if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
15967 if (cursor.end <= lastEnd - maxBufferLength) {
15968 makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
15969 lastGroup = localChildren.length;
15970 lastEnd = cursor.end;
15971 }
15972 cursor.next();
15973 }
15974 else if (depth > 2500 /* CutOff.Depth */) {
15975 takeFlatNode(start, endPos, localChildren, localPositions);
15976 }
15977 else {
15978 takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
15979 }
15980 }
15981 if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length)
15982 makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
15983 localChildren.reverse();
15984 localPositions.reverse();
15985 if (localInRepeat > -1 && lastGroup > 0) {
15986 let make = makeBalanced(type);
15987 node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
15988 }
15989 else {
15990 node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
15991 }
15992 }
15993 children.push(node);
15994 positions.push(startPos);
15995 }
15996 function takeFlatNode(parentStart, minPos, children, positions) {
15997 let nodes = []; // Temporary, inverted array of leaf nodes found, with absolute positions
15998 let nodeCount = 0, stopAt = -1;
15999 while (cursor.pos > minPos) {
16000 let { id, start, end, size } = cursor;
16001 if (size > 4) { // Not a leaf
16002 cursor.next();
16003 }
16004 else if (stopAt > -1 && start < stopAt) {
16005 break;
16006 }
16007 else {
16008 if (stopAt < 0)
16009 stopAt = end - maxBufferLength;
16010 nodes.push(id, start, end);
16011 nodeCount++;
16012 cursor.next();
16013 }
16014 }
16015 if (nodeCount) {
16016 let buffer = new Uint16Array(nodeCount * 4);
16017 let start = nodes[nodes.length - 2];
16018 for (let i = nodes.length - 3, j = 0; i >= 0; i -= 3) {
16019 buffer[j++] = nodes[i];
16020 buffer[j++] = nodes[i + 1] - start;
16021 buffer[j++] = nodes[i + 2] - start;
16022 buffer[j++] = j;
16023 }
16024 children.push(new TreeBuffer(buffer, nodes[2] - start, nodeSet));
16025 positions.push(start - parentStart);
16026 }
16027 }
16028 function makeBalanced(type) {
16029 return (children, positions, length) => {
16030 let lookAhead = 0, lastI = children.length - 1, last, lookAheadProp;
16031 if (lastI >= 0 && (last = children[lastI]) instanceof Tree) {
16032 if (!lastI && last.type == type && last.length == length)
16033 return last;
16034 if (lookAheadProp = last.prop(NodeProp.lookAhead))
16035 lookAhead = positions[lastI] + last.length + lookAheadProp;
16036 }
16037 return makeTree(type, children, positions, length, lookAhead);
16038 };
16039 }
16040 function makeRepeatLeaf(children, positions, base, i, from, to, type, lookAhead) {
16041 let localChildren = [], localPositions = [];
16042 while (children.length > i) {
16043 localChildren.push(children.pop());
16044 localPositions.push(positions.pop() + base - from);
16045 }
16046 children.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead - to));
16047 positions.push(from - base);
16048 }
16049 function makeTree(type, children, positions, length, lookAhead = 0, props) {
16050 if (contextHash) {
16051 let pair = [NodeProp.contextHash, contextHash];
16052 props = props ? [pair].concat(props) : [pair];
16053 }
16054 if (lookAhead > 25) {
16055 let pair = [NodeProp.lookAhead, lookAhead];
16056 props = props ? [pair].concat(props) : [pair];
16057 }
16058 return new Tree(type, children, positions, length, props);
16059 }
16060 function findBufferSize(maxSize, inRepeat) {
16061 // Scan through the buffer to find previous siblings that fit
16062 // together in a TreeBuffer, and don't contain any reused nodes
16063 // (which can't be stored in a buffer).
16064 // If `inRepeat` is > -1, ignore node boundaries of that type for
16065 // nesting, but make sure the end falls either at the start
16066 // (`maxSize`) or before such a node.
16067 let fork = cursor.fork();
16068 let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
16069 let result = { size: 0, start: 0, skip: 0 };
16070 scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
16071 let nodeSize = fork.size;
16072 // Pretend nested repeat nodes of the same type don't exist
16073 if (fork.id == inRepeat && nodeSize >= 0) {
16074 // Except that we store the current state as a valid return
16075 // value.
16076 result.size = size;
16077 result.start = start;
16078 result.skip = skip;
16079 skip += 4;
16080 size += 4;
16081 fork.next();
16082 continue;
16083 }
16084 let startPos = fork.pos - nodeSize;
16085 if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
16086 break;
16087 let localSkipped = fork.id >= minRepeatType ? 4 : 0;
16088 let nodeStart = fork.start;
16089 fork.next();
16090 while (fork.pos > startPos) {
16091 if (fork.size < 0) {
16092 if (fork.size == -3 /* SpecialRecord.ContextChange */)
16093 localSkipped += 4;
16094 else
16095 break scan;
16096 }
16097 else if (fork.id >= minRepeatType) {
16098 localSkipped += 4;
16099 }
16100 fork.next();
16101 }
16102 start = nodeStart;
16103 size += nodeSize;
16104 skip += localSkipped;
16105 }
16106 if (inRepeat < 0 || size == maxSize) {
16107 result.size = size;
16108 result.start = start;
16109 result.skip = skip;
16110 }
16111 return result.size > 4 ? result : undefined;
16112 }
16113 function copyToBuffer(bufferStart, buffer, index) {
16114 let { id, start, end, size } = cursor;
16115 cursor.next();
16116 if (size >= 0 && id < minRepeatType) {
16117 let startIndex = index;
16118 if (size > 4) {
16119 let endPos = cursor.pos - (size - 4);
16120 while (cursor.pos > endPos)
16121 index = copyToBuffer(bufferStart, buffer, index);
16122 }
16123 buffer[--index] = startIndex;
16124 buffer[--index] = end - bufferStart;
16125 buffer[--index] = start - bufferStart;
16126 buffer[--index] = id;
16127 }
16128 else if (size == -3 /* SpecialRecord.ContextChange */) {
16129 contextHash = id;
16130 }
16131 else if (size == -4 /* SpecialRecord.LookAhead */) {
16132 lookAhead = id;
16133 }
16134 return index;
16135 }
16136 let children = [], positions = [];
16137 while (cursor.pos > 0)
16138 takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
16139 let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
16140 return new Tree(types[data.topID], children.reverse(), positions.reverse(), length);
16141 }
16142 const nodeSizeCache = new WeakMap;
16143 function nodeSize(balanceType, node) {
16144 if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType)
16145 return 1;
16146 let size = nodeSizeCache.get(node);
16147 if (size == null) {
16148 size = 1;
16149 for (let child of node.children) {
16150 if (child.type != balanceType || !(child instanceof Tree)) {
16151 size = 1;
16152 break;
16153 }
16154 size += nodeSize(balanceType, child);
16155 }
16156 nodeSizeCache.set(node, size);
16157 }
16158 return size;
16159 }
16160 function balanceRange(
16161 // The type the balanced tree's inner nodes.
16162 balanceType,
16163 // The direct children and their positions
16164 children, positions,
16165 // The index range in children/positions to use
16166 from, to,
16167 // The start position of the nodes, relative to their parent.
16168 start,
16169 // Length of the outer node
16170 length,
16171 // Function to build the top node of the balanced tree
16172 mkTop,
16173 // Function to build internal nodes for the balanced tree
16174 mkTree) {
16175 let total = 0;
16176 for (let i = from; i < to; i++)
16177 total += nodeSize(balanceType, children[i]);
16178 let maxChild = Math.ceil((total * 1.5) / 8 /* Balance.BranchFactor */);
16179 let localChildren = [], localPositions = [];
16180 function divide(children, positions, from, to, offset) {
16181 for (let i = from; i < to;) {
16182 let groupFrom = i, groupStart = positions[i], groupSize = nodeSize(balanceType, children[i]);
16183 i++;
16184 for (; i < to; i++) {
16185 let nextSize = nodeSize(balanceType, children[i]);
16186 if (groupSize + nextSize >= maxChild)
16187 break;
16188 groupSize += nextSize;
16189 }
16190 if (i == groupFrom + 1) {
16191 if (groupSize > maxChild) {
16192 let only = children[groupFrom]; // Only trees can have a size > 1
16193 divide(only.children, only.positions, 0, only.children.length, positions[groupFrom] + offset);
16194 continue;
16195 }
16196 localChildren.push(children[groupFrom]);
16197 }
16198 else {
16199 let length = positions[i - 1] + children[i - 1].length - groupStart;
16200 localChildren.push(balanceRange(balanceType, children, positions, groupFrom, i, groupStart, length, null, mkTree));
16201 }
16202 localPositions.push(groupStart + offset - start);
16203 }
16204 }
16205 divide(children, positions, from, to, 0);
16206 return (mkTop || mkTree)(localChildren, localPositions, length);
16207 }
16208
16209 /**
16210 Tree fragments are used during [incremental
16211 parsing](#common.Parser.startParse) to track parts of old trees
16212 that can be reused in a new parse. An array of fragments is used
16213 to track regions of an old tree whose nodes might be reused in new
16214 parses. Use the static
16215 [`applyChanges`](#common.TreeFragment^applyChanges) method to
16216 update fragments for document changes.
16217 */
16218 class TreeFragment {
16219 /**
16220 Construct a tree fragment. You'll usually want to use
16221 [`addTree`](#common.TreeFragment^addTree) and
16222 [`applyChanges`](#common.TreeFragment^applyChanges) instead of
16223 calling this directly.
16224 */
16225 constructor(
16226 /**
16227 The start of the unchanged range pointed to by this fragment.
16228 This refers to an offset in the _updated_ document (as opposed
16229 to the original tree).
16230 */
16231 from,
16232 /**
16233 The end of the unchanged range.
16234 */
16235 to,
16236 /**
16237 The tree that this fragment is based on.
16238 */
16239 tree,
16240 /**
16241 The offset between the fragment's tree and the document that
16242 this fragment can be used against. Add this when going from
16243 document to tree positions, subtract it to go from tree to
16244 document positions.
16245 */
16246 offset, openStart = false, openEnd = false) {
16247 this.from = from;
16248 this.to = to;
16249 this.tree = tree;
16250 this.offset = offset;
16251 this.open = (openStart ? 1 /* Open.Start */ : 0) | (openEnd ? 2 /* Open.End */ : 0);
16252 }
16253 /**
16254 Whether the start of the fragment represents the start of a
16255 parse, or the end of a change. (In the second case, it may not
16256 be safe to reuse some nodes at the start, depending on the
16257 parsing algorithm.)
16258 */
16259 get openStart() { return (this.open & 1 /* Open.Start */) > 0; }
16260 /**
16261 Whether the end of the fragment represents the end of a
16262 full-document parse, or the start of a change.
16263 */
16264 get openEnd() { return (this.open & 2 /* Open.End */) > 0; }
16265 /**
16266 Create a set of fragments from a freshly parsed tree, or update
16267 an existing set of fragments by replacing the ones that overlap
16268 with a tree with content from the new tree. When `partial` is
16269 true, the parse is treated as incomplete, and the resulting
16270 fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
16271 true.
16272 */
16273 static addTree(tree, fragments = [], partial = false) {
16274 let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
16275 for (let f of fragments)
16276 if (f.to > tree.length)
16277 result.push(f);
16278 return result;
16279 }
16280 /**
16281 Apply a set of edits to an array of fragments, removing or
16282 splitting fragments as necessary to remove edited ranges, and
16283 adjusting offsets for fragments that moved.
16284 */
16285 static applyChanges(fragments, changes, minGap = 128) {
16286 if (!changes.length)
16287 return fragments;
16288 let result = [];
16289 let fI = 1, nextF = fragments.length ? fragments[0] : null;
16290 for (let cI = 0, pos = 0, off = 0;; cI++) {
16291 let nextC = cI < changes.length ? changes[cI] : null;
16292 let nextPos = nextC ? nextC.fromA : 1e9;
16293 if (nextPos - pos >= minGap)
16294 while (nextF && nextF.from < nextPos) {
16295 let cut = nextF;
16296 if (pos >= cut.from || nextPos <= cut.to || off) {
16297 let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
16298 cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
16299 }
16300 if (cut)
16301 result.push(cut);
16302 if (nextF.to > nextPos)
16303 break;
16304 nextF = fI < fragments.length ? fragments[fI++] : null;
16305 }
16306 if (!nextC)
16307 break;
16308 pos = nextC.toA;
16309 off = nextC.toA - nextC.toB;
16310 }
16311 return result;
16312 }
16313 }
16314 /**
16315 A superclass that parsers should extend.
16316 */
16317 class Parser {
16318 /**
16319 Start a parse, returning a [partial parse](#common.PartialParse)
16320 object. [`fragments`](#common.TreeFragment) can be passed in to
16321 make the parse incremental.
16322
16323 By default, the entire input is parsed. You can pass `ranges`,
16324 which should be a sorted array of non-empty, non-overlapping
16325 ranges, to parse only those ranges. The tree returned in that
16326 case will start at `ranges[0].from`.
16327 */
16328 startParse(input, fragments, ranges) {
16329 if (typeof input == "string")
16330 input = new StringInput(input);
16331 ranges = !ranges ? [new Range(0, input.length)] : ranges.length ? ranges.map(r => new Range(r.from, r.to)) : [new Range(0, 0)];
16332 return this.createParse(input, fragments || [], ranges);
16333 }
16334 /**
16335 Run a full parse, returning the resulting tree.
16336 */
16337 parse(input, fragments, ranges) {
16338 let parse = this.startParse(input, fragments, ranges);
16339 for (;;) {
16340 let done = parse.advance();
16341 if (done)
16342 return done;
16343 }
16344 }
16345 }
16346 class StringInput {
16347 constructor(string) {
16348 this.string = string;
16349 }
16350 get length() { return this.string.length; }
16351 chunk(from) { return this.string.slice(from); }
16352 get lineChunks() { return false; }
16353 read(from, to) { return this.string.slice(from, to); }
16354 }
16355 new NodeProp({ perNode: true });
16356
16357 let nextTagID = 0;
16358 /**
16359 Highlighting tags are markers that denote a highlighting category.
16360 They are [associated](#highlight.styleTags) with parts of a syntax
16361 tree by a language mode, and then mapped to an actual CSS style by
16362 a [highlighter](#highlight.Highlighter).
16363
16364 Because syntax tree node types and highlight styles have to be
16365 able to talk the same language, CodeMirror uses a mostly _closed_
16366 [vocabulary](#highlight.tags) of syntax tags (as opposed to
16367 traditional open string-based systems, which make it hard for
16368 highlighting themes to cover all the tokens produced by the
16369 various languages).
16370
16371 It _is_ possible to [define](#highlight.Tag^define) your own
16372 highlighting tags for system-internal use (where you control both
16373 the language package and the highlighter), but such tags will not
16374 be picked up by regular highlighters (though you can derive them
16375 from standard tags to allow highlighters to fall back to those).
16376 */
16377 class Tag {
16378 /**
16379 @internal
16380 */
16381 constructor(
16382 /**
16383 The set of this tag and all its parent tags, starting with
16384 this one itself and sorted in order of decreasing specificity.
16385 */
16386 set,
16387 /**
16388 The base unmodified tag that this one is based on, if it's
16389 modified @internal
16390 */
16391 base,
16392 /**
16393 The modifiers applied to this.base @internal
16394 */
16395 modified) {
16396 this.set = set;
16397 this.base = base;
16398 this.modified = modified;
16399 /**
16400 @internal
16401 */
16402 this.id = nextTagID++;
16403 }
16404 /**
16405 Define a new tag. If `parent` is given, the tag is treated as a
16406 sub-tag of that parent, and
16407 [highlighters](#highlight.tagHighlighter) that don't mention
16408 this tag will try to fall back to the parent tag (or grandparent
16409 tag, etc).
16410 */
16411 static define(parent) {
16412 if (parent === null || parent === void 0 ? void 0 : parent.base)
16413 throw new Error("Can not derive from a modified tag");
16414 let tag = new Tag([], null, []);
16415 tag.set.push(tag);
16416 if (parent)
16417 for (let t of parent.set)
16418 tag.set.push(t);
16419 return tag;
16420 }
16421 /**
16422 Define a tag _modifier_, which is a function that, given a tag,
16423 will return a tag that is a subtag of the original. Applying the
16424 same modifier to a twice tag will return the same value (`m1(t1)
16425 == m1(t1)`) and applying multiple modifiers will, regardless or
16426 order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
16427
16428 When multiple modifiers are applied to a given base tag, each
16429 smaller set of modifiers is registered as a parent, so that for
16430 example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
16431 `m1(m3(t1)`, and so on.
16432 */
16433 static defineModifier() {
16434 let mod = new Modifier;
16435 return (tag) => {
16436 if (tag.modified.indexOf(mod) > -1)
16437 return tag;
16438 return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
16439 };
16440 }
16441 }
16442 let nextModifierID = 0;
16443 class Modifier {
16444 constructor() {
16445 this.instances = [];
16446 this.id = nextModifierID++;
16447 }
16448 static get(base, mods) {
16449 if (!mods.length)
16450 return base;
16451 let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
16452 if (exists)
16453 return exists;
16454 let set = [], tag = new Tag(set, base, mods);
16455 for (let m of mods)
16456 m.instances.push(tag);
16457 let configs = powerSet(mods);
16458 for (let parent of base.set)
16459 if (!parent.modified.length)
16460 for (let config of configs)
16461 set.push(Modifier.get(parent, config));
16462 return tag;
16463 }
16464 }
16465 function sameArray(a, b) {
16466 return a.length == b.length && a.every((x, i) => x == b[i]);
16467 }
16468 function powerSet(array) {
16469 let sets = [[]];
16470 for (let i = 0; i < array.length; i++) {
16471 for (let j = 0, e = sets.length; j < e; j++) {
16472 sets.push(sets[j].concat(array[i]));
16473 }
16474 }
16475 return sets.sort((a, b) => b.length - a.length);
16476 }
16477 /**
16478 This function is used to add a set of tags to a language syntax
16479 via [`NodeSet.extend`](#common.NodeSet.extend) or
16480 [`LRParser.configure`](#lr.LRParser.configure).
16481
16482 The argument object maps node selectors to [highlighting
16483 tags](#highlight.Tag) or arrays of tags.
16484
16485 Node selectors may hold one or more (space-separated) node paths.
16486 Such a path can be a [node name](#common.NodeType.name), or
16487 multiple node names (or `*` wildcards) separated by slash
16488 characters, as in `"Block/Declaration/VariableName"`. Such a path
16489 matches the final node but only if its direct parent nodes are the
16490 other nodes mentioned. A `*` in such a path matches any parent,
16491 but only a single level—wildcards that match multiple parents
16492 aren't supported, both for efficiency reasons and because Lezer
16493 trees make it rather hard to reason about what they would match.)
16494
16495 A path can be ended with `/...` to indicate that the tag assigned
16496 to the node should also apply to all child nodes, even if they
16497 match their own style (by default, only the innermost style is
16498 used).
16499
16500 When a path ends in `!`, as in `Attribute!`, no further matching
16501 happens for the node's child nodes, and the entire node gets the
16502 given style.
16503
16504 In this notation, node names that contain `/`, `!`, `*`, or `...`
16505 must be quoted as JSON strings.
16506
16507 For example:
16508
16509 ```javascript
16510 parser.withProps(
16511 styleTags({
16512 // Style Number and BigNumber nodes
16513 "Number BigNumber": tags.number,
16514 // Style Escape nodes whose parent is String
16515 "String/Escape": tags.escape,
16516 // Style anything inside Attributes nodes
16517 "Attributes!": tags.meta,
16518 // Add a style to all content inside Italic nodes
16519 "Italic/...": tags.emphasis,
16520 // Style InvalidString nodes as both `string` and `invalid`
16521 "InvalidString": [tags.string, tags.invalid],
16522 // Style the node named "/" as punctuation
16523 '"/"': tags.punctuation
16524 })
16525 )
16526 ```
16527 */
16528 function styleTags(spec) {
16529 let byName = Object.create(null);
16530 for (let prop in spec) {
16531 let tags = spec[prop];
16532 if (!Array.isArray(tags))
16533 tags = [tags];
16534 for (let part of prop.split(" "))
16535 if (part) {
16536 let pieces = [], mode = 2 /* Mode.Normal */, rest = part;
16537 for (let pos = 0;;) {
16538 if (rest == "..." && pos > 0 && pos + 3 == part.length) {
16539 mode = 1 /* Mode.Inherit */;
16540 break;
16541 }
16542 let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
16543 if (!m)
16544 throw new RangeError("Invalid path: " + part);
16545 pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
16546 pos += m[0].length;
16547 if (pos == part.length)
16548 break;
16549 let next = part[pos++];
16550 if (pos == part.length && next == "!") {
16551 mode = 0 /* Mode.Opaque */;
16552 break;
16553 }
16554 if (next != "/")
16555 throw new RangeError("Invalid path: " + part);
16556 rest = part.slice(pos);
16557 }
16558 let last = pieces.length - 1, inner = pieces[last];
16559 if (!inner)
16560 throw new RangeError("Invalid path: " + part);
16561 let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
16562 byName[inner] = rule.sort(byName[inner]);
16563 }
16564 }
16565 return ruleNodeProp.add(byName);
16566 }
16567 const ruleNodeProp = new NodeProp();
16568 class Rule {
16569 constructor(tags, mode, context, next) {
16570 this.tags = tags;
16571 this.mode = mode;
16572 this.context = context;
16573 this.next = next;
16574 }
16575 get opaque() { return this.mode == 0 /* Mode.Opaque */; }
16576 get inherit() { return this.mode == 1 /* Mode.Inherit */; }
16577 sort(other) {
16578 if (!other || other.depth < this.depth) {
16579 this.next = other;
16580 return this;
16581 }
16582 other.next = this.sort(other.next);
16583 return other;
16584 }
16585 get depth() { return this.context ? this.context.length : 0; }
16586 }
16587 Rule.empty = new Rule([], 2 /* Mode.Normal */, null);
16588 /**
16589 Define a [highlighter](#highlight.Highlighter) from an array of
16590 tag/class pairs. Classes associated with more specific tags will
16591 take precedence.
16592 */
16593 function tagHighlighter(tags, options) {
16594 let map = Object.create(null);
16595 for (let style of tags) {
16596 if (!Array.isArray(style.tag))
16597 map[style.tag.id] = style.class;
16598 else
16599 for (let tag of style.tag)
16600 map[tag.id] = style.class;
16601 }
16602 let { scope, all = null } = options || {};
16603 return {
16604 style: (tags) => {
16605 let cls = all;
16606 for (let tag of tags) {
16607 for (let sub of tag.set) {
16608 let tagClass = map[sub.id];
16609 if (tagClass) {
16610 cls = cls ? cls + " " + tagClass : tagClass;
16611 break;
16612 }
16613 }
16614 }
16615 return cls;
16616 },
16617 scope
16618 };
16619 }
16620 function highlightTags(highlighters, tags) {
16621 let result = null;
16622 for (let highlighter of highlighters) {
16623 let value = highlighter.style(tags);
16624 if (value)
16625 result = result ? result + " " + value : value;
16626 }
16627 return result;
16628 }
16629 /**
16630 Highlight the given [tree](#common.Tree) with the given
16631 [highlighter](#highlight.Highlighter). Often, the higher-level
16632 [`highlightCode`](#highlight.highlightCode) function is easier to
16633 use.
16634 */
16635 function highlightTree(tree, highlighter,
16636 /**
16637 Assign styling to a region of the text. Will be called, in order
16638 of position, for any ranges where more than zero classes apply.
16639 `classes` is a space separated string of CSS classes.
16640 */
16641 putStyle,
16642 /**
16643 The start of the range to highlight.
16644 */
16645 from = 0,
16646 /**
16647 The end of the range.
16648 */
16649 to = tree.length) {
16650 let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
16651 builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
16652 builder.flush(to);
16653 }
16654 /**
16655 Highlight the given tree with the given highlighter, calling
16656 `putText` for every piece of text, either with a set of classes or
16657 with the empty string when unstyled, and `putBreak` for every line
16658 break.
16659 */
16660 function highlightCode(code, tree, highlighter, putText, putBreak, from = 0, to = code.length) {
16661 let pos = from;
16662 function writeTo(p, classes) {
16663 if (p <= pos)
16664 return;
16665 for (let text = code.slice(pos, p), i = 0;;) {
16666 let nextBreak = text.indexOf("\n", i);
16667 let upto = nextBreak < 0 ? text.length : nextBreak;
16668 if (upto > i)
16669 putText(text.slice(i, upto), classes);
16670 if (nextBreak < 0)
16671 break;
16672 putBreak();
16673 i = nextBreak + 1;
16674 }
16675 pos = p;
16676 }
16677 highlightTree(tree, highlighter, (from, to, classes) => {
16678 writeTo(from, "");
16679 writeTo(to, classes);
16680 }, from, to);
16681 writeTo(to, "");
16682 }
16683 class HighlightBuilder {
16684 constructor(at, highlighters, span) {
16685 this.at = at;
16686 this.highlighters = highlighters;
16687 this.span = span;
16688 this.class = "";
16689 }
16690 startSpan(at, cls) {
16691 if (cls != this.class) {
16692 this.flush(at);
16693 if (at > this.at)
16694 this.at = at;
16695 this.class = cls;
16696 }
16697 }
16698 flush(to) {
16699 if (to > this.at && this.class)
16700 this.span(this.at, to, this.class);
16701 }
16702 highlightRange(cursor, from, to, inheritedClass, highlighters) {
16703 let { type, from: start, to: end } = cursor;
16704 if (start >= to || end <= from)
16705 return;
16706 if (type.isTop)
16707 highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
16708 let cls = inheritedClass;
16709 let rule = getStyleTags(cursor) || Rule.empty;
16710 let tagCls = highlightTags(highlighters, rule.tags);
16711 if (tagCls) {
16712 if (cls)
16713 cls += " ";
16714 cls += tagCls;
16715 if (rule.mode == 1 /* Mode.Inherit */)
16716 inheritedClass += (inheritedClass ? " " : "") + tagCls;
16717 }
16718 this.startSpan(Math.max(from, start), cls);
16719 if (rule.opaque)
16720 return;
16721 let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
16722 if (mounted && mounted.overlay) {
16723 let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
16724 let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
16725 let hasChild = cursor.firstChild();
16726 for (let i = 0, pos = start;; i++) {
16727 let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
16728 let nextPos = next ? next.from + start : end;
16729 let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
16730 if (rangeFrom < rangeTo && hasChild) {
16731 while (cursor.from < rangeTo) {
16732 this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
16733 this.startSpan(Math.min(rangeTo, cursor.to), cls);
16734 if (cursor.to >= nextPos || !cursor.nextSibling())
16735 break;
16736 }
16737 }
16738 if (!next || nextPos > to)
16739 break;
16740 pos = next.to + start;
16741 if (pos > from) {
16742 this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters);
16743 this.startSpan(Math.min(to, pos), cls);
16744 }
16745 }
16746 if (hasChild)
16747 cursor.parent();
16748 }
16749 else if (cursor.firstChild()) {
16750 if (mounted)
16751 inheritedClass = "";
16752 do {
16753 if (cursor.to <= from)
16754 continue;
16755 if (cursor.from >= to)
16756 break;
16757 this.highlightRange(cursor, from, to, inheritedClass, highlighters);
16758 this.startSpan(Math.min(to, cursor.to), cls);
16759 } while (cursor.nextSibling());
16760 cursor.parent();
16761 }
16762 }
16763 }
16764 /**
16765 Match a syntax node's [highlight rules](#highlight.styleTags). If
16766 there's a match, return its set of tags, and whether it is
16767 opaque (uses a `!`) or applies to all child nodes (`/...`).
16768 */
16769 function getStyleTags(node) {
16770 let rule = node.type.prop(ruleNodeProp);
16771 while (rule && rule.context && !node.matchContext(rule.context))
16772 rule = rule.next;
16773 return rule || null;
16774 }
16775 const t = Tag.define;
16776 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();
16777 /**
16778 The default set of highlighting [tags](#highlight.Tag).
16779
16780 This collection is heavily biased towards programming languages,
16781 and necessarily incomplete. A full ontology of syntactic
16782 constructs would fill a stack of books, and be impractical to
16783 write themes for. So try to make do with this set. If all else
16784 fails, [open an
16785 issue](https://github.com/codemirror/codemirror.next) to propose a
16786 new tag, or [define](#highlight.Tag^define) a local custom tag for
16787 your use case.
16788
16789 Note that it is not obligatory to always attach the most specific
16790 tag possible to an element—if your grammar can't easily
16791 distinguish a certain type of element (such as a local variable),
16792 it is okay to style it as its more general variant (a variable).
16793
16794 For tags that extend some parent tag, the documentation links to
16795 the parent.
16796 */
16797 const tags = {
16798 /**
16799 A comment.
16800 */
16801 comment,
16802 /**
16803 A line [comment](#highlight.tags.comment).
16804 */
16805 lineComment: t(comment),
16806 /**
16807 A block [comment](#highlight.tags.comment).
16808 */
16809 blockComment: t(comment),
16810 /**
16811 A documentation [comment](#highlight.tags.comment).
16812 */
16813 docComment: t(comment),
16814 /**
16815 Any kind of identifier.
16816 */
16817 name,
16818 /**
16819 The [name](#highlight.tags.name) of a variable.
16820 */
16821 variableName: t(name),
16822 /**
16823 A type [name](#highlight.tags.name).
16824 */
16825 typeName: typeName,
16826 /**
16827 A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
16828 */
16829 tagName: t(typeName),
16830 /**
16831 A property or field [name](#highlight.tags.name).
16832 */
16833 propertyName: propertyName,
16834 /**
16835 An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
16836 */
16837 attributeName: t(propertyName),
16838 /**
16839 The [name](#highlight.tags.name) of a class.
16840 */
16841 className: t(name),
16842 /**
16843 A label [name](#highlight.tags.name).
16844 */
16845 labelName: t(name),
16846 /**
16847 A namespace [name](#highlight.tags.name).
16848 */
16849 namespace: t(name),
16850 /**
16851 The [name](#highlight.tags.name) of a macro.
16852 */
16853 macroName: t(name),
16854 /**
16855 A literal value.
16856 */
16857 literal,
16858 /**
16859 A string [literal](#highlight.tags.literal).
16860 */
16861 string,
16862 /**
16863 A documentation [string](#highlight.tags.string).
16864 */
16865 docString: t(string),
16866 /**
16867 A character literal (subtag of [string](#highlight.tags.string)).
16868 */
16869 character: t(string),
16870 /**
16871 An attribute value (subtag of [string](#highlight.tags.string)).
16872 */
16873 attributeValue: t(string),
16874 /**
16875 A number [literal](#highlight.tags.literal).
16876 */
16877 number,
16878 /**
16879 An integer [number](#highlight.tags.number) literal.
16880 */
16881 integer: t(number),
16882 /**
16883 A floating-point [number](#highlight.tags.number) literal.
16884 */
16885 float: t(number),
16886 /**
16887 A boolean [literal](#highlight.tags.literal).
16888 */
16889 bool: t(literal),
16890 /**
16891 Regular expression [literal](#highlight.tags.literal).
16892 */
16893 regexp: t(literal),
16894 /**
16895 An escape [literal](#highlight.tags.literal), for example a
16896 backslash escape in a string.
16897 */
16898 escape: t(literal),
16899 /**
16900 A color [literal](#highlight.tags.literal).
16901 */
16902 color: t(literal),
16903 /**
16904 A URL [literal](#highlight.tags.literal).
16905 */
16906 url: t(literal),
16907 /**
16908 A language keyword.
16909 */
16910 keyword,
16911 /**
16912 The [keyword](#highlight.tags.keyword) for the self or this
16913 object.
16914 */
16915 self: t(keyword),
16916 /**
16917 The [keyword](#highlight.tags.keyword) for null.
16918 */
16919 null: t(keyword),
16920 /**
16921 A [keyword](#highlight.tags.keyword) denoting some atomic value.
16922 */
16923 atom: t(keyword),
16924 /**
16925 A [keyword](#highlight.tags.keyword) that represents a unit.
16926 */
16927 unit: t(keyword),
16928 /**
16929 A modifier [keyword](#highlight.tags.keyword).
16930 */
16931 modifier: t(keyword),
16932 /**
16933 A [keyword](#highlight.tags.keyword) that acts as an operator.
16934 */
16935 operatorKeyword: t(keyword),
16936 /**
16937 A control-flow related [keyword](#highlight.tags.keyword).
16938 */
16939 controlKeyword: t(keyword),
16940 /**
16941 A [keyword](#highlight.tags.keyword) that defines something.
16942 */
16943 definitionKeyword: t(keyword),
16944 /**
16945 A [keyword](#highlight.tags.keyword) related to defining or
16946 interfacing with modules.
16947 */
16948 moduleKeyword: t(keyword),
16949 /**
16950 An operator.
16951 */
16952 operator,
16953 /**
16954 An [operator](#highlight.tags.operator) that dereferences something.
16955 */
16956 derefOperator: t(operator),
16957 /**
16958 Arithmetic-related [operator](#highlight.tags.operator).
16959 */
16960 arithmeticOperator: t(operator),
16961 /**
16962 Logical [operator](#highlight.tags.operator).
16963 */
16964 logicOperator: t(operator),
16965 /**
16966 Bit [operator](#highlight.tags.operator).
16967 */
16968 bitwiseOperator: t(operator),
16969 /**
16970 Comparison [operator](#highlight.tags.operator).
16971 */
16972 compareOperator: t(operator),
16973 /**
16974 [Operator](#highlight.tags.operator) that updates its operand.
16975 */
16976 updateOperator: t(operator),
16977 /**
16978 [Operator](#highlight.tags.operator) that defines something.
16979 */
16980 definitionOperator: t(operator),
16981 /**
16982 Type-related [operator](#highlight.tags.operator).
16983 */
16984 typeOperator: t(operator),
16985 /**
16986 Control-flow [operator](#highlight.tags.operator).
16987 */
16988 controlOperator: t(operator),
16989 /**
16990 Program or markup punctuation.
16991 */
16992 punctuation,
16993 /**
16994 [Punctuation](#highlight.tags.punctuation) that separates
16995 things.
16996 */
16997 separator: t(punctuation),
16998 /**
16999 Bracket-style [punctuation](#highlight.tags.punctuation).
17000 */
17001 bracket,
17002 /**
17003 Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
17004 tokens).
17005 */
17006 angleBracket: t(bracket),
17007 /**
17008 Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
17009 tokens).
17010 */
17011 squareBracket: t(bracket),
17012 /**
17013 Parentheses (usually `(` and `)` tokens). Subtag of
17014 [bracket](#highlight.tags.bracket).
17015 */
17016 paren: t(bracket),
17017 /**
17018 Braces (usually `{` and `}` tokens). Subtag of
17019 [bracket](#highlight.tags.bracket).
17020 */
17021 brace: t(bracket),
17022 /**
17023 Content, for example plain text in XML or markup documents.
17024 */
17025 content,
17026 /**
17027 [Content](#highlight.tags.content) that represents a heading.
17028 */
17029 heading,
17030 /**
17031 A level 1 [heading](#highlight.tags.heading).
17032 */
17033 heading1: t(heading),
17034 /**
17035 A level 2 [heading](#highlight.tags.heading).
17036 */
17037 heading2: t(heading),
17038 /**
17039 A level 3 [heading](#highlight.tags.heading).
17040 */
17041 heading3: t(heading),
17042 /**
17043 A level 4 [heading](#highlight.tags.heading).
17044 */
17045 heading4: t(heading),
17046 /**
17047 A level 5 [heading](#highlight.tags.heading).
17048 */
17049 heading5: t(heading),
17050 /**
17051 A level 6 [heading](#highlight.tags.heading).
17052 */
17053 heading6: t(heading),
17054 /**
17055 A prose separator (such as a horizontal rule).
17056 */
17057 contentSeparator: t(content),
17058 /**
17059 [Content](#highlight.tags.content) that represents a list.
17060 */
17061 list: t(content),
17062 /**
17063 [Content](#highlight.tags.content) that represents a quote.
17064 */
17065 quote: t(content),
17066 /**
17067 [Content](#highlight.tags.content) that is emphasized.
17068 */
17069 emphasis: t(content),
17070 /**
17071 [Content](#highlight.tags.content) that is styled strong.
17072 */
17073 strong: t(content),
17074 /**
17075 [Content](#highlight.tags.content) that is part of a link.
17076 */
17077 link: t(content),
17078 /**
17079 [Content](#highlight.tags.content) that is styled as code or
17080 monospace.
17081 */
17082 monospace: t(content),
17083 /**
17084 [Content](#highlight.tags.content) that has a strike-through
17085 style.
17086 */
17087 strikethrough: t(content),
17088 /**
17089 Inserted text in a change-tracking format.
17090 */
17091 inserted: t(),
17092 /**
17093 Deleted text.
17094 */
17095 deleted: t(),
17096 /**
17097 Changed text.
17098 */
17099 changed: t(),
17100 /**
17101 An invalid or unsyntactic element.
17102 */
17103 invalid: t(),
17104 /**
17105 Metadata or meta-instruction.
17106 */
17107 meta,
17108 /**
17109 [Metadata](#highlight.tags.meta) that applies to the entire
17110 document.
17111 */
17112 documentMeta: t(meta),
17113 /**
17114 [Metadata](#highlight.tags.meta) that annotates or adds
17115 attributes to a given syntactic element.
17116 */
17117 annotation: t(meta),
17118 /**
17119 Processing instruction or preprocessor directive. Subtag of
17120 [meta](#highlight.tags.meta).
17121 */
17122 processingInstruction: t(meta),
17123 /**
17124 [Modifier](#highlight.Tag^defineModifier) that indicates that a
17125 given element is being defined. Expected to be used with the
17126 various [name](#highlight.tags.name) tags.
17127 */
17128 definition: Tag.defineModifier(),
17129 /**
17130 [Modifier](#highlight.Tag^defineModifier) that indicates that
17131 something is constant. Mostly expected to be used with
17132 [variable names](#highlight.tags.variableName).
17133 */
17134 constant: Tag.defineModifier(),
17135 /**
17136 [Modifier](#highlight.Tag^defineModifier) used to indicate that
17137 a [variable](#highlight.tags.variableName) or [property
17138 name](#highlight.tags.propertyName) is being called or defined
17139 as a function.
17140 */
17141 function: Tag.defineModifier(),
17142 /**
17143 [Modifier](#highlight.Tag^defineModifier) that can be applied to
17144 [names](#highlight.tags.name) to indicate that they belong to
17145 the language's standard environment.
17146 */
17147 standard: Tag.defineModifier(),
17148 /**
17149 [Modifier](#highlight.Tag^defineModifier) that indicates a given
17150 [names](#highlight.tags.name) is local to some scope.
17151 */
17152 local: Tag.defineModifier(),
17153 /**
17154 A generic variant [modifier](#highlight.Tag^defineModifier) that
17155 can be used to tag language-specific alternative variants of
17156 some common tag. It is recommended for themes to define special
17157 forms of at least the [string](#highlight.tags.string) and
17158 [variable name](#highlight.tags.variableName) tags, since those
17159 come up a lot.
17160 */
17161 special: Tag.defineModifier()
17162 };
17163 /**
17164 This is a highlighter that adds stable, predictable classes to
17165 tokens, for styling with external CSS.
17166
17167 The following tags are mapped to their name prefixed with `"tok-"`
17168 (for example `"tok-comment"`):
17169
17170 * [`link`](#highlight.tags.link)
17171 * [`heading`](#highlight.tags.heading)
17172 * [`emphasis`](#highlight.tags.emphasis)
17173 * [`strong`](#highlight.tags.strong)
17174 * [`keyword`](#highlight.tags.keyword)
17175 * [`atom`](#highlight.tags.atom)
17176 * [`bool`](#highlight.tags.bool)
17177 * [`url`](#highlight.tags.url)
17178 * [`labelName`](#highlight.tags.labelName)
17179 * [`inserted`](#highlight.tags.inserted)
17180 * [`deleted`](#highlight.tags.deleted)
17181 * [`literal`](#highlight.tags.literal)
17182 * [`string`](#highlight.tags.string)
17183 * [`number`](#highlight.tags.number)
17184 * [`variableName`](#highlight.tags.variableName)
17185 * [`typeName`](#highlight.tags.typeName)
17186 * [`namespace`](#highlight.tags.namespace)
17187 * [`className`](#highlight.tags.className)
17188 * [`macroName`](#highlight.tags.macroName)
17189 * [`propertyName`](#highlight.tags.propertyName)
17190 * [`operator`](#highlight.tags.operator)
17191 * [`comment`](#highlight.tags.comment)
17192 * [`meta`](#highlight.tags.meta)
17193 * [`punctuation`](#highlight.tags.punctuation)
17194 * [`invalid`](#highlight.tags.invalid)
17195
17196 In addition, these mappings are provided:
17197
17198 * [`regexp`](#highlight.tags.regexp),
17199 [`escape`](#highlight.tags.escape), and
17200 [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
17201 are mapped to `"tok-string2"`
17202 * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
17203 to `"tok-variableName2"`
17204 * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
17205 to `"tok-variableName tok-local"`
17206 * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
17207 to `"tok-variableName tok-definition"`
17208 * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
17209 to `"tok-propertyName tok-definition"`
17210 */
17211 const classHighlighter = tagHighlighter([
17212 { tag: tags.link, class: "tok-link" },
17213 { tag: tags.heading, class: "tok-heading" },
17214 { tag: tags.emphasis, class: "tok-emphasis" },
17215 { tag: tags.strong, class: "tok-strong" },
17216 { tag: tags.keyword, class: "tok-keyword" },
17217 { tag: tags.atom, class: "tok-atom" },
17218 { tag: tags.bool, class: "tok-bool" },
17219 { tag: tags.url, class: "tok-url" },
17220 { tag: tags.labelName, class: "tok-labelName" },
17221 { tag: tags.inserted, class: "tok-inserted" },
17222 { tag: tags.deleted, class: "tok-deleted" },
17223 { tag: tags.literal, class: "tok-literal" },
17224 { tag: tags.string, class: "tok-string" },
17225 { tag: tags.number, class: "tok-number" },
17226 { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
17227 { tag: tags.variableName, class: "tok-variableName" },
17228 { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
17229 { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
17230 { tag: tags.special(tags.variableName), class: "tok-variableName2" },
17231 { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
17232 { tag: tags.typeName, class: "tok-typeName" },
17233 { tag: tags.namespace, class: "tok-namespace" },
17234 { tag: tags.className, class: "tok-className" },
17235 { tag: tags.macroName, class: "tok-macroName" },
17236 { tag: tags.propertyName, class: "tok-propertyName" },
17237 { tag: tags.operator, class: "tok-operator" },
17238 { tag: tags.comment, class: "tok-comment" },
17239 { tag: tags.meta, class: "tok-meta" },
17240 { tag: tags.invalid, class: "tok-invalid" },
17241 { tag: tags.punctuation, class: "tok-punctuation" }
17242 ]);
17243
17244 var _a;
17245 /**
17246 Node prop stored in a parser's top syntax node to provide the
17247 facet that stores language-specific data for that language.
17248 */
17249 const languageDataProp = /*@__PURE__*/new NodeProp();
17250 /**
17251 Helper function to define a facet (to be added to the top syntax
17252 node(s) for a language via
17253 [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
17254 used to associate language data with the language. You
17255 probably only need this when subclassing
17256 [`Language`](https://codemirror.net/6/docs/ref/#language.Language).
17257 */
17258 function defineLanguageFacet(baseData) {
17259 return Facet.define({
17260 combine: baseData ? values => values.concat(baseData) : undefined
17261 });
17262 }
17263 /**
17264 Syntax node prop used to register sublanguages. Should be added to
17265 the top level node type for the language.
17266 */
17267 const sublanguageProp = /*@__PURE__*/new NodeProp();
17268 /**
17269 A language object manages parsing and per-language
17270 [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
17271 managed as a [Lezer](https://lezer.codemirror.net) tree. The class
17272 can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
17273 subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
17274 via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
17275 for stream parsers.
17276 */
17277 class Language {
17278 /**
17279 Construct a language object. If you need to invoke this
17280 directly, first define a data facet with
17281 [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
17282 configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
17283 to the language's outer syntax node.
17284 */
17285 constructor(
17286 /**
17287 The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
17288 used for this language.
17289 */
17290 data, parser, extraExtensions = [],
17291 /**
17292 A language name.
17293 */
17294 name = "") {
17295 this.data = data;
17296 this.name = name;
17297 // Kludge to define EditorState.tree as a debugging helper,
17298 // without the EditorState package actually knowing about
17299 // languages and lezer trees.
17300 if (!EditorState.prototype.hasOwnProperty("tree"))
17301 Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
17302 this.parser = parser;
17303 this.extension = [
17304 language.of(this),
17305 EditorState.languageData.of((state, pos, side) => {
17306 let top = topNodeAt(state, pos, side), data = top.type.prop(languageDataProp);
17307 if (!data)
17308 return [];
17309 let base = state.facet(data), sub = top.type.prop(sublanguageProp);
17310 if (sub) {
17311 let innerNode = top.resolve(pos - top.from, side);
17312 for (let sublang of sub)
17313 if (sublang.test(innerNode, state)) {
17314 let data = state.facet(sublang.facet);
17315 return sublang.type == "replace" ? data : data.concat(base);
17316 }
17317 }
17318 return base;
17319 })
17320 ].concat(extraExtensions);
17321 }
17322 /**
17323 Query whether this language is active at the given position.
17324 */
17325 isActiveAt(state, pos, side = -1) {
17326 return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
17327 }
17328 /**
17329 Find the document regions that were parsed using this language.
17330 The returned regions will _include_ any nested languages rooted
17331 in this language, when those exist.
17332 */
17333 findRegions(state) {
17334 let lang = state.facet(language);
17335 if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
17336 return [{ from: 0, to: state.doc.length }];
17337 if (!lang || !lang.allowsNesting)
17338 return [];
17339 let result = [];
17340 let explore = (tree, from) => {
17341 if (tree.prop(languageDataProp) == this.data) {
17342 result.push({ from, to: from + tree.length });
17343 return;
17344 }
17345 let mount = tree.prop(NodeProp.mounted);
17346 if (mount) {
17347 if (mount.tree.prop(languageDataProp) == this.data) {
17348 if (mount.overlay)
17349 for (let r of mount.overlay)
17350 result.push({ from: r.from + from, to: r.to + from });
17351 else
17352 result.push({ from: from, to: from + tree.length });
17353 return;
17354 }
17355 else if (mount.overlay) {
17356 let size = result.length;
17357 explore(mount.tree, mount.overlay[0].from + from);
17358 if (result.length > size)
17359 return;
17360 }
17361 }
17362 for (let i = 0; i < tree.children.length; i++) {
17363 let ch = tree.children[i];
17364 if (ch instanceof Tree)
17365 explore(ch, tree.positions[i] + from);
17366 }
17367 };
17368 explore(syntaxTree(state), 0);
17369 return result;
17370 }
17371 /**
17372 Indicates whether this language allows nested languages. The
17373 default implementation returns true.
17374 */
17375 get allowsNesting() { return true; }
17376 }
17377 /**
17378 @internal
17379 */
17380 Language.setState = /*@__PURE__*/StateEffect.define();
17381 function topNodeAt(state, pos, side) {
17382 let topLang = state.facet(language), tree = syntaxTree(state).topNode;
17383 if (!topLang || topLang.allowsNesting) {
17384 for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers))
17385 if (node.type.isTop)
17386 tree = node;
17387 }
17388 return tree;
17389 }
17390 /**
17391 A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
17392 [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
17393 parsers.
17394 */
17395 class LRLanguage extends Language {
17396 constructor(data, parser, name) {
17397 super(data, parser, [], name);
17398 this.parser = parser;
17399 }
17400 /**
17401 Define a language from a parser.
17402 */
17403 static define(spec) {
17404 let data = defineLanguageFacet(spec.languageData);
17405 return new LRLanguage(data, spec.parser.configure({
17406 props: [languageDataProp.add(type => type.isTop ? data : undefined)]
17407 }), spec.name);
17408 }
17409 /**
17410 Create a new instance of this language with a reconfigured
17411 version of its parser and optionally a new name.
17412 */
17413 configure(options, name) {
17414 return new LRLanguage(this.data, this.parser.configure(options), name || this.name);
17415 }
17416 get allowsNesting() { return this.parser.hasWrappers(); }
17417 }
17418 /**
17419 Get the syntax tree for a state, which is the current (possibly
17420 incomplete) parse tree of the active
17421 [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
17422 language available.
17423 */
17424 function syntaxTree(state) {
17425 let field = state.field(Language.state, false);
17426 return field ? field.tree : Tree.empty;
17427 }
17428 /**
17429 Try to get a parse tree that spans at least up to `upto`. The
17430 method will do at most `timeout` milliseconds of work to parse
17431 up to that point if the tree isn't already available.
17432 */
17433 function ensureSyntaxTree(state, upto, timeout = 50) {
17434 var _a;
17435 let parse = (_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context;
17436 if (!parse)
17437 return null;
17438 let oldVieport = parse.viewport;
17439 parse.updateViewport({ from: 0, to: upto });
17440 let result = parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null;
17441 parse.updateViewport(oldVieport);
17442 return result;
17443 }
17444 /**
17445 Queries whether there is a full syntax tree available up to the
17446 given document position. If there isn't, the background parse
17447 process _might_ still be working and update the tree further, but
17448 there is no guarantee of that—the parser will [stop
17449 working](https://codemirror.net/6/docs/ref/#language.syntaxParserRunning) when it has spent a
17450 certain amount of time or has moved beyond the visible viewport.
17451 Always returns false if no language has been enabled.
17452 */
17453 function syntaxTreeAvailable(state, upto = state.doc.length) {
17454 var _a;
17455 return ((_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context.isDone(upto)) || false;
17456 }
17457 /**
17458 Move parsing forward, and update the editor state afterwards to
17459 reflect the new tree. Will work for at most `timeout`
17460 milliseconds. Returns true if the parser managed get to the given
17461 position in that time.
17462 */
17463 function forceParsing(view, upto = view.viewport.to, timeout = 100) {
17464 let success = ensureSyntaxTree(view.state, upto, timeout);
17465 if (success != syntaxTree(view.state))
17466 view.dispatch({});
17467 return !!success;
17468 }
17469 /**
17470 Tells you whether the language parser is planning to do more
17471 parsing work (in a `requestIdleCallback` pseudo-thread) or has
17472 stopped running, either because it parsed the entire document,
17473 because it spent too much time and was cut off, or because there
17474 is no language parser enabled.
17475 */
17476 function syntaxParserRunning(view) {
17477 var _a;
17478 return ((_a = view.plugin(parseWorker)) === null || _a === void 0 ? void 0 : _a.isWorking()) || false;
17479 }
17480 /**
17481 Lezer-style
17482 [`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
17483 object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
17484 */
17485 class DocInput {
17486 /**
17487 Create an input object for the given document.
17488 */
17489 constructor(doc) {
17490 this.doc = doc;
17491 this.cursorPos = 0;
17492 this.string = "";
17493 this.cursor = doc.iter();
17494 }
17495 get length() { return this.doc.length; }
17496 syncTo(pos) {
17497 this.string = this.cursor.next(pos - this.cursorPos).value;
17498 this.cursorPos = pos + this.string.length;
17499 return this.cursorPos - this.string.length;
17500 }
17501 chunk(pos) {
17502 this.syncTo(pos);
17503 return this.string;
17504 }
17505 get lineChunks() { return true; }
17506 read(from, to) {
17507 let stringStart = this.cursorPos - this.string.length;
17508 if (from < stringStart || to >= this.cursorPos)
17509 return this.doc.sliceString(from, to);
17510 else
17511 return this.string.slice(from - stringStart, to - stringStart);
17512 }
17513 }
17514 let currentContext = null;
17515 /**
17516 A parse context provided to parsers working on the editor content.
17517 */
17518 class ParseContext {
17519 constructor(parser,
17520 /**
17521 The current editor state.
17522 */
17523 state,
17524 /**
17525 Tree fragments that can be reused by incremental re-parses.
17526 */
17527 fragments = [],
17528 /**
17529 @internal
17530 */
17531 tree,
17532 /**
17533 @internal
17534 */
17535 treeLen,
17536 /**
17537 The current editor viewport (or some overapproximation
17538 thereof). Intended to be used for opportunistically avoiding
17539 work (in which case
17540 [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
17541 should be called to make sure the parser is restarted when the
17542 skipped region becomes visible).
17543 */
17544 viewport,
17545 /**
17546 @internal
17547 */
17548 skipped,
17549 /**
17550 This is where skipping parsers can register a promise that,
17551 when resolved, will schedule a new parse. It is cleared when
17552 the parse worker picks up the promise. @internal
17553 */
17554 scheduleOn) {
17555 this.parser = parser;
17556 this.state = state;
17557 this.fragments = fragments;
17558 this.tree = tree;
17559 this.treeLen = treeLen;
17560 this.viewport = viewport;
17561 this.skipped = skipped;
17562 this.scheduleOn = scheduleOn;
17563 this.parse = null;
17564 /**
17565 @internal
17566 */
17567 this.tempSkipped = [];
17568 }
17569 /**
17570 @internal
17571 */
17572 static create(parser, state, viewport) {
17573 return new ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null);
17574 }
17575 startParse() {
17576 return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
17577 }
17578 /**
17579 @internal
17580 */
17581 work(until, upto) {
17582 if (upto != null && upto >= this.state.doc.length)
17583 upto = undefined;
17584 if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
17585 this.takeTree();
17586 return true;
17587 }
17588 return this.withContext(() => {
17589 var _a;
17590 if (typeof until == "number") {
17591 let endTime = Date.now() + until;
17592 until = () => Date.now() > endTime;
17593 }
17594 if (!this.parse)
17595 this.parse = this.startParse();
17596 if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&
17597 upto < this.state.doc.length)
17598 this.parse.stopAt(upto);
17599 for (;;) {
17600 let done = this.parse.advance();
17601 if (done) {
17602 this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
17603 this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
17604 this.tree = done;
17605 this.parse = null;
17606 if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
17607 this.parse = this.startParse();
17608 else
17609 return true;
17610 }
17611 if (until())
17612 return false;
17613 }
17614 });
17615 }
17616 /**
17617 @internal
17618 */
17619 takeTree() {
17620 let pos, tree;
17621 if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
17622 if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
17623 this.parse.stopAt(pos);
17624 this.withContext(() => { while (!(tree = this.parse.advance())) { } });
17625 this.treeLen = pos;
17626 this.tree = tree;
17627 this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
17628 this.parse = null;
17629 }
17630 }
17631 withContext(f) {
17632 let prev = currentContext;
17633 currentContext = this;
17634 try {
17635 return f();
17636 }
17637 finally {
17638 currentContext = prev;
17639 }
17640 }
17641 withoutTempSkipped(fragments) {
17642 for (let r; r = this.tempSkipped.pop();)
17643 fragments = cutFragments(fragments, r.from, r.to);
17644 return fragments;
17645 }
17646 /**
17647 @internal
17648 */
17649 changes(changes, newState) {
17650 let { fragments, tree, treeLen, viewport, skipped } = this;
17651 this.takeTree();
17652 if (!changes.empty) {
17653 let ranges = [];
17654 changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
17655 fragments = TreeFragment.applyChanges(fragments, ranges);
17656 tree = Tree.empty;
17657 treeLen = 0;
17658 viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
17659 if (this.skipped.length) {
17660 skipped = [];
17661 for (let r of this.skipped) {
17662 let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
17663 if (from < to)
17664 skipped.push({ from, to });
17665 }
17666 }
17667 }
17668 return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
17669 }
17670 /**
17671 @internal
17672 */
17673 updateViewport(viewport) {
17674 if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
17675 return false;
17676 this.viewport = viewport;
17677 let startLen = this.skipped.length;
17678 for (let i = 0; i < this.skipped.length; i++) {
17679 let { from, to } = this.skipped[i];
17680 if (from < viewport.to && to > viewport.from) {
17681 this.fragments = cutFragments(this.fragments, from, to);
17682 this.skipped.splice(i--, 1);
17683 }
17684 }
17685 if (this.skipped.length >= startLen)
17686 return false;
17687 this.reset();
17688 return true;
17689 }
17690 /**
17691 @internal
17692 */
17693 reset() {
17694 if (this.parse) {
17695 this.takeTree();
17696 this.parse = null;
17697 }
17698 }
17699 /**
17700 Notify the parse scheduler that the given region was skipped
17701 because it wasn't in view, and the parse should be restarted
17702 when it comes into view.
17703 */
17704 skipUntilInView(from, to) {
17705 this.skipped.push({ from, to });
17706 }
17707 /**
17708 Returns a parser intended to be used as placeholder when
17709 asynchronously loading a nested parser. It'll skip its input and
17710 mark it as not-really-parsed, so that the next update will parse
17711 it again.
17712
17713 When `until` is given, a reparse will be scheduled when that
17714 promise resolves.
17715 */
17716 static getSkippingParser(until) {
17717 return new class extends Parser {
17718 createParse(input, fragments, ranges) {
17719 let from = ranges[0].from, to = ranges[ranges.length - 1].to;
17720 let parser = {
17721 parsedPos: from,
17722 advance() {
17723 let cx = currentContext;
17724 if (cx) {
17725 for (let r of ranges)
17726 cx.tempSkipped.push(r);
17727 if (until)
17728 cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
17729 }
17730 this.parsedPos = to;
17731 return new Tree(NodeType.none, [], [], to - from);
17732 },
17733 stoppedAt: null,
17734 stopAt() { }
17735 };
17736 return parser;
17737 }
17738 };
17739 }
17740 /**
17741 @internal
17742 */
17743 isDone(upto) {
17744 upto = Math.min(upto, this.state.doc.length);
17745 let frags = this.fragments;
17746 return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
17747 }
17748 /**
17749 Get the context for the current parse, or `null` if no editor
17750 parse is in progress.
17751 */
17752 static get() { return currentContext; }
17753 }
17754 function cutFragments(fragments, from, to) {
17755 return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
17756 }
17757 class LanguageState {
17758 constructor(
17759 // A mutable parse state that is used to preserve work done during
17760 // the lifetime of a state when moving to the next state.
17761 context) {
17762 this.context = context;
17763 this.tree = context.tree;
17764 }
17765 apply(tr) {
17766 if (!tr.docChanged && this.tree == this.context.tree)
17767 return this;
17768 let newCx = this.context.changes(tr.changes, tr.state);
17769 // If the previous parse wasn't done, go forward only up to its
17770 // end position or the end of the viewport, to avoid slowing down
17771 // state updates with parse work beyond the viewport.
17772 let upto = this.context.treeLen == tr.startState.doc.length ? undefined
17773 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
17774 if (!newCx.work(20 /* Work.Apply */, upto))
17775 newCx.takeTree();
17776 return new LanguageState(newCx);
17777 }
17778 static init(state) {
17779 let vpTo = Math.min(3000 /* Work.InitViewport */, state.doc.length);
17780 let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
17781 if (!parseState.work(20 /* Work.Apply */, vpTo))
17782 parseState.takeTree();
17783 return new LanguageState(parseState);
17784 }
17785 }
17786 Language.state = /*@__PURE__*/StateField.define({
17787 create: LanguageState.init,
17788 update(value, tr) {
17789 for (let e of tr.effects)
17790 if (e.is(Language.setState))
17791 return e.value;
17792 if (tr.startState.facet(language) != tr.state.facet(language))
17793 return LanguageState.init(tr.state);
17794 return value.apply(tr);
17795 }
17796 });
17797 let requestIdle = (callback) => {
17798 let timeout = setTimeout(() => callback(), 500 /* Work.MaxPause */);
17799 return () => clearTimeout(timeout);
17800 };
17801 if (typeof requestIdleCallback != "undefined")
17802 requestIdle = (callback) => {
17803 let idle = -1, timeout = setTimeout(() => {
17804 idle = requestIdleCallback(callback, { timeout: 500 /* Work.MaxPause */ - 100 /* Work.MinPause */ });
17805 }, 100 /* Work.MinPause */);
17806 return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
17807 };
17808 const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)
17809 ? () => navigator.scheduling.isInputPending() : null;
17810 const parseWorker = /*@__PURE__*/ViewPlugin.fromClass(class ParseWorker {
17811 constructor(view) {
17812 this.view = view;
17813 this.working = null;
17814 this.workScheduled = 0;
17815 // End of the current time chunk
17816 this.chunkEnd = -1;
17817 // Milliseconds of budget left for this chunk
17818 this.chunkBudget = -1;
17819 this.work = this.work.bind(this);
17820 this.scheduleWork();
17821 }
17822 update(update) {
17823 let cx = this.view.state.field(Language.state).context;
17824 if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
17825 this.scheduleWork();
17826 if (update.docChanged || update.selectionSet) {
17827 if (this.view.hasFocus)
17828 this.chunkBudget += 50 /* Work.ChangeBonus */;
17829 this.scheduleWork();
17830 }
17831 this.checkAsyncSchedule(cx);
17832 }
17833 scheduleWork() {
17834 if (this.working)
17835 return;
17836 let { state } = this.view, field = state.field(Language.state);
17837 if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
17838 this.working = requestIdle(this.work);
17839 }
17840 work(deadline) {
17841 this.working = null;
17842 let now = Date.now();
17843 if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
17844 this.chunkEnd = now + 30000 /* Work.ChunkTime */;
17845 this.chunkBudget = 3000 /* Work.ChunkBudget */;
17846 }
17847 if (this.chunkBudget <= 0)
17848 return; // No more budget
17849 let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
17850 if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* Work.MaxParseAhead */))
17851 return;
17852 let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Work.Slice */, deadline && !isInputPending ? Math.max(25 /* Work.MinSlice */, deadline.timeRemaining() - 5) : 1e9);
17853 let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
17854 let done = field.context.work(() => {
17855 return isInputPending && isInputPending() || Date.now() > endTime;
17856 }, vpTo + (viewportFirst ? 0 : 100000 /* Work.MaxParseAhead */));
17857 this.chunkBudget -= Date.now() - now;
17858 if (done || this.chunkBudget <= 0) {
17859 field.context.takeTree();
17860 this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
17861 }
17862 if (this.chunkBudget > 0 && !(done && !viewportFirst))
17863 this.scheduleWork();
17864 this.checkAsyncSchedule(field.context);
17865 }
17866 checkAsyncSchedule(cx) {
17867 if (cx.scheduleOn) {
17868 this.workScheduled++;
17869 cx.scheduleOn
17870 .then(() => this.scheduleWork())
17871 .catch(err => logException(this.view.state, err))
17872 .then(() => this.workScheduled--);
17873 cx.scheduleOn = null;
17874 }
17875 }
17876 destroy() {
17877 if (this.working)
17878 this.working();
17879 }
17880 isWorking() {
17881 return !!(this.working || this.workScheduled > 0);
17882 }
17883 }, {
17884 eventHandlers: { focus() { this.scheduleWork(); } }
17885 });
17886 /**
17887 The facet used to associate a language with an editor state. Used
17888 by `Language` object's `extension` property (so you don't need to
17889 manually wrap your languages in this). Can be used to access the
17890 current language on a state.
17891 */
17892 const language = /*@__PURE__*/Facet.define({
17893 combine(languages) { return languages.length ? languages[0] : null; },
17894 enables: language => [
17895 Language.state,
17896 parseWorker,
17897 EditorView.contentAttributes.compute([language], state => {
17898 let lang = state.facet(language);
17899 return lang && lang.name ? { "data-language": lang.name } : {};
17900 })
17901 ]
17902 });
17903 /**
17904 This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
17905 optional set of supporting extensions. Language packages are
17906 encouraged to export a function that optionally takes a
17907 configuration object and returns a `LanguageSupport` instance, as
17908 the main way for client code to use the package.
17909 */
17910 class LanguageSupport {
17911 /**
17912 Create a language support object.
17913 */
17914 constructor(
17915 /**
17916 The language object.
17917 */
17918 language,
17919 /**
17920 An optional set of supporting extensions. When nesting a
17921 language in another language, the outer language is encouraged
17922 to include the supporting extensions for its inner languages
17923 in its own set of support extensions.
17924 */
17925 support = []) {
17926 this.language = language;
17927 this.support = support;
17928 this.extension = [language, support];
17929 }
17930 }
17931 /**
17932 Language descriptions are used to store metadata about languages
17933 and to dynamically load them. Their main role is finding the
17934 appropriate language for a filename or dynamically loading nested
17935 parsers.
17936 */
17937 class LanguageDescription {
17938 constructor(
17939 /**
17940 The name of this language.
17941 */
17942 name,
17943 /**
17944 Alternative names for the mode (lowercased, includes `this.name`).
17945 */
17946 alias,
17947 /**
17948 File extensions associated with this language.
17949 */
17950 extensions,
17951 /**
17952 Optional filename pattern that should be associated with this
17953 language.
17954 */
17955 filename, loadFunc,
17956 /**
17957 If the language has been loaded, this will hold its value.
17958 */
17959 support = undefined) {
17960 this.name = name;
17961 this.alias = alias;
17962 this.extensions = extensions;
17963 this.filename = filename;
17964 this.loadFunc = loadFunc;
17965 this.support = support;
17966 this.loading = null;
17967 }
17968 /**
17969 Start loading the the language. Will return a promise that
17970 resolves to a [`LanguageSupport`](https://codemirror.net/6/docs/ref/#language.LanguageSupport)
17971 object when the language successfully loads.
17972 */
17973 load() {
17974 return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => { this.loading = null; throw err; }));
17975 }
17976 /**
17977 Create a language description.
17978 */
17979 static of(spec) {
17980 let { load, support } = spec;
17981 if (!load) {
17982 if (!support)
17983 throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");
17984 load = () => Promise.resolve(support);
17985 }
17986 return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, load, support);
17987 }
17988 /**
17989 Look for a language in the given array of descriptions that
17990 matches the filename. Will first match
17991 [`filename`](https://codemirror.net/6/docs/ref/#language.LanguageDescription.filename) patterns,
17992 and then [extensions](https://codemirror.net/6/docs/ref/#language.LanguageDescription.extensions),
17993 and return the first language that matches.
17994 */
17995 static matchFilename(descs, filename) {
17996 for (let d of descs)
17997 if (d.filename && d.filename.test(filename))
17998 return d;
17999 let ext = /\.([^.]+)$/.exec(filename);
18000 if (ext)
18001 for (let d of descs)
18002 if (d.extensions.indexOf(ext[1]) > -1)
18003 return d;
18004 return null;
18005 }
18006 /**
18007 Look for a language whose name or alias matches the the given
18008 name (case-insensitively). If `fuzzy` is true, and no direct
18009 matchs is found, this'll also search for a language whose name
18010 or alias occurs in the string (for names shorter than three
18011 characters, only when surrounded by non-word characters).
18012 */
18013 static matchLanguageName(descs, name, fuzzy = true) {
18014 name = name.toLowerCase();
18015 for (let d of descs)
18016 if (d.alias.some(a => a == name))
18017 return d;
18018 if (fuzzy)
18019 for (let d of descs)
18020 for (let a of d.alias) {
18021 let found = name.indexOf(a);
18022 if (found > -1 && (a.length > 2 || !/\w/.test(name[found - 1]) && !/\w/.test(name[found + a.length])))
18023 return d;
18024 }
18025 return null;
18026 }
18027 }
18028
18029 /**
18030 Facet that defines a way to provide a function that computes the
18031 appropriate indentation depth, as a column number (see
18032 [`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
18033 line. A return value of `null` indicates no indentation can be
18034 determined, and the line should inherit the indentation of the one
18035 above it. A return value of `undefined` defers to the next indent
18036 service.
18037 */
18038 const indentService = /*@__PURE__*/Facet.define();
18039 /**
18040 Facet for overriding the unit by which indentation happens. Should
18041 be a string consisting either entirely of the same whitespace
18042 character. When not set, this defaults to 2 spaces.
18043 */
18044 const indentUnit = /*@__PURE__*/Facet.define({
18045 combine: values => {
18046 if (!values.length)
18047 return " ";
18048 let unit = values[0];
18049 if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0]))
18050 throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
18051 return unit;
18052 }
18053 });
18054 /**
18055 Return the _column width_ of an indent unit in the state.
18056 Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
18057 facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
18058 contains tabs.
18059 */
18060 function getIndentUnit(state) {
18061 let unit = state.facet(indentUnit);
18062 return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
18063 }
18064 /**
18065 Create an indentation string that covers columns 0 to `cols`.
18066 Will use tabs for as much of the columns as possible when the
18067 [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
18068 tabs.
18069 */
18070 function indentString(state, cols) {
18071 let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0];
18072 if (ch == "\t") {
18073 while (cols >= ts) {
18074 result += "\t";
18075 cols -= ts;
18076 }
18077 ch = " ";
18078 }
18079 for (let i = 0; i < cols; i++)
18080 result += ch;
18081 return result;
18082 }
18083 /**
18084 Get the indentation, as a column number, at the given position.
18085 Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
18086 that are registered, and if none of those return an indentation,
18087 this will check the syntax tree for the [indent node
18088 prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
18089 number when an indentation could be determined, and null
18090 otherwise.
18091 */
18092 function getIndentation(context, pos) {
18093 if (context instanceof EditorState)
18094 context = new IndentContext(context);
18095 for (let service of context.state.facet(indentService)) {
18096 let result = service(context, pos);
18097 if (result !== undefined)
18098 return result;
18099 }
18100 let tree = syntaxTree(context.state);
18101 return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
18102 }
18103 /**
18104 Create a change set that auto-indents all lines touched by the
18105 given document range.
18106 */
18107 function indentRange(state, from, to) {
18108 let updated = Object.create(null);
18109 let context = new IndentContext(state, { overrideIndentation: start => { var _a; return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1; } });
18110 let changes = [];
18111 for (let pos = from; pos <= to;) {
18112 let line = state.doc.lineAt(pos);
18113 pos = line.to + 1;
18114 let indent = getIndentation(context, line.from);
18115 if (indent == null)
18116 continue;
18117 if (!/\S/.test(line.text))
18118 indent = 0;
18119 let cur = /^\s*/.exec(line.text)[0];
18120 let norm = indentString(state, indent);
18121 if (cur != norm) {
18122 updated[line.from] = indent;
18123 changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
18124 }
18125 }
18126 return state.changes(changes);
18127 }
18128 /**
18129 Indentation contexts are used when calling [indentation
18130 services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
18131 useful in indentation logic, and can selectively override the
18132 indentation reported for some lines.
18133 */
18134 class IndentContext {
18135 /**
18136 Create an indent context.
18137 */
18138 constructor(
18139 /**
18140 The editor state.
18141 */
18142 state,
18143 /**
18144 @internal
18145 */
18146 options = {}) {
18147 this.state = state;
18148 this.options = options;
18149 this.unit = getIndentUnit(state);
18150 }
18151 /**
18152 Get a description of the line at the given position, taking
18153 [simulated line
18154 breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
18155 into account. If there is such a break at `pos`, the `bias`
18156 argument determines whether the part of the line line before or
18157 after the break is used.
18158 */
18159 lineAt(pos, bias = 1) {
18160 let line = this.state.doc.lineAt(pos);
18161 let { simulateBreak, simulateDoubleBreak } = this.options;
18162 if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
18163 if (simulateDoubleBreak && simulateBreak == pos)
18164 return { text: "", from: pos };
18165 else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
18166 return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
18167 else
18168 return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
18169 }
18170 return line;
18171 }
18172 /**
18173 Get the text directly after `pos`, either the entire line
18174 or the next 100 characters, whichever is shorter.
18175 */
18176 textAfterPos(pos, bias = 1) {
18177 if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
18178 return "";
18179 let { text, from } = this.lineAt(pos, bias);
18180 return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
18181 }
18182 /**
18183 Find the column for the given position.
18184 */
18185 column(pos, bias = 1) {
18186 let { text, from } = this.lineAt(pos, bias);
18187 let result = this.countColumn(text, pos - from);
18188 let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
18189 if (override > -1)
18190 result += override - this.countColumn(text, text.search(/\S|$/));
18191 return result;
18192 }
18193 /**
18194 Find the column position (taking tabs into account) of the given
18195 position in the given string.
18196 */
18197 countColumn(line, pos = line.length) {
18198 return countColumn(line, this.state.tabSize, pos);
18199 }
18200 /**
18201 Find the indentation column of the line at the given point.
18202 */
18203 lineIndent(pos, bias = 1) {
18204 let { text, from } = this.lineAt(pos, bias);
18205 let override = this.options.overrideIndentation;
18206 if (override) {
18207 let overriden = override(from);
18208 if (overriden > -1)
18209 return overriden;
18210 }
18211 return this.countColumn(text, text.search(/\S|$/));
18212 }
18213 /**
18214 Returns the [simulated line
18215 break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
18216 for this context, if any.
18217 */
18218 get simulatedBreak() {
18219 return this.options.simulateBreak || null;
18220 }
18221 }
18222 /**
18223 A syntax tree node prop used to associate indentation strategies
18224 with node types. Such a strategy is a function from an indentation
18225 context to a column number (see also
18226 [`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
18227 indicates that no definitive indentation can be determined.
18228 */
18229 const indentNodeProp = /*@__PURE__*/new NodeProp();
18230 // Compute the indentation for a given position from the syntax tree.
18231 function syntaxIndentation(cx, ast, pos) {
18232 let stack = ast.resolveStack(pos);
18233 let inner = stack.node.enterUnfinishedNodesBefore(pos);
18234 if (inner != stack.node) {
18235 let add = [];
18236 for (let cur = inner; cur != stack.node; cur = cur.parent)
18237 add.push(cur);
18238 for (let i = add.length - 1; i >= 0; i--)
18239 stack = { node: add[i], next: stack };
18240 }
18241 return indentFor(stack, cx, pos);
18242 }
18243 function indentFor(stack, cx, pos) {
18244 for (let cur = stack; cur; cur = cur.next) {
18245 let strategy = indentStrategy(cur.node);
18246 if (strategy)
18247 return strategy(TreeIndentContext.create(cx, pos, cur));
18248 }
18249 return 0;
18250 }
18251 function ignoreClosed(cx) {
18252 return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
18253 }
18254 function indentStrategy(tree) {
18255 let strategy = tree.type.prop(indentNodeProp);
18256 if (strategy)
18257 return strategy;
18258 let first = tree.firstChild, close;
18259 if (first && (close = first.type.prop(NodeProp.closedBy))) {
18260 let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
18261 return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
18262 }
18263 return tree.parent == null ? topIndent : null;
18264 }
18265 function topIndent() { return 0; }
18266 /**
18267 Objects of this type provide context information and helper
18268 methods to indentation functions registered on syntax nodes.
18269 */
18270 class TreeIndentContext extends IndentContext {
18271 constructor(base,
18272 /**
18273 The position at which indentation is being computed.
18274 */
18275 pos,
18276 /**
18277 @internal
18278 */
18279 context) {
18280 super(base.state, base.options);
18281 this.base = base;
18282 this.pos = pos;
18283 this.context = context;
18284 }
18285 /**
18286 The syntax tree node to which the indentation strategy
18287 applies.
18288 */
18289 get node() { return this.context.node; }
18290 /**
18291 @internal
18292 */
18293 static create(base, pos, context) {
18294 return new TreeIndentContext(base, pos, context);
18295 }
18296 /**
18297 Get the text directly after `this.pos`, either the entire line
18298 or the next 100 characters, whichever is shorter.
18299 */
18300 get textAfter() {
18301 return this.textAfterPos(this.pos);
18302 }
18303 /**
18304 Get the indentation at the reference line for `this.node`, which
18305 is the line on which it starts, unless there is a node that is
18306 _not_ a parent of this node covering the start of that line. If
18307 so, the line at the start of that node is tried, again skipping
18308 on if it is covered by another such node.
18309 */
18310 get baseIndent() {
18311 return this.baseIndentFor(this.node);
18312 }
18313 /**
18314 Get the indentation for the reference line of the given node
18315 (see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
18316 */
18317 baseIndentFor(node) {
18318 let line = this.state.doc.lineAt(node.from);
18319 // Skip line starts that are covered by a sibling (or cousin, etc)
18320 for (;;) {
18321 let atBreak = node.resolve(line.from);
18322 while (atBreak.parent && atBreak.parent.from == atBreak.from)
18323 atBreak = atBreak.parent;
18324 if (isParent(atBreak, node))
18325 break;
18326 line = this.state.doc.lineAt(atBreak.from);
18327 }
18328 return this.lineIndent(line.from);
18329 }
18330 /**
18331 Continue looking for indentations in the node's parent nodes,
18332 and return the result of that.
18333 */
18334 continue() {
18335 return indentFor(this.context.next, this.base, this.pos);
18336 }
18337 }
18338 function isParent(parent, of) {
18339 for (let cur = of; cur; cur = cur.parent)
18340 if (parent == cur)
18341 return true;
18342 return false;
18343 }
18344 // Check whether a delimited node is aligned (meaning there are
18345 // non-skipped nodes on the same line as the opening delimiter). And
18346 // if so, return the opening token.
18347 function bracketedAligned(context) {
18348 let tree = context.node;
18349 let openToken = tree.childAfter(tree.from), last = tree.lastChild;
18350 if (!openToken)
18351 return null;
18352 let sim = context.options.simulateBreak;
18353 let openLine = context.state.doc.lineAt(openToken.from);
18354 let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
18355 for (let pos = openToken.to;;) {
18356 let next = tree.childAfter(pos);
18357 if (!next || next == last)
18358 return null;
18359 if (!next.type.isSkipped)
18360 return next.from < lineEnd ? openToken : null;
18361 pos = next.to;
18362 }
18363 }
18364 /**
18365 An indentation strategy for delimited (usually bracketed) nodes.
18366 Will, by default, indent one unit more than the parent's base
18367 indent unless the line starts with a closing token. When `align`
18368 is true and there are non-skipped nodes on the node's opening
18369 line, the content of the node will be aligned with the end of the
18370 opening node, like this:
18371
18372 foo(bar,
18373 baz)
18374 */
18375 function delimitedIndent({ closing, align = true, units = 1 }) {
18376 return (context) => delimitedStrategy(context, align, units, closing);
18377 }
18378 function delimitedStrategy(context, align, units, closing, closedAt) {
18379 let after = context.textAfter, space = after.match(/^\s*/)[0].length;
18380 let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
18381 let aligned = align ? bracketedAligned(context) : null;
18382 if (aligned)
18383 return closed ? context.column(aligned.from) : context.column(aligned.to);
18384 return context.baseIndent + (closed ? 0 : context.unit * units);
18385 }
18386 /**
18387 An indentation strategy that aligns a node's content to its base
18388 indentation.
18389 */
18390 const flatIndent = (context) => context.baseIndent;
18391 /**
18392 Creates an indentation strategy that, by default, indents
18393 continued lines one unit more than the node's base indentation.
18394 You can provide `except` to prevent indentation of lines that
18395 match a pattern (for example `/^else\b/` in `if`/`else`
18396 constructs), and you can change the amount of units used with the
18397 `units` option.
18398 */
18399 function continuedIndent({ except, units = 1 } = {}) {
18400 return (context) => {
18401 let matchExcept = except && except.test(context.textAfter);
18402 return context.baseIndent + (matchExcept ? 0 : units * context.unit);
18403 };
18404 }
18405 const DontIndentBeyond = 200;
18406 /**
18407 Enables reindentation on input. When a language defines an
18408 `indentOnInput` field in its [language
18409 data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
18410 expression, the line at the cursor will be reindented whenever new
18411 text is typed and the input from the start of the line up to the
18412 cursor matches that regexp.
18413
18414 To avoid unneccesary reindents, it is recommended to start the
18415 regexp with `^` (usually followed by `\s*`), and end it with `$`.
18416 For example, `/^\s*\}$/` will reindent when a closing brace is
18417 added at the start of a line.
18418 */
18419 function indentOnInput() {
18420 return EditorState.transactionFilter.of(tr => {
18421 if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
18422 return tr;
18423 let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
18424 if (!rules.length)
18425 return tr;
18426 let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
18427 if (head > line.from + DontIndentBeyond)
18428 return tr;
18429 let lineStart = doc.sliceString(line.from, head);
18430 if (!rules.some(r => r.test(lineStart)))
18431 return tr;
18432 let { state } = tr, last = -1, changes = [];
18433 for (let { head } of state.selection.ranges) {
18434 let line = state.doc.lineAt(head);
18435 if (line.from == last)
18436 continue;
18437 last = line.from;
18438 let indent = getIndentation(state, line.from);
18439 if (indent == null)
18440 continue;
18441 let cur = /^\s*/.exec(line.text)[0];
18442 let norm = indentString(state, indent);
18443 if (cur != norm)
18444 changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
18445 }
18446 return changes.length ? [tr, { changes, sequential: true }] : tr;
18447 });
18448 }
18449
18450 /**
18451 A facet that registers a code folding service. When called with
18452 the extent of a line, such a function should return a foldable
18453 range that starts on that line (but continues beyond it), if one
18454 can be found.
18455 */
18456 const foldService = /*@__PURE__*/Facet.define();
18457 /**
18458 This node prop is used to associate folding information with
18459 syntax node types. Given a syntax node, it should check whether
18460 that tree is foldable and return the range that can be collapsed
18461 when it is.
18462 */
18463 const foldNodeProp = /*@__PURE__*/new NodeProp();
18464 /**
18465 [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
18466 the first and the last child of a syntax node. Useful for nodes
18467 that start and end with delimiters.
18468 */
18469 function foldInside(node) {
18470 let first = node.firstChild, last = node.lastChild;
18471 return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
18472 }
18473 function syntaxFolding(state, start, end) {
18474 let tree = syntaxTree(state);
18475 if (tree.length < end)
18476 return null;
18477 let stack = tree.resolveStack(end, 1);
18478 let found = null;
18479 for (let iter = stack; iter; iter = iter.next) {
18480 let cur = iter.node;
18481 if (cur.to <= end || cur.from > end)
18482 continue;
18483 if (found && cur.from < start)
18484 break;
18485 let prop = cur.type.prop(foldNodeProp);
18486 if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
18487 let value = prop(cur, state);
18488 if (value && value.from <= end && value.from >= start && value.to > end)
18489 found = value;
18490 }
18491 }
18492 return found;
18493 }
18494 function isUnfinished(node) {
18495 let ch = node.lastChild;
18496 return ch && ch.to == node.to && ch.type.isError;
18497 }
18498 /**
18499 Check whether the given line is foldable. First asks any fold
18500 services registered through
18501 [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
18502 a result, tries to query the [fold node
18503 prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
18504 of the line.
18505 */
18506 function foldable(state, lineStart, lineEnd) {
18507 for (let service of state.facet(foldService)) {
18508 let result = service(state, lineStart, lineEnd);
18509 if (result)
18510 return result;
18511 }
18512 return syntaxFolding(state, lineStart, lineEnd);
18513 }
18514 function mapRange(range, mapping) {
18515 let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
18516 return from >= to ? undefined : { from, to };
18517 }
18518 /**
18519 State effect that can be attached to a transaction to fold the
18520 given range. (You probably only need this in exceptional
18521 circumstances—usually you'll just want to let
18522 [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
18523 gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
18524 */
18525 const foldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
18526 /**
18527 State effect that unfolds the given range (if it was folded).
18528 */
18529 const unfoldEffect = /*@__PURE__*/StateEffect.define({ map: mapRange });
18530 function selectedLines(view) {
18531 let lines = [];
18532 for (let { head } of view.state.selection.ranges) {
18533 if (lines.some(l => l.from <= head && l.to >= head))
18534 continue;
18535 lines.push(view.lineBlockAt(head));
18536 }
18537 return lines;
18538 }
18539 /**
18540 The state field that stores the folded ranges (as a [decoration
18541 set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
18542 [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
18543 [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
18544 state.
18545 */
18546 const foldState = /*@__PURE__*/StateField.define({
18547 create() {
18548 return Decoration.none;
18549 },
18550 update(folded, tr) {
18551 folded = folded.map(tr.changes);
18552 for (let e of tr.effects) {
18553 if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
18554 let { preparePlaceholder } = tr.state.facet(foldConfig);
18555 let widget = !preparePlaceholder ? foldWidget :
18556 Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) });
18557 folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] });
18558 }
18559 else if (e.is(unfoldEffect)) {
18560 folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
18561 filterFrom: e.value.from, filterTo: e.value.to });
18562 }
18563 }
18564 // Clear folded ranges that cover the selection head
18565 if (tr.selection) {
18566 let onSelection = false, { head } = tr.selection.main;
18567 folded.between(head, head, (a, b) => { if (a < head && b > head)
18568 onSelection = true; });
18569 if (onSelection)
18570 folded = folded.update({
18571 filterFrom: head,
18572 filterTo: head,
18573 filter: (a, b) => b <= head || a >= head
18574 });
18575 }
18576 return folded;
18577 },
18578 provide: f => EditorView.decorations.from(f),
18579 toJSON(folded, state) {
18580 let ranges = [];
18581 folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });
18582 return ranges;
18583 },
18584 fromJSON(value) {
18585 if (!Array.isArray(value) || value.length % 2)
18586 throw new RangeError("Invalid JSON for fold state");
18587 let ranges = [];
18588 for (let i = 0; i < value.length;) {
18589 let from = value[i++], to = value[i++];
18590 if (typeof from != "number" || typeof to != "number")
18591 throw new RangeError("Invalid JSON for fold state");
18592 ranges.push(foldWidget.range(from, to));
18593 }
18594 return Decoration.set(ranges, true);
18595 }
18596 });
18597 /**
18598 Get a [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) containing the folded ranges
18599 in the given state.
18600 */
18601 function foldedRanges(state) {
18602 return state.field(foldState, false) || RangeSet.empty;
18603 }
18604 function findFold(state, from, to) {
18605 var _a;
18606 let found = null;
18607 (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
18608 if (!found || found.from > from)
18609 found = { from, to };
18610 });
18611 return found;
18612 }
18613 function foldExists(folded, from, to) {
18614 let found = false;
18615 folded.between(from, from, (a, b) => { if (a == from && b == to)
18616 found = true; });
18617 return found;
18618 }
18619 function maybeEnable(state, other) {
18620 return state.field(foldState, false) ? other : other.concat(StateEffect.appendConfig.of(codeFolding()));
18621 }
18622 /**
18623 Fold the lines that are selected, if possible.
18624 */
18625 const foldCode = view => {
18626 for (let line of selectedLines(view)) {
18627 let range = foldable(view.state, line.from, line.to);
18628 if (range) {
18629 view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
18630 return true;
18631 }
18632 }
18633 return false;
18634 };
18635 /**
18636 Unfold folded ranges on selected lines.
18637 */
18638 const unfoldCode = view => {
18639 if (!view.state.field(foldState, false))
18640 return false;
18641 let effects = [];
18642 for (let line of selectedLines(view)) {
18643 let folded = findFold(view.state, line.from, line.to);
18644 if (folded)
18645 effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
18646 }
18647 if (effects.length)
18648 view.dispatch({ effects });
18649 return effects.length > 0;
18650 };
18651 function announceFold(view, range, fold = true) {
18652 let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number;
18653 return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
18654 }
18655 /**
18656 Fold all top-level foldable ranges. Note that, in most cases,
18657 folding information will depend on the [syntax
18658 tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
18659 reliably when the document hasn't been fully parsed (either
18660 because the editor state was only just initialized, or because the
18661 document is so big that the parser decided not to parse it
18662 entirely).
18663 */
18664 const foldAll = view => {
18665 let { state } = view, effects = [];
18666 for (let pos = 0; pos < state.doc.length;) {
18667 let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
18668 if (range)
18669 effects.push(foldEffect.of(range));
18670 pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
18671 }
18672 if (effects.length)
18673 view.dispatch({ effects: maybeEnable(view.state, effects) });
18674 return !!effects.length;
18675 };
18676 /**
18677 Unfold all folded code.
18678 */
18679 const unfoldAll = view => {
18680 let field = view.state.field(foldState, false);
18681 if (!field || !field.size)
18682 return false;
18683 let effects = [];
18684 field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
18685 view.dispatch({ effects });
18686 return true;
18687 };
18688 // Find the foldable region containing the given line, if one exists
18689 function foldableContainer(view, lineBlock) {
18690 // Look backwards through line blocks until we find a foldable region that
18691 // intersects with the line
18692 for (let line = lineBlock;;) {
18693 let foldableRegion = foldable(view.state, line.from, line.to);
18694 if (foldableRegion && foldableRegion.to > lineBlock.from)
18695 return foldableRegion;
18696 if (!line.from)
18697 return null;
18698 line = view.lineBlockAt(line.from - 1);
18699 }
18700 }
18701 /**
18702 Toggle folding at cursors. Unfolds if there is an existing fold
18703 starting in that line, tries to find a foldable range around it
18704 otherwise.
18705 */
18706 const toggleFold = (view) => {
18707 let effects = [];
18708 for (let line of selectedLines(view)) {
18709 let folded = findFold(view.state, line.from, line.to);
18710 if (folded) {
18711 effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
18712 }
18713 else {
18714 let foldRange = foldableContainer(view, line);
18715 if (foldRange)
18716 effects.push(foldEffect.of(foldRange), announceFold(view, foldRange));
18717 }
18718 }
18719 if (effects.length > 0)
18720 view.dispatch({ effects: maybeEnable(view.state, effects) });
18721 return !!effects.length;
18722 };
18723 /**
18724 Default fold-related key bindings.
18725
18726 - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
18727 - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
18728 - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
18729 - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
18730 */
18731 const foldKeymap = [
18732 { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
18733 { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
18734 { key: "Ctrl-Alt-[", run: foldAll },
18735 { key: "Ctrl-Alt-]", run: unfoldAll }
18736 ];
18737 const defaultConfig = {
18738 placeholderDOM: null,
18739 preparePlaceholder: null,
18740 placeholderText: "…"
18741 };
18742 const foldConfig = /*@__PURE__*/Facet.define({
18743 combine(values) { return combineConfig(values, defaultConfig); }
18744 });
18745 /**
18746 Create an extension that configures code folding.
18747 */
18748 function codeFolding(config) {
18749 let result = [foldState, baseTheme$1$1];
18750 if (config)
18751 result.push(foldConfig.of(config));
18752 return result;
18753 }
18754 function widgetToDOM(view, prepared) {
18755 let { state } = view, conf = state.facet(foldConfig);
18756 let onclick = (event) => {
18757 let line = view.lineBlockAt(view.posAtDOM(event.target));
18758 let folded = findFold(view.state, line.from, line.to);
18759 if (folded)
18760 view.dispatch({ effects: unfoldEffect.of(folded) });
18761 event.preventDefault();
18762 };
18763 if (conf.placeholderDOM)
18764 return conf.placeholderDOM(view, onclick, prepared);
18765 let element = document.createElement("span");
18766 element.textContent = conf.placeholderText;
18767 element.setAttribute("aria-label", state.phrase("folded code"));
18768 element.title = state.phrase("unfold");
18769 element.className = "cm-foldPlaceholder";
18770 element.onclick = onclick;
18771 return element;
18772 }
18773 const foldWidget = /*@__PURE__*/Decoration.replace({ widget: /*@__PURE__*/new class extends WidgetType {
18774 toDOM(view) { return widgetToDOM(view, null); }
18775 } });
18776 class PreparedFoldWidget extends WidgetType {
18777 constructor(value) {
18778 super();
18779 this.value = value;
18780 }
18781 eq(other) { return this.value == other.value; }
18782 toDOM(view) { return widgetToDOM(view, this.value); }
18783 }
18784 const foldGutterDefaults = {
18785 openText: "⌄",
18786 closedText: "›",
18787 markerDOM: null,
18788 domEventHandlers: {},
18789 foldingChanged: () => false
18790 };
18791 class FoldMarker extends GutterMarker {
18792 constructor(config, open) {
18793 super();
18794 this.config = config;
18795 this.open = open;
18796 }
18797 eq(other) { return this.config == other.config && this.open == other.open; }
18798 toDOM(view) {
18799 if (this.config.markerDOM)
18800 return this.config.markerDOM(this.open);
18801 let span = document.createElement("span");
18802 span.textContent = this.open ? this.config.openText : this.config.closedText;
18803 span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
18804 return span;
18805 }
18806 }
18807 /**
18808 Create an extension that registers a fold gutter, which shows a
18809 fold status indicator before foldable lines (which can be clicked
18810 to fold or unfold the line).
18811 */
18812 function foldGutter(config = {}) {
18813 let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
18814 let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
18815 let markers = ViewPlugin.fromClass(class {
18816 constructor(view) {
18817 this.from = view.viewport.from;
18818 this.markers = this.buildMarkers(view);
18819 }
18820 update(update) {
18821 if (update.docChanged || update.viewportChanged ||
18822 update.startState.facet(language) != update.state.facet(language) ||
18823 update.startState.field(foldState, false) != update.state.field(foldState, false) ||
18824 syntaxTree(update.startState) != syntaxTree(update.state) ||
18825 fullConfig.foldingChanged(update))
18826 this.markers = this.buildMarkers(update.view);
18827 }
18828 buildMarkers(view) {
18829 let builder = new RangeSetBuilder();
18830 for (let line of view.viewportLineBlocks) {
18831 let mark = findFold(view.state, line.from, line.to) ? canUnfold
18832 : foldable(view.state, line.from, line.to) ? canFold : null;
18833 if (mark)
18834 builder.add(line.from, line.from, mark);
18835 }
18836 return builder.finish();
18837 }
18838 });
18839 let { domEventHandlers } = fullConfig;
18840 return [
18841 markers,
18842 gutter({
18843 class: "cm-foldGutter",
18844 markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },
18845 initialSpacer() {
18846 return new FoldMarker(fullConfig, false);
18847 },
18848 domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
18849 if (domEventHandlers.click && domEventHandlers.click(view, line, event))
18850 return true;
18851 let folded = findFold(view.state, line.from, line.to);
18852 if (folded) {
18853 view.dispatch({ effects: unfoldEffect.of(folded) });
18854 return true;
18855 }
18856 let range = foldable(view.state, line.from, line.to);
18857 if (range) {
18858 view.dispatch({ effects: foldEffect.of(range) });
18859 return true;
18860 }
18861 return false;
18862 } })
18863 }),
18864 codeFolding()
18865 ];
18866 }
18867 const baseTheme$1$1 = /*@__PURE__*/EditorView.baseTheme({
18868 ".cm-foldPlaceholder": {
18869 backgroundColor: "#eee",
18870 border: "1px solid #ddd",
18871 color: "#888",
18872 borderRadius: ".2em",
18873 margin: "0 1px",
18874 padding: "0 1px",
18875 cursor: "pointer"
18876 },
18877 ".cm-foldGutter span": {
18878 padding: "0 1px",
18879 cursor: "pointer"
18880 }
18881 });
18882
18883 /**
18884 A highlight style associates CSS styles with higlighting
18885 [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
18886 */
18887 class HighlightStyle {
18888 constructor(
18889 /**
18890 The tag styles used to create this highlight style.
18891 */
18892 specs, options) {
18893 this.specs = specs;
18894 let modSpec;
18895 function def(spec) {
18896 let cls = StyleModule.newName();
18897 (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
18898 return cls;
18899 }
18900 const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
18901 const scopeOpt = options.scope;
18902 this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
18903 : scopeOpt ? (type) => type == scopeOpt : undefined;
18904 this.style = tagHighlighter(specs.map(style => ({
18905 tag: style.tag,
18906 class: style.class || def(Object.assign({}, style, { tag: null }))
18907 })), {
18908 all,
18909 }).style;
18910 this.module = modSpec ? new StyleModule(modSpec) : null;
18911 this.themeType = options.themeType;
18912 }
18913 /**
18914 Create a highlighter style that associates the given styles to
18915 the given tags. The specs must be objects that hold a style tag
18916 or array of tags in their `tag` property, and either a single
18917 `class` property providing a static CSS class (for highlighter
18918 that rely on external styling), or a
18919 [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
18920 set of CSS properties (which define the styling for those tags).
18921
18922 The CSS rules created for a highlighter will be emitted in the
18923 order of the spec's properties. That means that for elements that
18924 have multiple tags associated with them, styles defined further
18925 down in the list will have a higher CSS precedence than styles
18926 defined earlier.
18927 */
18928 static define(specs, options) {
18929 return new HighlightStyle(specs, options || {});
18930 }
18931 }
18932 const highlighterFacet = /*@__PURE__*/Facet.define();
18933 const fallbackHighlighter = /*@__PURE__*/Facet.define({
18934 combine(values) { return values.length ? [values[0]] : null; }
18935 });
18936 function getHighlighters(state) {
18937 let main = state.facet(highlighterFacet);
18938 return main.length ? main : state.facet(fallbackHighlighter);
18939 }
18940 /**
18941 Wrap a highlighter in an editor extension that uses it to apply
18942 syntax highlighting to the editor content.
18943
18944 When multiple (non-fallback) styles are provided, the styling
18945 applied is the union of the classes they emit.
18946 */
18947 function syntaxHighlighting(highlighter, options) {
18948 let ext = [treeHighlighter], themeType;
18949 if (highlighter instanceof HighlightStyle) {
18950 if (highlighter.module)
18951 ext.push(EditorView.styleModule.of(highlighter.module));
18952 themeType = highlighter.themeType;
18953 }
18954 if (options === null || options === void 0 ? void 0 : options.fallback)
18955 ext.push(fallbackHighlighter.of(highlighter));
18956 else if (themeType)
18957 ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
18958 return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
18959 }));
18960 else
18961 ext.push(highlighterFacet.of(highlighter));
18962 return ext;
18963 }
18964 /**
18965 Returns the CSS classes (if any) that the highlighters active in
18966 the state would assign to the given style
18967 [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag) and
18968 (optional) language
18969 [scope](https://codemirror.net/6/docs/ref/#language.HighlightStyle^define^options.scope).
18970 */
18971 function highlightingFor(state, tags, scope) {
18972 let highlighters = getHighlighters(state);
18973 let result = null;
18974 if (highlighters)
18975 for (let highlighter of highlighters) {
18976 if (!highlighter.scope || scope && highlighter.scope(scope)) {
18977 let cls = highlighter.style(tags);
18978 if (cls)
18979 result = result ? result + " " + cls : cls;
18980 }
18981 }
18982 return result;
18983 }
18984 class TreeHighlighter {
18985 constructor(view) {
18986 this.markCache = Object.create(null);
18987 this.tree = syntaxTree(view.state);
18988 this.decorations = this.buildDeco(view, getHighlighters(view.state));
18989 }
18990 update(update) {
18991 let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
18992 let styleChange = highlighters != getHighlighters(update.startState);
18993 if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) {
18994 this.decorations = this.decorations.map(update.changes);
18995 }
18996 else if (tree != this.tree || update.viewportChanged || styleChange) {
18997 this.tree = tree;
18998 this.decorations = this.buildDeco(update.view, highlighters);
18999 }
19000 }
19001 buildDeco(view, highlighters) {
19002 if (!highlighters || !this.tree.length)
19003 return Decoration.none;
19004 let builder = new RangeSetBuilder();
19005 for (let { from, to } of view.visibleRanges) {
19006 highlightTree(this.tree, highlighters, (from, to, style) => {
19007 builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
19008 }, from, to);
19009 }
19010 return builder.finish();
19011 }
19012 }
19013 const treeHighlighter = /*@__PURE__*/Prec.high(/*@__PURE__*/ViewPlugin.fromClass(TreeHighlighter, {
19014 decorations: v => v.decorations
19015 }));
19016 /**
19017 A default highlight style (works well with light themes).
19018 */
19019 const defaultHighlightStyle = /*@__PURE__*/HighlightStyle.define([
19020 { tag: tags.meta,
19021 color: "#404740" },
19022 { tag: tags.link,
19023 textDecoration: "underline" },
19024 { tag: tags.heading,
19025 textDecoration: "underline",
19026 fontWeight: "bold" },
19027 { tag: tags.emphasis,
19028 fontStyle: "italic" },
19029 { tag: tags.strong,
19030 fontWeight: "bold" },
19031 { tag: tags.strikethrough,
19032 textDecoration: "line-through" },
19033 { tag: tags.keyword,
19034 color: "#708" },
19035 { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
19036 color: "#219" },
19037 { tag: [tags.literal, tags.inserted],
19038 color: "#164" },
19039 { tag: [tags.string, tags.deleted],
19040 color: "#a11" },
19041 { tag: [tags.regexp, tags.escape, /*@__PURE__*/tags.special(tags.string)],
19042 color: "#e40" },
19043 { tag: /*@__PURE__*/tags.definition(tags.variableName),
19044 color: "#00f" },
19045 { tag: /*@__PURE__*/tags.local(tags.variableName),
19046 color: "#30a" },
19047 { tag: [tags.typeName, tags.namespace],
19048 color: "#085" },
19049 { tag: tags.className,
19050 color: "#167" },
19051 { tag: [/*@__PURE__*/tags.special(tags.variableName), tags.macroName],
19052 color: "#256" },
19053 { tag: /*@__PURE__*/tags.definition(tags.propertyName),
19054 color: "#00c" },
19055 { tag: tags.comment,
19056 color: "#940" },
19057 { tag: tags.invalid,
19058 color: "#f00" }
19059 ]);
19060
19061 const baseTheme$2 = /*@__PURE__*/EditorView.baseTheme({
19062 "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
19063 "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
19064 });
19065 const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
19066 const bracketMatchingConfig = /*@__PURE__*/Facet.define({
19067 combine(configs) {
19068 return combineConfig(configs, {
19069 afterCursor: true,
19070 brackets: DefaultBrackets,
19071 maxScanDistance: DefaultScanDist,
19072 renderMatch: defaultRenderMatch
19073 });
19074 }
19075 });
19076 const matchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = /*@__PURE__*/Decoration.mark({ class: "cm-nonmatchingBracket" });
19077 function defaultRenderMatch(match) {
19078 let decorations = [];
19079 let mark = match.matched ? matchingMark : nonmatchingMark;
19080 decorations.push(mark.range(match.start.from, match.start.to));
19081 if (match.end)
19082 decorations.push(mark.range(match.end.from, match.end.to));
19083 return decorations;
19084 }
19085 const bracketMatchingState = /*@__PURE__*/StateField.define({
19086 create() { return Decoration.none; },
19087 update(deco, tr) {
19088 if (!tr.docChanged && !tr.selection)
19089 return deco;
19090 let decorations = [];
19091 let config = tr.state.facet(bracketMatchingConfig);
19092 for (let range of tr.state.selection.ranges) {
19093 if (!range.empty)
19094 continue;
19095 let match = matchBrackets(tr.state, range.head, -1, config)
19096 || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
19097 || (config.afterCursor &&
19098 (matchBrackets(tr.state, range.head, 1, config) ||
19099 (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
19100 if (match)
19101 decorations = decorations.concat(config.renderMatch(match, tr.state));
19102 }
19103 return Decoration.set(decorations, true);
19104 },
19105 provide: f => EditorView.decorations.from(f)
19106 });
19107 const bracketMatchingUnique = [
19108 bracketMatchingState,
19109 baseTheme$2
19110 ];
19111 /**
19112 Create an extension that enables bracket matching. Whenever the
19113 cursor is next to a bracket, that bracket and the one it matches
19114 are highlighted. Or, when no matching bracket is found, another
19115 highlighting style is used to indicate this.
19116 */
19117 function bracketMatching(config = {}) {
19118 return [bracketMatchingConfig.of(config), bracketMatchingUnique];
19119 }
19120 /**
19121 When larger syntax nodes, such as HTML tags, are marked as
19122 opening/closing, it can be a bit messy to treat the whole node as
19123 a matchable bracket. This node prop allows you to define, for such
19124 a node, a ‘handle’—the part of the node that is highlighted, and
19125 that the cursor must be on to activate highlighting in the first
19126 place.
19127 */
19128 const bracketMatchingHandle = /*@__PURE__*/new NodeProp();
19129 function matchingNodes(node, dir, brackets) {
19130 let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
19131 if (byProp)
19132 return byProp;
19133 if (node.name.length == 1) {
19134 let index = brackets.indexOf(node.name);
19135 if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
19136 return [brackets[index + dir]];
19137 }
19138 return null;
19139 }
19140 function findHandle(node) {
19141 let hasHandle = node.type.prop(bracketMatchingHandle);
19142 return hasHandle ? hasHandle(node.node) : node;
19143 }
19144 /**
19145 Find the matching bracket for the token at `pos`, scanning
19146 direction `dir`. Only the `brackets` and `maxScanDistance`
19147 properties are used from `config`, if given. Returns null if no
19148 bracket was found at `pos`, or a match result otherwise.
19149 */
19150 function matchBrackets(state, pos, dir, config = {}) {
19151 let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
19152 let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
19153 for (let cur = node; cur; cur = cur.parent) {
19154 let matches = matchingNodes(cur.type, dir, brackets);
19155 if (matches && cur.from < cur.to) {
19156 let handle = findHandle(cur);
19157 if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to))
19158 return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets);
19159 }
19160 }
19161 return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
19162 }
19163 function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
19164 let parent = token.parent, firstToken = { from: handle.from, to: handle.to };
19165 let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
19166 if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
19167 do {
19168 if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
19169 if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
19170 let endHandle = findHandle(cursor);
19171 return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : undefined, matched: true };
19172 }
19173 else if (matchingNodes(cursor.type, dir, brackets)) {
19174 depth++;
19175 }
19176 else if (matchingNodes(cursor.type, -dir, brackets)) {
19177 if (depth == 0) {
19178 let endHandle = findHandle(cursor);
19179 return {
19180 start: firstToken,
19181 end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : undefined,
19182 matched: false
19183 };
19184 }
19185 depth--;
19186 }
19187 }
19188 } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
19189 return { start: firstToken, matched: false };
19190 }
19191 function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
19192 let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
19193 let bracket = brackets.indexOf(startCh);
19194 if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
19195 return null;
19196 let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
19197 let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
19198 for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
19199 let text = iter.value;
19200 if (dir < 0)
19201 distance += text.length;
19202 let basePos = pos + distance * dir;
19203 for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
19204 let found = brackets.indexOf(text[pos]);
19205 if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)
19206 continue;
19207 if ((found % 2 == 0) == (dir > 0)) {
19208 depth++;
19209 }
19210 else if (depth == 1) { // Closing
19211 return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
19212 }
19213 else {
19214 depth--;
19215 }
19216 }
19217 if (dir > 0)
19218 distance += text.length;
19219 }
19220 return iter.done ? { start: startToken, matched: false } : null;
19221 }
19222
19223 // Counts the column offset in a string, taking tabs into account.
19224 // Used mostly to find indentation.
19225 function countCol(string, end, tabSize, startIndex = 0, startValue = 0) {
19226 if (end == null) {
19227 end = string.search(/[^\s\u00a0]/);
19228 if (end == -1)
19229 end = string.length;
19230 }
19231 let n = startValue;
19232 for (let i = startIndex; i < end; i++) {
19233 if (string.charCodeAt(i) == 9)
19234 n += tabSize - (n % tabSize);
19235 else
19236 n++;
19237 }
19238 return n;
19239 }
19240 /**
19241 Encapsulates a single line of input. Given to stream syntax code,
19242 which uses it to tokenize the content.
19243 */
19244 class StringStream {
19245 /**
19246 Create a stream.
19247 */
19248 constructor(
19249 /**
19250 The line.
19251 */
19252 string, tabSize,
19253 /**
19254 The current indent unit size.
19255 */
19256 indentUnit, overrideIndent) {
19257 this.string = string;
19258 this.tabSize = tabSize;
19259 this.indentUnit = indentUnit;
19260 this.overrideIndent = overrideIndent;
19261 /**
19262 The current position on the line.
19263 */
19264 this.pos = 0;
19265 /**
19266 The start position of the current token.
19267 */
19268 this.start = 0;
19269 this.lastColumnPos = 0;
19270 this.lastColumnValue = 0;
19271 }
19272 /**
19273 True if we are at the end of the line.
19274 */
19275 eol() { return this.pos >= this.string.length; }
19276 /**
19277 True if we are at the start of the line.
19278 */
19279 sol() { return this.pos == 0; }
19280 /**
19281 Get the next code unit after the current position, or undefined
19282 if we're at the end of the line.
19283 */
19284 peek() { return this.string.charAt(this.pos) || undefined; }
19285 /**
19286 Read the next code unit and advance `this.pos`.
19287 */
19288 next() {
19289 if (this.pos < this.string.length)
19290 return this.string.charAt(this.pos++);
19291 }
19292 /**
19293 Match the next character against the given string, regular
19294 expression, or predicate. Consume and return it if it matches.
19295 */
19296 eat(match) {
19297 let ch = this.string.charAt(this.pos);
19298 let ok;
19299 if (typeof match == "string")
19300 ok = ch == match;
19301 else
19302 ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
19303 if (ok) {
19304 ++this.pos;
19305 return ch;
19306 }
19307 }
19308 /**
19309 Continue matching characters that match the given string,
19310 regular expression, or predicate function. Return true if any
19311 characters were consumed.
19312 */
19313 eatWhile(match) {
19314 let start = this.pos;
19315 while (this.eat(match)) { }
19316 return this.pos > start;
19317 }
19318 /**
19319 Consume whitespace ahead of `this.pos`. Return true if any was
19320 found.
19321 */
19322 eatSpace() {
19323 let start = this.pos;
19324 while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
19325 ++this.pos;
19326 return this.pos > start;
19327 }
19328 /**
19329 Move to the end of the line.
19330 */
19331 skipToEnd() { this.pos = this.string.length; }
19332 /**
19333 Move to directly before the given character, if found on the
19334 current line.
19335 */
19336 skipTo(ch) {
19337 let found = this.string.indexOf(ch, this.pos);
19338 if (found > -1) {
19339 this.pos = found;
19340 return true;
19341 }
19342 }
19343 /**
19344 Move back `n` characters.
19345 */
19346 backUp(n) { this.pos -= n; }
19347 /**
19348 Get the column position at `this.pos`.
19349 */
19350 column() {
19351 if (this.lastColumnPos < this.start) {
19352 this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
19353 this.lastColumnPos = this.start;
19354 }
19355 return this.lastColumnValue;
19356 }
19357 /**
19358 Get the indentation column of the current line.
19359 */
19360 indentation() {
19361 var _a;
19362 return (_a = this.overrideIndent) !== null && _a !== void 0 ? _a : countCol(this.string, null, this.tabSize);
19363 }
19364 /**
19365 Match the input against the given string or regular expression
19366 (which should start with a `^`). Return true or the regexp match
19367 if it matches.
19368
19369 Unless `consume` is set to `false`, this will move `this.pos`
19370 past the matched text.
19371
19372 When matching a string `caseInsensitive` can be set to true to
19373 make the match case-insensitive.
19374 */
19375 match(pattern, consume, caseInsensitive) {
19376 if (typeof pattern == "string") {
19377 let cased = (str) => caseInsensitive ? str.toLowerCase() : str;
19378 let substr = this.string.substr(this.pos, pattern.length);
19379 if (cased(substr) == cased(pattern)) {
19380 if (consume !== false)
19381 this.pos += pattern.length;
19382 return true;
19383 }
19384 else
19385 return null;
19386 }
19387 else {
19388 let match = this.string.slice(this.pos).match(pattern);
19389 if (match && match.index > 0)
19390 return null;
19391 if (match && consume !== false)
19392 this.pos += match[0].length;
19393 return match;
19394 }
19395 }
19396 /**
19397 Get the current token.
19398 */
19399 current() { return this.string.slice(this.start, this.pos); }
19400 }
19401
19402 function fullParser(spec) {
19403 return {
19404 name: spec.name || "",
19405 token: spec.token,
19406 blankLine: spec.blankLine || (() => { }),
19407 startState: spec.startState || (() => true),
19408 copyState: spec.copyState || defaultCopyState,
19409 indent: spec.indent || (() => null),
19410 languageData: spec.languageData || {},
19411 tokenTable: spec.tokenTable || noTokens
19412 };
19413 }
19414 function defaultCopyState(state) {
19415 if (typeof state != "object")
19416 return state;
19417 let newState = {};
19418 for (let prop in state) {
19419 let val = state[prop];
19420 newState[prop] = (val instanceof Array ? val.slice() : val);
19421 }
19422 return newState;
19423 }
19424 const IndentedFrom = /*@__PURE__*/new WeakMap();
19425 /**
19426 A [language](https://codemirror.net/6/docs/ref/#language.Language) class based on a CodeMirror
19427 5-style [streaming parser](https://codemirror.net/6/docs/ref/#language.StreamParser).
19428 */
19429 class StreamLanguage extends Language {
19430 constructor(parser) {
19431 let data = defineLanguageFacet(parser.languageData);
19432 let p = fullParser(parser), self;
19433 let impl = new class extends Parser {
19434 createParse(input, fragments, ranges) {
19435 return new Parse(self, input, fragments, ranges);
19436 }
19437 };
19438 super(data, impl, [indentService.of((cx, pos) => this.getIndent(cx, pos))], parser.name);
19439 this.topNode = docID(data);
19440 self = this;
19441 this.streamParser = p;
19442 this.stateAfter = new NodeProp({ perNode: true });
19443 this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;
19444 }
19445 /**
19446 Define a stream language.
19447 */
19448 static define(spec) { return new StreamLanguage(spec); }
19449 getIndent(cx, pos) {
19450 let tree = syntaxTree(cx.state), at = tree.resolve(pos);
19451 while (at && at.type != this.topNode)
19452 at = at.parent;
19453 if (!at)
19454 return null;
19455 let from = undefined;
19456 let { overrideIndentation } = cx.options;
19457 if (overrideIndentation) {
19458 from = IndentedFrom.get(cx.state);
19459 if (from != null && from < pos - 1e4)
19460 from = undefined;
19461 }
19462 let start = findState(this, tree, 0, at.from, from !== null && from !== void 0 ? from : pos), statePos, state;
19463 if (start) {
19464 state = start.state;
19465 statePos = start.pos + 1;
19466 }
19467 else {
19468 state = this.streamParser.startState(cx.unit);
19469 statePos = 0;
19470 }
19471 if (pos - statePos > 10000 /* C.MaxIndentScanDist */)
19472 return null;
19473 while (statePos < pos) {
19474 let line = cx.state.doc.lineAt(statePos), end = Math.min(pos, line.to);
19475 if (line.length) {
19476 let indentation = overrideIndentation ? overrideIndentation(line.from) : -1;
19477 let stream = new StringStream(line.text, cx.state.tabSize, cx.unit, indentation < 0 ? undefined : indentation);
19478 while (stream.pos < end - line.from)
19479 readToken(this.streamParser.token, stream, state);
19480 }
19481 else {
19482 this.streamParser.blankLine(state, cx.unit);
19483 }
19484 if (end == pos)
19485 break;
19486 statePos = line.to + 1;
19487 }
19488 let line = cx.lineAt(pos);
19489 if (overrideIndentation && from == null)
19490 IndentedFrom.set(cx.state, line.from);
19491 return this.streamParser.indent(state, /^\s*(.*)/.exec(line.text)[1], cx);
19492 }
19493 get allowsNesting() { return false; }
19494 }
19495 function findState(lang, tree, off, startPos, before) {
19496 let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
19497 if (state)
19498 return { state: lang.streamParser.copyState(state), pos: off + tree.length };
19499 for (let i = tree.children.length - 1; i >= 0; i--) {
19500 let child = tree.children[i], pos = off + tree.positions[i];
19501 let found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before);
19502 if (found)
19503 return found;
19504 }
19505 return null;
19506 }
19507 function cutTree(lang, tree, from, to, inside) {
19508 if (inside && from <= 0 && to >= tree.length)
19509 return tree;
19510 if (!inside && tree.type == lang.topNode)
19511 inside = true;
19512 for (let i = tree.children.length - 1; i >= 0; i--) {
19513 let pos = tree.positions[i], child = tree.children[i], inner;
19514 if (pos < to && child instanceof Tree) {
19515 if (!(inner = cutTree(lang, child, from - pos, to - pos, inside)))
19516 break;
19517 return !inside ? inner
19518 : new Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
19519 }
19520 }
19521 return null;
19522 }
19523 function findStartInFragments(lang, fragments, startPos, editorState) {
19524 for (let f of fragments) {
19525 let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
19526 let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree;
19527 if (found && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
19528 return { state: found.state, tree };
19529 }
19530 return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty };
19531 }
19532 class Parse {
19533 constructor(lang, input, fragments, ranges) {
19534 this.lang = lang;
19535 this.input = input;
19536 this.fragments = fragments;
19537 this.ranges = ranges;
19538 this.stoppedAt = null;
19539 this.chunks = [];
19540 this.chunkPos = [];
19541 this.chunk = [];
19542 this.chunkReused = undefined;
19543 this.rangeIndex = 0;
19544 this.to = ranges[ranges.length - 1].to;
19545 let context = ParseContext.get(), from = ranges[0].from;
19546 let { state, tree } = findStartInFragments(lang, fragments, from, context === null || context === void 0 ? void 0 : context.state);
19547 this.state = state;
19548 this.parsedPos = this.chunkStart = from + tree.length;
19549 for (let i = 0; i < tree.children.length; i++) {
19550 this.chunks.push(tree.children[i]);
19551 this.chunkPos.push(tree.positions[i]);
19552 }
19553 if (context && this.parsedPos < context.viewport.from - 100000 /* C.MaxDistanceBeforeViewport */) {
19554 this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
19555 context.skipUntilInView(this.parsedPos, context.viewport.from);
19556 this.parsedPos = context.viewport.from;
19557 }
19558 this.moveRangeIndex();
19559 }
19560 advance() {
19561 let context = ParseContext.get();
19562 let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
19563 let end = Math.min(parseEnd, this.chunkStart + 2048 /* C.ChunkSize */);
19564 if (context)
19565 end = Math.min(end, context.viewport.to);
19566 while (this.parsedPos < end)
19567 this.parseLine(context);
19568 if (this.chunkStart < this.parsedPos)
19569 this.finishChunk();
19570 if (this.parsedPos >= parseEnd)
19571 return this.finish();
19572 if (context && this.parsedPos >= context.viewport.to) {
19573 context.skipUntilInView(this.parsedPos, parseEnd);
19574 return this.finish();
19575 }
19576 return null;
19577 }
19578 stopAt(pos) {
19579 this.stoppedAt = pos;
19580 }
19581 lineAfter(pos) {
19582 let chunk = this.input.chunk(pos);
19583 if (!this.input.lineChunks) {
19584 let eol = chunk.indexOf("\n");
19585 if (eol > -1)
19586 chunk = chunk.slice(0, eol);
19587 }
19588 else if (chunk == "\n") {
19589 chunk = "";
19590 }
19591 return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
19592 }
19593 nextLine() {
19594 let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
19595 for (let index = this.rangeIndex;;) {
19596 let rangeEnd = this.ranges[index].to;
19597 if (rangeEnd >= end)
19598 break;
19599 line = line.slice(0, rangeEnd - (end - line.length));
19600 index++;
19601 if (index == this.ranges.length)
19602 break;
19603 let rangeStart = this.ranges[index].from;
19604 let after = this.lineAfter(rangeStart);
19605 line += after;
19606 end = rangeStart + after.length;
19607 }
19608 return { line, end };
19609 }
19610 skipGapsTo(pos, offset, side) {
19611 for (;;) {
19612 let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
19613 if (side > 0 ? end > offPos : end >= offPos)
19614 break;
19615 let start = this.ranges[++this.rangeIndex].from;
19616 offset += start - end;
19617 }
19618 return offset;
19619 }
19620 moveRangeIndex() {
19621 while (this.ranges[this.rangeIndex].to < this.parsedPos)
19622 this.rangeIndex++;
19623 }
19624 emitToken(id, from, to, size, offset) {
19625 if (this.ranges.length > 1) {
19626 offset = this.skipGapsTo(from, offset, 1);
19627 from += offset;
19628 let len0 = this.chunk.length;
19629 offset = this.skipGapsTo(to, offset, -1);
19630 to += offset;
19631 size += this.chunk.length - len0;
19632 }
19633 this.chunk.push(id, from, to, size);
19634 return offset;
19635 }
19636 parseLine(context) {
19637 let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
19638 let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
19639 if (stream.eol()) {
19640 streamParser.blankLine(this.state, stream.indentUnit);
19641 }
19642 else {
19643 while (!stream.eol()) {
19644 let token = readToken(streamParser.token, stream, this.state);
19645 if (token)
19646 offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, 4, offset);
19647 if (stream.start > 10000 /* C.MaxLineLength */)
19648 break;
19649 }
19650 }
19651 this.parsedPos = end;
19652 this.moveRangeIndex();
19653 if (this.parsedPos < this.to)
19654 this.parsedPos++;
19655 }
19656 finishChunk() {
19657 let tree = Tree.build({
19658 buffer: this.chunk,
19659 start: this.chunkStart,
19660 length: this.parsedPos - this.chunkStart,
19661 nodeSet,
19662 topID: 0,
19663 maxBufferLength: 2048 /* C.ChunkSize */,
19664 reused: this.chunkReused
19665 });
19666 tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
19667 this.chunks.push(tree);
19668 this.chunkPos.push(this.chunkStart - this.ranges[0].from);
19669 this.chunk = [];
19670 this.chunkReused = undefined;
19671 this.chunkStart = this.parsedPos;
19672 }
19673 finish() {
19674 return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
19675 }
19676 }
19677 function readToken(token, stream, state) {
19678 stream.start = stream.pos;
19679 for (let i = 0; i < 10; i++) {
19680 let result = token(stream, state);
19681 if (stream.pos > stream.start)
19682 return result;
19683 }
19684 throw new Error("Stream parser failed to advance stream.");
19685 }
19686 const noTokens = /*@__PURE__*/Object.create(null);
19687 const typeArray = [NodeType.none];
19688 const nodeSet = /*@__PURE__*/new NodeSet(typeArray);
19689 const warned = [];
19690 // Cache of node types by name and tags
19691 const byTag = /*@__PURE__*/Object.create(null);
19692 const defaultTable = /*@__PURE__*/Object.create(null);
19693 for (let [legacyName, name] of [
19694 ["variable", "variableName"],
19695 ["variable-2", "variableName.special"],
19696 ["string-2", "string.special"],
19697 ["def", "variableName.definition"],
19698 ["tag", "tagName"],
19699 ["attribute", "attributeName"],
19700 ["type", "typeName"],
19701 ["builtin", "variableName.standard"],
19702 ["qualifier", "modifier"],
19703 ["error", "invalid"],
19704 ["header", "heading"],
19705 ["property", "propertyName"]
19706 ])
19707 defaultTable[legacyName] = /*@__PURE__*/createTokenType(noTokens, name);
19708 class TokenTable {
19709 constructor(extra) {
19710 this.extra = extra;
19711 this.table = Object.assign(Object.create(null), defaultTable);
19712 }
19713 resolve(tag) {
19714 return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
19715 }
19716 }
19717 const defaultTokenTable = /*@__PURE__*/new TokenTable(noTokens);
19718 function warnForPart(part, msg) {
19719 if (warned.indexOf(part) > -1)
19720 return;
19721 warned.push(part);
19722 console.warn(msg);
19723 }
19724 function createTokenType(extra, tagStr) {
19725 let tags$1 = [];
19726 for (let name of tagStr.split(" ")) {
19727 let found = [];
19728 for (let part of name.split(".")) {
19729 let value = (extra[part] || tags[part]);
19730 if (!value) {
19731 warnForPart(part, `Unknown highlighting tag ${part}`);
19732 }
19733 else if (typeof value == "function") {
19734 if (!found.length)
19735 warnForPart(part, `Modifier ${part} used at start of tag`);
19736 else
19737 found = found.map(value);
19738 }
19739 else {
19740 if (found.length)
19741 warnForPart(part, `Tag ${part} used as modifier`);
19742 else
19743 found = Array.isArray(value) ? value : [value];
19744 }
19745 }
19746 for (let tag of found)
19747 tags$1.push(tag);
19748 }
19749 if (!tags$1.length)
19750 return 0;
19751 let name = tagStr.replace(/ /g, "_"), key = name + " " + tags$1.map(t => t.id);
19752 let known = byTag[key];
19753 if (known)
19754 return known.id;
19755 let type = byTag[key] = NodeType.define({
19756 id: typeArray.length,
19757 name,
19758 props: [styleTags({ [name]: tags$1 })]
19759 });
19760 typeArray.push(type);
19761 return type.id;
19762 }
19763 function docID(data) {
19764 let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data)], top: true });
19765 typeArray.push(type);
19766 return type;
19767 }
19768
19769 /**
19770 Comment or uncomment the current selection. Will use line comments
19771 if available, otherwise falling back to block comments.
19772 */
19773 const toggleComment = target => {
19774 let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from);
19775 return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : false;
19776 };
19777 function command(f, option) {
19778 return ({ state, dispatch }) => {
19779 if (state.readOnly)
19780 return false;
19781 let tr = f(option, state);
19782 if (!tr)
19783 return false;
19784 dispatch(state.update(tr));
19785 return true;
19786 };
19787 }
19788 /**
19789 Comment or uncomment the current selection using line comments.
19790 The line comment syntax is taken from the
19791 [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
19792 data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
19793 */
19794 const toggleLineComment = /*@__PURE__*/command(changeLineComment, 0 /* CommentOption.Toggle */);
19795 /**
19796 Comment the current selection using line comments.
19797 */
19798 const lineComment = /*@__PURE__*/command(changeLineComment, 1 /* CommentOption.Comment */);
19799 /**
19800 Uncomment the current selection using line comments.
19801 */
19802 const lineUncomment = /*@__PURE__*/command(changeLineComment, 2 /* CommentOption.Uncomment */);
19803 /**
19804 Comment or uncomment the current selection using block comments.
19805 The block comment syntax is taken from the
19806 [`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
19807 data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
19808 */
19809 const toggleBlockComment = /*@__PURE__*/command(changeBlockComment, 0 /* CommentOption.Toggle */);
19810 /**
19811 Comment the current selection using block comments.
19812 */
19813 const blockComment = /*@__PURE__*/command(changeBlockComment, 1 /* CommentOption.Comment */);
19814 /**
19815 Uncomment the current selection using block comments.
19816 */
19817 const blockUncomment = /*@__PURE__*/command(changeBlockComment, 2 /* CommentOption.Uncomment */);
19818 /**
19819 Comment or uncomment the lines around the current selection using
19820 block comments.
19821 */
19822 const toggleBlockCommentByLine = /*@__PURE__*/command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0 /* CommentOption.Toggle */);
19823 function getConfig(state, pos) {
19824 let data = state.languageDataAt("commentTokens", pos);
19825 return data.length ? data[0] : {};
19826 }
19827 const SearchMargin = 50;
19828 /**
19829 Determines if the given range is block-commented in the given
19830 state.
19831 */
19832 function findBlockComment(state, { open, close }, from, to) {
19833 let textBefore = state.sliceDoc(from - SearchMargin, from);
19834 let textAfter = state.sliceDoc(to, to + SearchMargin);
19835 let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
19836 let beforeOff = textBefore.length - spaceBefore;
19837 if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&
19838 textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
19839 return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
19840 close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };
19841 }
19842 let startText, endText;
19843 if (to - from <= 2 * SearchMargin) {
19844 startText = endText = state.sliceDoc(from, to);
19845 }
19846 else {
19847 startText = state.sliceDoc(from, from + SearchMargin);
19848 endText = state.sliceDoc(to - SearchMargin, to);
19849 }
19850 let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
19851 let endOff = endText.length - endSpace - close.length;
19852 if (startText.slice(startSpace, startSpace + open.length) == open &&
19853 endText.slice(endOff, endOff + close.length) == close) {
19854 return { open: { pos: from + startSpace + open.length,
19855 margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },
19856 close: { pos: to - endSpace - close.length,
19857 margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };
19858 }
19859 return null;
19860 }
19861 function selectedLineRanges(state) {
19862 let ranges = [];
19863 for (let r of state.selection.ranges) {
19864 let fromLine = state.doc.lineAt(r.from);
19865 let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
19866 let last = ranges.length - 1;
19867 if (last >= 0 && ranges[last].to > fromLine.from)
19868 ranges[last].to = toLine.to;
19869 else
19870 ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to });
19871 }
19872 return ranges;
19873 }
19874 // Performs toggle, comment and uncomment of block comments in
19875 // languages that support them.
19876 function changeBlockComment(option, state, ranges = state.selection.ranges) {
19877 let tokens = ranges.map(r => getConfig(state, r.from).block);
19878 if (!tokens.every(c => c))
19879 return null;
19880 let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
19881 if (option != 2 /* CommentOption.Uncomment */ && !comments.every(c => c)) {
19882 return { changes: state.changes(ranges.map((range, i) => {
19883 if (comments[i])
19884 return [];
19885 return [{ from: range.from, insert: tokens[i].open + " " }, { from: range.to, insert: " " + tokens[i].close }];
19886 })) };
19887 }
19888 else if (option != 1 /* CommentOption.Comment */ && comments.some(c => c)) {
19889 let changes = [];
19890 for (let i = 0, comment; i < comments.length; i++)
19891 if (comment = comments[i]) {
19892 let token = tokens[i], { open, close } = comment;
19893 changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
19894 }
19895 return { changes };
19896 }
19897 return null;
19898 }
19899 // Performs toggle, comment and uncomment of line comments.
19900 function changeLineComment(option, state, ranges = state.selection.ranges) {
19901 let lines = [];
19902 let prevLine = -1;
19903 for (let { from, to } of ranges) {
19904 let startI = lines.length, minIndent = 1e9;
19905 let token = getConfig(state, from).line;
19906 if (!token)
19907 continue;
19908 for (let pos = from; pos <= to;) {
19909 let line = state.doc.lineAt(pos);
19910 if (line.from > prevLine && (from == to || to > line.from)) {
19911 prevLine = line.from;
19912 let indent = /^\s*/.exec(line.text)[0].length;
19913 let empty = indent == line.length;
19914 let comment = line.text.slice(indent, indent + token.length) == token ? indent : -1;
19915 if (indent < line.text.length && indent < minIndent)
19916 minIndent = indent;
19917 lines.push({ line, comment, token, indent, empty, single: false });
19918 }
19919 pos = line.to + 1;
19920 }
19921 if (minIndent < 1e9)
19922 for (let i = startI; i < lines.length; i++)
19923 if (lines[i].indent < lines[i].line.text.length)
19924 lines[i].indent = minIndent;
19925 if (lines.length == startI + 1)
19926 lines[startI].single = true;
19927 }
19928 if (option != 2 /* CommentOption.Uncomment */ && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {
19929 let changes = [];
19930 for (let { line, token, indent, empty, single } of lines)
19931 if (single || !empty)
19932 changes.push({ from: line.from + indent, insert: token + " " });
19933 let changeSet = state.changes(changes);
19934 return { changes: changeSet, selection: state.selection.map(changeSet, 1) };
19935 }
19936 else if (option != 1 /* CommentOption.Comment */ && lines.some(l => l.comment >= 0)) {
19937 let changes = [];
19938 for (let { line, comment, token } of lines)
19939 if (comment >= 0) {
19940 let from = line.from + comment, to = from + token.length;
19941 if (line.text[to - line.from] == " ")
19942 to++;
19943 changes.push({ from, to });
19944 }
19945 return { changes };
19946 }
19947 return null;
19948 }
19949
19950 const fromHistory = /*@__PURE__*/Annotation.define();
19951 /**
19952 Transaction annotation that will prevent that transaction from
19953 being combined with other transactions in the undo history. Given
19954 `"before"`, it'll prevent merging with previous transactions. With
19955 `"after"`, subsequent transactions won't be combined with this
19956 one. With `"full"`, the transaction is isolated on both sides.
19957 */
19958 const isolateHistory = /*@__PURE__*/Annotation.define();
19959 /**
19960 This facet provides a way to register functions that, given a
19961 transaction, provide a set of effects that the history should
19962 store when inverting the transaction. This can be used to
19963 integrate some kinds of effects in the history, so that they can
19964 be undone (and redone again).
19965 */
19966 const invertedEffects = /*@__PURE__*/Facet.define();
19967 const historyConfig = /*@__PURE__*/Facet.define({
19968 combine(configs) {
19969 return combineConfig(configs, {
19970 minDepth: 100,
19971 newGroupDelay: 500,
19972 joinToEvent: (_t, isAdjacent) => isAdjacent,
19973 }, {
19974 minDepth: Math.max,
19975 newGroupDelay: Math.min,
19976 joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
19977 });
19978 }
19979 });
19980 function changeEnd(changes) {
19981 let end = 0;
19982 changes.iterChangedRanges((_, to) => end = to);
19983 return end;
19984 }
19985 const historyField_ = /*@__PURE__*/StateField.define({
19986 create() {
19987 return HistoryState.empty;
19988 },
19989 update(state, tr) {
19990 let config = tr.state.facet(historyConfig);
19991 let fromHist = tr.annotation(fromHistory);
19992 if (fromHist) {
19993 let selection = tr.docChanged ? EditorSelection.single(changeEnd(tr.changes)) : undefined;
19994 let item = HistEvent.fromTransaction(tr, selection), from = fromHist.side;
19995 let other = from == 0 /* BranchName.Done */ ? state.undone : state.done;
19996 if (item)
19997 other = updateBranch(other, other.length, config.minDepth, item);
19998 else
19999 other = addSelection(other, tr.startState.selection);
20000 return new HistoryState(from == 0 /* BranchName.Done */ ? fromHist.rest : other, from == 0 /* BranchName.Done */ ? other : fromHist.rest);
20001 }
20002 let isolate = tr.annotation(isolateHistory);
20003 if (isolate == "full" || isolate == "before")
20004 state = state.isolate();
20005 if (tr.annotation(Transaction.addToHistory) === false)
20006 return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
20007 let event = HistEvent.fromTransaction(tr);
20008 let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
20009 if (event)
20010 state = state.addChanges(event, time, userEvent, config, tr);
20011 else if (tr.selection)
20012 state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
20013 if (isolate == "full" || isolate == "after")
20014 state = state.isolate();
20015 return state;
20016 },
20017 toJSON(value) {
20018 return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) };
20019 },
20020 fromJSON(json) {
20021 return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON));
20022 }
20023 });
20024 /**
20025 Create a history extension with the given configuration.
20026 */
20027 function history(config = {}) {
20028 return [
20029 historyField_,
20030 historyConfig.of(config),
20031 EditorView.domEventHandlers({
20032 beforeinput(e, view) {
20033 let command = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
20034 if (!command)
20035 return false;
20036 e.preventDefault();
20037 return command(view);
20038 }
20039 })
20040 ];
20041 }
20042 /**
20043 The state field used to store the history data. Should probably
20044 only be used when you want to
20045 [serialize](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) or
20046 [deserialize](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) state objects in a way
20047 that preserves history.
20048 */
20049 const historyField = historyField_;
20050 function cmd(side, selection) {
20051 return function ({ state, dispatch }) {
20052 if (!selection && state.readOnly)
20053 return false;
20054 let historyState = state.field(historyField_, false);
20055 if (!historyState)
20056 return false;
20057 let tr = historyState.pop(side, state, selection);
20058 if (!tr)
20059 return false;
20060 dispatch(tr);
20061 return true;
20062 };
20063 }
20064 /**
20065 Undo a single group of history events. Returns false if no group
20066 was available.
20067 */
20068 const undo = /*@__PURE__*/cmd(0 /* BranchName.Done */, false);
20069 /**
20070 Redo a group of history events. Returns false if no group was
20071 available.
20072 */
20073 const redo = /*@__PURE__*/cmd(1 /* BranchName.Undone */, false);
20074 /**
20075 Undo a change or selection change.
20076 */
20077 const undoSelection = /*@__PURE__*/cmd(0 /* BranchName.Done */, true);
20078 /**
20079 Redo a change or selection change.
20080 */
20081 const redoSelection = /*@__PURE__*/cmd(1 /* BranchName.Undone */, true);
20082 function depth(side) {
20083 return function (state) {
20084 let histState = state.field(historyField_, false);
20085 if (!histState)
20086 return 0;
20087 let branch = side == 0 /* BranchName.Done */ ? histState.done : histState.undone;
20088 return branch.length - (branch.length && !branch[0].changes ? 1 : 0);
20089 };
20090 }
20091 /**
20092 The amount of undoable change events available in a given state.
20093 */
20094 const undoDepth = /*@__PURE__*/depth(0 /* BranchName.Done */);
20095 /**
20096 The amount of redoable change events available in a given state.
20097 */
20098 const redoDepth = /*@__PURE__*/depth(1 /* BranchName.Undone */);
20099 // History events store groups of changes or effects that need to be
20100 // undone/redone together.
20101 class HistEvent {
20102 constructor(
20103 // The changes in this event. Normal events hold at least one
20104 // change or effect. But it may be necessary to store selection
20105 // events before the first change, in which case a special type of
20106 // instance is created which doesn't hold any changes, with
20107 // changes == startSelection == undefined
20108 changes,
20109 // The effects associated with this event
20110 effects,
20111 // Accumulated mapping (from addToHistory==false) that should be
20112 // applied to events below this one.
20113 mapped,
20114 // The selection before this event
20115 startSelection,
20116 // Stores selection changes after this event, to be used for
20117 // selection undo/redo.
20118 selectionsAfter) {
20119 this.changes = changes;
20120 this.effects = effects;
20121 this.mapped = mapped;
20122 this.startSelection = startSelection;
20123 this.selectionsAfter = selectionsAfter;
20124 }
20125 setSelAfter(after) {
20126 return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
20127 }
20128 toJSON() {
20129 var _a, _b, _c;
20130 return {
20131 changes: (_a = this.changes) === null || _a === void 0 ? void 0 : _a.toJSON(),
20132 mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
20133 startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
20134 selectionsAfter: this.selectionsAfter.map(s => s.toJSON())
20135 };
20136 }
20137 static fromJSON(json) {
20138 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));
20139 }
20140 // This does not check `addToHistory` and such, it assumes the
20141 // transaction needs to be converted to an item. Returns null when
20142 // there are no changes or effects in the transaction.
20143 static fromTransaction(tr, selection) {
20144 let effects = none;
20145 for (let invert of tr.startState.facet(invertedEffects)) {
20146 let result = invert(tr);
20147 if (result.length)
20148 effects = effects.concat(result);
20149 }
20150 if (!effects.length && tr.changes.empty)
20151 return null;
20152 return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, selection || tr.startState.selection, none);
20153 }
20154 static selection(selections) {
20155 return new HistEvent(undefined, none, undefined, undefined, selections);
20156 }
20157 }
20158 function updateBranch(branch, to, maxLen, newEvent) {
20159 let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
20160 let newBranch = branch.slice(start, to);
20161 newBranch.push(newEvent);
20162 return newBranch;
20163 }
20164 function isAdjacent(a, b) {
20165 let ranges = [], isAdjacent = false;
20166 a.iterChangedRanges((f, t) => ranges.push(f, t));
20167 b.iterChangedRanges((_f, _t, f, t) => {
20168 for (let i = 0; i < ranges.length;) {
20169 let from = ranges[i++], to = ranges[i++];
20170 if (t >= from && f <= to)
20171 isAdjacent = true;
20172 }
20173 });
20174 return isAdjacent;
20175 }
20176 function eqSelectionShape(a, b) {
20177 return a.ranges.length == b.ranges.length &&
20178 a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
20179 }
20180 function conc(a, b) {
20181 return !a.length ? b : !b.length ? a : a.concat(b);
20182 }
20183 const none = [];
20184 const MaxSelectionsPerEvent = 200;
20185 function addSelection(branch, selection) {
20186 if (!branch.length) {
20187 return [HistEvent.selection([selection])];
20188 }
20189 else {
20190 let lastEvent = branch[branch.length - 1];
20191 let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
20192 if (sels.length && sels[sels.length - 1].eq(selection))
20193 return branch;
20194 sels.push(selection);
20195 return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
20196 }
20197 }
20198 // Assumes the top item has one or more selectionAfter values
20199 function popSelection(branch) {
20200 let last = branch[branch.length - 1];
20201 let newBranch = branch.slice();
20202 newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
20203 return newBranch;
20204 }
20205 // Add a mapping to the top event in the given branch. If this maps
20206 // away all the changes and effects in that item, drop it and
20207 // propagate the mapping to the next item.
20208 function addMappingToBranch(branch, mapping) {
20209 if (!branch.length)
20210 return branch;
20211 let length = branch.length, selections = none;
20212 while (length) {
20213 let event = mapEvent(branch[length - 1], mapping, selections);
20214 if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping
20215 let result = branch.slice(0, length);
20216 result[length - 1] = event;
20217 return result;
20218 }
20219 else { // Drop this event, since there's no changes or effects left
20220 mapping = event.mapped;
20221 length--;
20222 selections = event.selectionsAfter;
20223 }
20224 }
20225 return selections.length ? [HistEvent.selection(selections)] : none;
20226 }
20227 function mapEvent(event, mapping, extraSelections) {
20228 let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none, extraSelections);
20229 // Change-less events don't store mappings (they are always the last event in a branch)
20230 if (!event.changes)
20231 return HistEvent.selection(selections);
20232 let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
20233 let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
20234 return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
20235 }
20236 const joinableUserEvent = /^(input\.type|delete)($|\.)/;
20237 class HistoryState {
20238 constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {
20239 this.done = done;
20240 this.undone = undone;
20241 this.prevTime = prevTime;
20242 this.prevUserEvent = prevUserEvent;
20243 }
20244 isolate() {
20245 return this.prevTime ? new HistoryState(this.done, this.undone) : this;
20246 }
20247 addChanges(event, time, userEvent, config, tr) {
20248 let done = this.done, lastEvent = done[done.length - 1];
20249 if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes &&
20250 (!userEvent || joinableUserEvent.test(userEvent)) &&
20251 ((!lastEvent.selectionsAfter.length &&
20252 time - this.prevTime < config.newGroupDelay &&
20253 config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes))) ||
20254 // For compose (but not compose.start) events, always join with previous event
20255 userEvent == "input.type.compose")) {
20256 done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none));
20257 }
20258 else {
20259 done = updateBranch(done, done.length, config.minDepth, event);
20260 }
20261 return new HistoryState(done, none, time, userEvent);
20262 }
20263 addSelection(selection, time, userEvent, newGroupDelay) {
20264 let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none;
20265 if (last.length > 0 &&
20266 time - this.prevTime < newGroupDelay &&
20267 userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) &&
20268 eqSelectionShape(last[last.length - 1], selection))
20269 return this;
20270 return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
20271 }
20272 addMapping(mapping) {
20273 return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
20274 }
20275 pop(side, state, selection) {
20276 let branch = side == 0 /* BranchName.Done */ ? this.done : this.undone;
20277 if (branch.length == 0)
20278 return null;
20279 let event = branch[branch.length - 1];
20280 if (selection && event.selectionsAfter.length) {
20281 return state.update({
20282 selection: event.selectionsAfter[event.selectionsAfter.length - 1],
20283 annotations: fromHistory.of({ side, rest: popSelection(branch) }),
20284 userEvent: side == 0 /* BranchName.Done */ ? "select.undo" : "select.redo",
20285 scrollIntoView: true
20286 });
20287 }
20288 else if (!event.changes) {
20289 return null;
20290 }
20291 else {
20292 let rest = branch.length == 1 ? none : branch.slice(0, branch.length - 1);
20293 if (event.mapped)
20294 rest = addMappingToBranch(rest, event.mapped);
20295 return state.update({
20296 changes: event.changes,
20297 selection: event.startSelection,
20298 effects: event.effects,
20299 annotations: fromHistory.of({ side, rest }),
20300 filter: false,
20301 userEvent: side == 0 /* BranchName.Done */ ? "undo" : "redo",
20302 scrollIntoView: true
20303 });
20304 }
20305 }
20306 }
20307 HistoryState.empty = /*@__PURE__*/new HistoryState(none, none);
20308 /**
20309 Default key bindings for the undo history.
20310
20311 - Mod-z: [`undo`](https://codemirror.net/6/docs/ref/#commands.undo).
20312 - Mod-y (Mod-Shift-z on macOS) + Ctrl-Shift-z on Linux: [`redo`](https://codemirror.net/6/docs/ref/#commands.redo).
20313 - Mod-u: [`undoSelection`](https://codemirror.net/6/docs/ref/#commands.undoSelection).
20314 - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](https://codemirror.net/6/docs/ref/#commands.redoSelection).
20315 */
20316 const historyKeymap = [
20317 { key: "Mod-z", run: undo, preventDefault: true },
20318 { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
20319 { linux: "Ctrl-Shift-z", run: redo, preventDefault: true },
20320 { key: "Mod-u", run: undoSelection, preventDefault: true },
20321 { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
20322 ];
20323
20324 function updateSel(sel, by) {
20325 return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
20326 }
20327 function setSel(state, selection) {
20328 return state.update({ selection, scrollIntoView: true, userEvent: "select" });
20329 }
20330 function moveSel({ state, dispatch }, how) {
20331 let selection = updateSel(state.selection, how);
20332 if (selection.eq(state.selection))
20333 return false;
20334 dispatch(setSel(state, selection));
20335 return true;
20336 }
20337 function rangeEnd(range, forward) {
20338 return EditorSelection.cursor(forward ? range.to : range.from);
20339 }
20340 function cursorByChar(view, forward) {
20341 return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
20342 }
20343 function ltrAtCursor(view) {
20344 return view.textDirectionAt(view.state.selection.main.head) == exports.Direction.LTR;
20345 }
20346 /**
20347 Move the selection one character to the left (which is backward in
20348 left-to-right text, forward in right-to-left text).
20349 */
20350 const cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));
20351 /**
20352 Move the selection one character to the right.
20353 */
20354 const cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));
20355 /**
20356 Move the selection one character forward.
20357 */
20358 const cursorCharForward = view => cursorByChar(view, true);
20359 /**
20360 Move the selection one character backward.
20361 */
20362 const cursorCharBackward = view => cursorByChar(view, false);
20363 function cursorByGroup(view, forward) {
20364 return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
20365 }
20366 /**
20367 Move the selection to the left across one group of word or
20368 non-word (but also non-space) characters.
20369 */
20370 const cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));
20371 /**
20372 Move the selection one group to the right.
20373 */
20374 const cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));
20375 /**
20376 Move the selection one group forward.
20377 */
20378 const cursorGroupForward = view => cursorByGroup(view, true);
20379 /**
20380 Move the selection one group backward.
20381 */
20382 const cursorGroupBackward = view => cursorByGroup(view, false);
20383 const segmenter = typeof Intl != "undefined" && Intl.Segmenter ?
20384 /*@__PURE__*/new (Intl.Segmenter)(undefined, { granularity: "word" }) : null;
20385 function moveBySubword(view, range, forward) {
20386 let categorize = view.state.charCategorizer(range.from);
20387 let cat = exports.CharCategory.Space, pos = range.from, steps = 0;
20388 let done = false, sawUpper = false, sawLower = false;
20389 let step = (next) => {
20390 if (done)
20391 return false;
20392 pos += forward ? next.length : -next.length;
20393 let nextCat = categorize(next), ahead;
20394 if (nextCat == exports.CharCategory.Word && next.charCodeAt(0) < 128 && /[\W_]/.test(next))
20395 nextCat = -1; // Treat word punctuation specially
20396 if (cat == exports.CharCategory.Space)
20397 cat = nextCat;
20398 if (cat != nextCat)
20399 return false;
20400 if (cat == exports.CharCategory.Word) {
20401 if (next.toLowerCase() == next) {
20402 if (!forward && sawUpper)
20403 return false;
20404 sawLower = true;
20405 }
20406 else if (sawLower) {
20407 if (forward)
20408 return false;
20409 done = true;
20410 }
20411 else {
20412 if (sawUpper && forward && categorize(ahead = view.state.sliceDoc(pos, pos + 1)) == exports.CharCategory.Word &&
20413 ahead.toLowerCase() == ahead)
20414 return false;
20415 sawUpper = true;
20416 }
20417 }
20418 steps++;
20419 return true;
20420 };
20421 let end = view.moveByChar(range, forward, start => {
20422 step(start);
20423 return step;
20424 });
20425 if (segmenter && cat == exports.CharCategory.Word && end.from == range.from + steps * (forward ? 1 : -1)) {
20426 let from = Math.min(range.head, end.head), to = Math.max(range.head, end.head);
20427 let skipped = view.state.sliceDoc(from, to);
20428 if (skipped.length > 1 && /[\u4E00-\uffff]/.test(skipped)) {
20429 let segments = Array.from(segmenter.segment(skipped));
20430 if (segments.length > 1) {
20431 if (forward)
20432 return EditorSelection.cursor(range.head + segments[1].index, -1);
20433 return EditorSelection.cursor(end.head + segments[segments.length - 1].index, 1);
20434 }
20435 }
20436 }
20437 return end;
20438 }
20439 function cursorBySubword(view, forward) {
20440 return moveSel(view, range => range.empty ? moveBySubword(view, range, forward) : rangeEnd(range, forward));
20441 }
20442 /**
20443 Move the selection one group or camel-case subword forward.
20444 */
20445 const cursorSubwordForward = view => cursorBySubword(view, true);
20446 /**
20447 Move the selection one group or camel-case subword backward.
20448 */
20449 const cursorSubwordBackward = view => cursorBySubword(view, false);
20450 function interestingNode(state, node, bracketProp) {
20451 if (node.type.prop(bracketProp))
20452 return true;
20453 let len = node.to - node.from;
20454 return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
20455 }
20456 function moveBySyntax(state, start, forward) {
20457 let pos = syntaxTree(state).resolveInner(start.head);
20458 let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
20459 // Scan forward through child nodes to see if there's an interesting
20460 // node ahead.
20461 for (let at = start.head;;) {
20462 let next = forward ? pos.childAfter(at) : pos.childBefore(at);
20463 if (!next)
20464 break;
20465 if (interestingNode(state, next, bracketProp))
20466 pos = next;
20467 else
20468 at = forward ? next.to : next.from;
20469 }
20470 let bracket = pos.type.prop(bracketProp), match, newPos;
20471 if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
20472 newPos = forward ? match.end.to : match.end.from;
20473 else
20474 newPos = forward ? pos.to : pos.from;
20475 return EditorSelection.cursor(newPos, forward ? -1 : 1);
20476 }
20477 /**
20478 Move the cursor over the next syntactic element to the left.
20479 */
20480 const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20481 /**
20482 Move the cursor over the next syntactic element to the right.
20483 */
20484 const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20485 function cursorByLine(view, forward) {
20486 return moveSel(view, range => {
20487 if (!range.empty)
20488 return rangeEnd(range, forward);
20489 let moved = view.moveVertically(range, forward);
20490 return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
20491 });
20492 }
20493 /**
20494 Move the selection one line up.
20495 */
20496 const cursorLineUp = view => cursorByLine(view, false);
20497 /**
20498 Move the selection one line down.
20499 */
20500 const cursorLineDown = view => cursorByLine(view, true);
20501 function pageInfo(view) {
20502 let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
20503 let marginTop = 0, marginBottom = 0, height;
20504 if (selfScroll) {
20505 for (let source of view.state.facet(EditorView.scrollMargins)) {
20506 let margins = source(view);
20507 if (margins === null || margins === void 0 ? void 0 : margins.top)
20508 marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
20509 if (margins === null || margins === void 0 ? void 0 : margins.bottom)
20510 marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
20511 }
20512 height = view.scrollDOM.clientHeight - marginTop - marginBottom;
20513 }
20514 else {
20515 height = (view.dom.ownerDocument.defaultView || window).innerHeight;
20516 }
20517 return { marginTop, marginBottom, selfScroll,
20518 height: Math.max(view.defaultLineHeight, height - 5) };
20519 }
20520 function cursorByPage(view, forward) {
20521 let page = pageInfo(view);
20522 let { state } = view, selection = updateSel(state.selection, range => {
20523 return range.empty ? view.moveVertically(range, forward, page.height)
20524 : rangeEnd(range, forward);
20525 });
20526 if (selection.eq(state.selection))
20527 return false;
20528 let effect;
20529 if (page.selfScroll) {
20530 let startPos = view.coordsAtPos(state.selection.main.head);
20531 let scrollRect = view.scrollDOM.getBoundingClientRect();
20532 let scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom;
20533 if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom)
20534 effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop });
20535 }
20536 view.dispatch(setSel(state, selection), { effects: effect });
20537 return true;
20538 }
20539 /**
20540 Move the selection one page up.
20541 */
20542 const cursorPageUp = view => cursorByPage(view, false);
20543 /**
20544 Move the selection one page down.
20545 */
20546 const cursorPageDown = view => cursorByPage(view, true);
20547 function moveByLineBoundary(view, start, forward) {
20548 let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward);
20549 if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
20550 moved = view.moveToLineBoundary(start, forward, false);
20551 if (!forward && moved.head == line.from && line.length) {
20552 let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
20553 if (space && start.head != line.from + space)
20554 moved = EditorSelection.cursor(line.from + space);
20555 }
20556 return moved;
20557 }
20558 /**
20559 Move the selection to the next line wrap point, or to the end of
20560 the line if there isn't one left on this line.
20561 */
20562 const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
20563 /**
20564 Move the selection to previous line wrap point, or failing that to
20565 the start of the line. If the line is indented, and the cursor
20566 isn't already at the end of the indentation, this will move to the
20567 end of the indentation instead of the start of the line.
20568 */
20569 const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
20570 /**
20571 Move the selection one line wrap point to the left.
20572 */
20573 const cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20574 /**
20575 Move the selection one line wrap point to the right.
20576 */
20577 const cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20578 /**
20579 Move the selection to the start of the line.
20580 */
20581 const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
20582 /**
20583 Move the selection to the end of the line.
20584 */
20585 const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
20586 function toMatchingBracket(state, dispatch, extend) {
20587 let found = false, selection = updateSel(state.selection, range => {
20588 let matching = matchBrackets(state, range.head, -1)
20589 || matchBrackets(state, range.head, 1)
20590 || (range.head > 0 && matchBrackets(state, range.head - 1, 1))
20591 || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));
20592 if (!matching || !matching.end)
20593 return range;
20594 found = true;
20595 let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
20596 return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);
20597 });
20598 if (!found)
20599 return false;
20600 dispatch(setSel(state, selection));
20601 return true;
20602 }
20603 /**
20604 Move the selection to the bracket matching the one it is currently
20605 on, if any.
20606 */
20607 const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
20608 /**
20609 Extend the selection to the bracket matching the one the selection
20610 head is currently on, if any.
20611 */
20612 const selectMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, true);
20613 function extendSel(view, how) {
20614 let selection = updateSel(view.state.selection, range => {
20615 let head = how(range);
20616 return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || undefined);
20617 });
20618 if (selection.eq(view.state.selection))
20619 return false;
20620 view.dispatch(setSel(view.state, selection));
20621 return true;
20622 }
20623 function selectByChar(view, forward) {
20624 return extendSel(view, range => view.moveByChar(range, forward));
20625 }
20626 /**
20627 Move the selection head one character to the left, while leaving
20628 the anchor in place.
20629 */
20630 const selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));
20631 /**
20632 Move the selection head one character to the right.
20633 */
20634 const selectCharRight = view => selectByChar(view, ltrAtCursor(view));
20635 /**
20636 Move the selection head one character forward.
20637 */
20638 const selectCharForward = view => selectByChar(view, true);
20639 /**
20640 Move the selection head one character backward.
20641 */
20642 const selectCharBackward = view => selectByChar(view, false);
20643 function selectByGroup(view, forward) {
20644 return extendSel(view, range => view.moveByGroup(range, forward));
20645 }
20646 /**
20647 Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to
20648 the left.
20649 */
20650 const selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));
20651 /**
20652 Move the selection head one group to the right.
20653 */
20654 const selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));
20655 /**
20656 Move the selection head one group forward.
20657 */
20658 const selectGroupForward = view => selectByGroup(view, true);
20659 /**
20660 Move the selection head one group backward.
20661 */
20662 const selectGroupBackward = view => selectByGroup(view, false);
20663 function selectBySubword(view, forward) {
20664 return extendSel(view, range => moveBySubword(view, range, forward));
20665 }
20666 /**
20667 Move the selection head one group or camel-case subword forward.
20668 */
20669 const selectSubwordForward = view => selectBySubword(view, true);
20670 /**
20671 Move the selection head one group or subword backward.
20672 */
20673 const selectSubwordBackward = view => selectBySubword(view, false);
20674 /**
20675 Move the selection head over the next syntactic element to the left.
20676 */
20677 const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view)));
20678 /**
20679 Move the selection head over the next syntactic element to the right.
20680 */
20681 const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view)));
20682 function selectByLine(view, forward) {
20683 return extendSel(view, range => view.moveVertically(range, forward));
20684 }
20685 /**
20686 Move the selection head one line up.
20687 */
20688 const selectLineUp = view => selectByLine(view, false);
20689 /**
20690 Move the selection head one line down.
20691 */
20692 const selectLineDown = view => selectByLine(view, true);
20693 function selectByPage(view, forward) {
20694 return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));
20695 }
20696 /**
20697 Move the selection head one page up.
20698 */
20699 const selectPageUp = view => selectByPage(view, false);
20700 /**
20701 Move the selection head one page down.
20702 */
20703 const selectPageDown = view => selectByPage(view, true);
20704 /**
20705 Move the selection head to the next line boundary.
20706 */
20707 const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
20708 /**
20709 Move the selection head to the previous line boundary.
20710 */
20711 const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
20712 /**
20713 Move the selection head one line boundary to the left.
20714 */
20715 const selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view)));
20716 /**
20717 Move the selection head one line boundary to the right.
20718 */
20719 const selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view)));
20720 /**
20721 Move the selection head to the start of the line.
20722 */
20723 const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from));
20724 /**
20725 Move the selection head to the end of the line.
20726 */
20727 const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to));
20728 /**
20729 Move the selection to the start of the document.
20730 */
20731 const cursorDocStart = ({ state, dispatch }) => {
20732 dispatch(setSel(state, { anchor: 0 }));
20733 return true;
20734 };
20735 /**
20736 Move the selection to the end of the document.
20737 */
20738 const cursorDocEnd = ({ state, dispatch }) => {
20739 dispatch(setSel(state, { anchor: state.doc.length }));
20740 return true;
20741 };
20742 /**
20743 Move the selection head to the start of the document.
20744 */
20745 const selectDocStart = ({ state, dispatch }) => {
20746 dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
20747 return true;
20748 };
20749 /**
20750 Move the selection head to the end of the document.
20751 */
20752 const selectDocEnd = ({ state, dispatch }) => {
20753 dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
20754 return true;
20755 };
20756 /**
20757 Select the entire document.
20758 */
20759 const selectAll = ({ state, dispatch }) => {
20760 dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" }));
20761 return true;
20762 };
20763 /**
20764 Expand the selection to cover entire lines.
20765 */
20766 const selectLine = ({ state, dispatch }) => {
20767 let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
20768 dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" }));
20769 return true;
20770 };
20771 /**
20772 Select the next syntactic construct that is larger than the
20773 selection. Note that this will only work insofar as the language
20774 [provider](https://codemirror.net/6/docs/ref/#language.language) you use builds up a full
20775 syntax tree.
20776 */
20777 const selectParentSyntax = ({ state, dispatch }) => {
20778 let selection = updateSel(state.selection, range => {
20779 var _a;
20780 let context = syntaxTree(state).resolveInner(range.head, 1);
20781 while (!((context.from < range.from && context.to >= range.to) ||
20782 (context.to > range.to && context.from <= range.from) ||
20783 !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent)))
20784 context = context.parent;
20785 return EditorSelection.range(context.to, context.from);
20786 });
20787 dispatch(setSel(state, selection));
20788 return true;
20789 };
20790 /**
20791 Simplify the current selection. When multiple ranges are selected,
20792 reduce it to its main range. Otherwise, if the selection is
20793 non-empty, convert it to a cursor selection.
20794 */
20795 const simplifySelection = ({ state, dispatch }) => {
20796 let cur = state.selection, selection = null;
20797 if (cur.ranges.length > 1)
20798 selection = EditorSelection.create([cur.main]);
20799 else if (!cur.main.empty)
20800 selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]);
20801 if (!selection)
20802 return false;
20803 dispatch(setSel(state, selection));
20804 return true;
20805 };
20806 function deleteBy(target, by) {
20807 if (target.state.readOnly)
20808 return false;
20809 let event = "delete.selection", { state } = target;
20810 let changes = state.changeByRange(range => {
20811 let { from, to } = range;
20812 if (from == to) {
20813 let towards = by(from);
20814 if (towards < from) {
20815 event = "delete.backward";
20816 towards = skipAtomic(target, towards, false);
20817 }
20818 else if (towards > from) {
20819 event = "delete.forward";
20820 towards = skipAtomic(target, towards, true);
20821 }
20822 from = Math.min(from, towards);
20823 to = Math.max(to, towards);
20824 }
20825 else {
20826 from = skipAtomic(target, from, false);
20827 to = skipAtomic(target, to, true);
20828 }
20829 return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) };
20830 });
20831 if (changes.changes.empty)
20832 return false;
20833 target.dispatch(state.update(changes, {
20834 scrollIntoView: true,
20835 userEvent: event,
20836 effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : undefined
20837 }));
20838 return true;
20839 }
20840 function skipAtomic(target, pos, forward) {
20841 if (target instanceof EditorView)
20842 for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target)))
20843 ranges.between(pos, pos, (from, to) => {
20844 if (from < pos && to > pos)
20845 pos = forward ? to : from;
20846 });
20847 return pos;
20848 }
20849 const deleteByChar = (target, forward) => deleteBy(target, pos => {
20850 let { state } = target, line = state.doc.lineAt(pos), before, targetPos;
20851 if (!forward && pos > line.from && pos < line.from + 200 &&
20852 !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
20853 if (before[before.length - 1] == "\t")
20854 return pos - 1;
20855 let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
20856 for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
20857 pos--;
20858 targetPos = pos;
20859 }
20860 else {
20861 targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
20862 if (targetPos == pos && line.number != (forward ? state.doc.lines : 1))
20863 targetPos += forward ? 1 : -1;
20864 }
20865 return targetPos;
20866 });
20867 /**
20868 Delete the selection, or, for cursor selections, the character
20869 before the cursor.
20870 */
20871 const deleteCharBackward = view => deleteByChar(view, false);
20872 /**
20873 Delete the selection or the character after the cursor.
20874 */
20875 const deleteCharForward = view => deleteByChar(view, true);
20876 const deleteByGroup = (target, forward) => deleteBy(target, start => {
20877 let pos = start, { state } = target, line = state.doc.lineAt(pos);
20878 let categorize = state.charCategorizer(pos);
20879 for (let cat = null;;) {
20880 if (pos == (forward ? line.to : line.from)) {
20881 if (pos == start && line.number != (forward ? state.doc.lines : 1))
20882 pos += forward ? 1 : -1;
20883 break;
20884 }
20885 let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
20886 let nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
20887 let nextCat = categorize(nextChar);
20888 if (cat != null && nextCat != cat)
20889 break;
20890 if (nextChar != " " || pos != start)
20891 cat = nextCat;
20892 pos = next;
20893 }
20894 return pos;
20895 });
20896 /**
20897 Delete the selection or backward until the end of the next
20898 [group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of
20899 whitespace when they consist of a single space.
20900 */
20901 const deleteGroupBackward = target => deleteByGroup(target, false);
20902 /**
20903 Delete the selection or forward until the end of the next group.
20904 */
20905 const deleteGroupForward = target => deleteByGroup(target, true);
20906 /**
20907 Delete the selection, or, if it is a cursor selection, delete to
20908 the end of the line. If the cursor is directly at the end of the
20909 line, delete the line break after it.
20910 */
20911 const deleteToLineEnd = view => deleteBy(view, pos => {
20912 let lineEnd = view.lineBlockAt(pos).to;
20913 return pos < lineEnd ? lineEnd : Math.min(view.state.doc.length, pos + 1);
20914 });
20915 /**
20916 Delete the selection, or, if it is a cursor selection, delete to
20917 the start of the line. If the cursor is directly at the start of the
20918 line, delete the line break before it.
20919 */
20920 const deleteToLineStart = view => deleteBy(view, pos => {
20921 let lineStart = view.lineBlockAt(pos).from;
20922 return pos > lineStart ? lineStart : Math.max(0, pos - 1);
20923 });
20924 /**
20925 Delete all whitespace directly before a line end from the
20926 document.
20927 */
20928 const deleteTrailingWhitespace = ({ state, dispatch }) => {
20929 if (state.readOnly)
20930 return false;
20931 let changes = [];
20932 for (let pos = 0, prev = "", iter = state.doc.iter();;) {
20933 iter.next();
20934 if (iter.lineBreak || iter.done) {
20935 let trailing = prev.search(/\s+$/);
20936 if (trailing > -1)
20937 changes.push({ from: pos - (prev.length - trailing), to: pos });
20938 if (iter.done)
20939 break;
20940 prev = "";
20941 }
20942 else {
20943 prev = iter.value;
20944 }
20945 pos += iter.value.length;
20946 }
20947 if (!changes.length)
20948 return false;
20949 dispatch(state.update({ changes, userEvent: "delete" }));
20950 return true;
20951 };
20952 /**
20953 Replace each selection range with a line break, leaving the cursor
20954 on the line before the break.
20955 */
20956 const splitLine = ({ state, dispatch }) => {
20957 if (state.readOnly)
20958 return false;
20959 let changes = state.changeByRange(range => {
20960 return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) },
20961 range: EditorSelection.cursor(range.from) };
20962 });
20963 dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
20964 return true;
20965 };
20966 /**
20967 Flip the characters before and after the cursor(s).
20968 */
20969 const transposeChars = ({ state, dispatch }) => {
20970 if (state.readOnly)
20971 return false;
20972 let changes = state.changeByRange(range => {
20973 if (!range.empty || range.from == 0 || range.from == state.doc.length)
20974 return { range };
20975 let pos = range.from, line = state.doc.lineAt(pos);
20976 let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
20977 let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
20978 return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
20979 range: EditorSelection.cursor(to) };
20980 });
20981 if (changes.changes.empty)
20982 return false;
20983 dispatch(state.update(changes, { scrollIntoView: true, userEvent: "move.character" }));
20984 return true;
20985 };
20986 function selectedLineBlocks(state) {
20987 let blocks = [], upto = -1;
20988 for (let range of state.selection.ranges) {
20989 let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
20990 if (!range.empty && range.to == endLine.from)
20991 endLine = state.doc.lineAt(range.to - 1);
20992 if (upto >= startLine.number) {
20993 let prev = blocks[blocks.length - 1];
20994 prev.to = endLine.to;
20995 prev.ranges.push(range);
20996 }
20997 else {
20998 blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] });
20999 }
21000 upto = endLine.number + 1;
21001 }
21002 return blocks;
21003 }
21004 function moveLine(state, dispatch, forward) {
21005 if (state.readOnly)
21006 return false;
21007 let changes = [], ranges = [];
21008 for (let block of selectedLineBlocks(state)) {
21009 if (forward ? block.to == state.doc.length : block.from == 0)
21010 continue;
21011 let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
21012 let size = nextLine.length + 1;
21013 if (forward) {
21014 changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
21015 for (let r of block.ranges)
21016 ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
21017 }
21018 else {
21019 changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
21020 for (let r of block.ranges)
21021 ranges.push(EditorSelection.range(r.anchor - size, r.head - size));
21022 }
21023 }
21024 if (!changes.length)
21025 return false;
21026 dispatch(state.update({
21027 changes,
21028 scrollIntoView: true,
21029 selection: EditorSelection.create(ranges, state.selection.mainIndex),
21030 userEvent: "move.line"
21031 }));
21032 return true;
21033 }
21034 /**
21035 Move the selected lines up one line.
21036 */
21037 const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
21038 /**
21039 Move the selected lines down one line.
21040 */
21041 const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
21042 function copyLine(state, dispatch, forward) {
21043 if (state.readOnly)
21044 return false;
21045 let changes = [];
21046 for (let block of selectedLineBlocks(state)) {
21047 if (forward)
21048 changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
21049 else
21050 changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
21051 }
21052 dispatch(state.update({ changes, scrollIntoView: true, userEvent: "input.copyline" }));
21053 return true;
21054 }
21055 /**
21056 Create a copy of the selected lines. Keep the selection in the top copy.
21057 */
21058 const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
21059 /**
21060 Create a copy of the selected lines. Keep the selection in the bottom copy.
21061 */
21062 const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
21063 /**
21064 Delete selected lines.
21065 */
21066 const deleteLine = view => {
21067 if (view.state.readOnly)
21068 return false;
21069 let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
21070 if (from > 0)
21071 from--;
21072 else if (to < state.doc.length)
21073 to++;
21074 return { from, to };
21075 }));
21076 let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes);
21077 view.dispatch({ changes, selection, scrollIntoView: true, userEvent: "delete.line" });
21078 return true;
21079 };
21080 /**
21081 Replace the selection with a newline.
21082 */
21083 const insertNewline = ({ state, dispatch }) => {
21084 dispatch(state.update(state.replaceSelection(state.lineBreak), { scrollIntoView: true, userEvent: "input" }));
21085 return true;
21086 };
21087 function isBetweenBrackets(state, pos) {
21088 if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
21089 return { from: pos, to: pos };
21090 let context = syntaxTree(state).resolveInner(pos);
21091 let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
21092 if (before && after && before.to <= pos && after.from >= pos &&
21093 (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 &&
21094 state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from &&
21095 !/\S/.test(state.sliceDoc(before.to, after.from)))
21096 return { from: before.to, to: after.from };
21097 return null;
21098 }
21099 /**
21100 Replace the selection with a newline and indent the newly created
21101 line(s). If the current line consists only of whitespace, this
21102 will also delete that whitespace. When the cursor is between
21103 matching brackets, an additional newline will be inserted after
21104 the cursor.
21105 */
21106 const insertNewlineAndIndent = /*@__PURE__*/newlineAndIndent(false);
21107 /**
21108 Create a blank, indented line below the current line.
21109 */
21110 const insertBlankLine = /*@__PURE__*/newlineAndIndent(true);
21111 function newlineAndIndent(atEof) {
21112 return ({ state, dispatch }) => {
21113 if (state.readOnly)
21114 return false;
21115 let changes = state.changeByRange(range => {
21116 let { from, to } = range, line = state.doc.lineAt(from);
21117 let explode = !atEof && from == to && isBetweenBrackets(state, from);
21118 if (atEof)
21119 from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
21120 let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
21121 let indent = getIndentation(cx, from);
21122 if (indent == null)
21123 indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
21124 while (to < line.to && /\s/.test(line.text[to - line.from]))
21125 to++;
21126 if (explode)
21127 ({ from, to } = explode);
21128 else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
21129 from = line.from;
21130 let insert = ["", indentString(state, indent)];
21131 if (explode)
21132 insert.push(indentString(state, cx.lineIndent(line.from, -1)));
21133 return { changes: { from, to, insert: Text.of(insert) },
21134 range: EditorSelection.cursor(from + 1 + insert[1].length) };
21135 });
21136 dispatch(state.update(changes, { scrollIntoView: true, userEvent: "input" }));
21137 return true;
21138 };
21139 }
21140 function changeBySelectedLine(state, f) {
21141 let atLine = -1;
21142 return state.changeByRange(range => {
21143 let changes = [];
21144 for (let pos = range.from; pos <= range.to;) {
21145 let line = state.doc.lineAt(pos);
21146 if (line.number > atLine && (range.empty || range.to > line.from)) {
21147 f(line, changes, range);
21148 atLine = line.number;
21149 }
21150 pos = line.to + 1;
21151 }
21152 let changeSet = state.changes(changes);
21153 return { changes,
21154 range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };
21155 });
21156 }
21157 /**
21158 Auto-indent the selected lines. This uses the [indentation service
21159 facet](https://codemirror.net/6/docs/ref/#language.indentService) as source for auto-indent
21160 information.
21161 */
21162 const indentSelection = ({ state, dispatch }) => {
21163 if (state.readOnly)
21164 return false;
21165 let updated = Object.create(null);
21166 let context = new IndentContext(state, { overrideIndentation: start => {
21167 let found = updated[start];
21168 return found == null ? -1 : found;
21169 } });
21170 let changes = changeBySelectedLine(state, (line, changes, range) => {
21171 let indent = getIndentation(context, line.from);
21172 if (indent == null)
21173 return;
21174 if (!/\S/.test(line.text))
21175 indent = 0;
21176 let cur = /^\s*/.exec(line.text)[0];
21177 let norm = indentString(state, indent);
21178 if (cur != norm || range.from < line.from + cur.length) {
21179 updated[line.from] = indent;
21180 changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
21181 }
21182 });
21183 if (!changes.changes.empty)
21184 dispatch(state.update(changes, { userEvent: "indent" }));
21185 return true;
21186 };
21187 /**
21188 Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected
21189 lines.
21190 */
21191 const indentMore = ({ state, dispatch }) => {
21192 if (state.readOnly)
21193 return false;
21194 dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
21195 changes.push({ from: line.from, insert: state.facet(indentUnit) });
21196 }), { userEvent: "input.indent" }));
21197 return true;
21198 };
21199 /**
21200 Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all
21201 selected lines.
21202 */
21203 const indentLess = ({ state, dispatch }) => {
21204 if (state.readOnly)
21205 return false;
21206 dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
21207 let space = /^\s*/.exec(line.text)[0];
21208 if (!space)
21209 return;
21210 let col = countColumn(space, state.tabSize), keep = 0;
21211 let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));
21212 while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))
21213 keep++;
21214 changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });
21215 }), { userEvent: "delete.dedent" }));
21216 return true;
21217 };
21218 /**
21219 Insert a tab character at the cursor or, if something is selected,
21220 use [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) to indent the entire
21221 selection.
21222 */
21223 const insertTab = ({ state, dispatch }) => {
21224 if (state.selection.ranges.some(r => !r.empty))
21225 return indentMore({ state, dispatch });
21226 dispatch(state.update(state.replaceSelection("\t"), { scrollIntoView: true, userEvent: "input" }));
21227 return true;
21228 };
21229 /**
21230 Array of key bindings containing the Emacs-style bindings that are
21231 available on macOS by default.
21232
21233 - Ctrl-b: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
21234 - Ctrl-f: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
21235 - Ctrl-p: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
21236 - Ctrl-n: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
21237 - Ctrl-a: [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
21238 - Ctrl-e: [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
21239 - Ctrl-d: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
21240 - Ctrl-h: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
21241 - Ctrl-k: [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd)
21242 - Ctrl-Alt-h: [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
21243 - Ctrl-o: [`splitLine`](https://codemirror.net/6/docs/ref/#commands.splitLine)
21244 - Ctrl-t: [`transposeChars`](https://codemirror.net/6/docs/ref/#commands.transposeChars)
21245 - Ctrl-v: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown)
21246 - Alt-v: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp)
21247 */
21248 const emacsStyleKeymap = [
21249 { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
21250 { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
21251 { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
21252 { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
21253 { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
21254 { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
21255 { key: "Ctrl-d", run: deleteCharForward },
21256 { key: "Ctrl-h", run: deleteCharBackward },
21257 { key: "Ctrl-k", run: deleteToLineEnd },
21258 { key: "Ctrl-Alt-h", run: deleteGroupBackward },
21259 { key: "Ctrl-o", run: splitLine },
21260 { key: "Ctrl-t", run: transposeChars },
21261 { key: "Ctrl-v", run: cursorPageDown },
21262 ];
21263 /**
21264 An array of key bindings closely sticking to platform-standard or
21265 widely used bindings. (This includes the bindings from
21266 [`emacsStyleKeymap`](https://codemirror.net/6/docs/ref/#commands.emacsStyleKeymap), with their `key`
21267 property changed to `mac`.)
21268
21269 - ArrowLeft: [`cursorCharLeft`](https://codemirror.net/6/docs/ref/#commands.cursorCharLeft) ([`selectCharLeft`](https://codemirror.net/6/docs/ref/#commands.selectCharLeft) with Shift)
21270 - ArrowRight: [`cursorCharRight`](https://codemirror.net/6/docs/ref/#commands.cursorCharRight) ([`selectCharRight`](https://codemirror.net/6/docs/ref/#commands.selectCharRight) with Shift)
21271 - 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)
21272 - 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)
21273 - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](https://codemirror.net/6/docs/ref/#commands.cursorLineStart) ([`selectLineStart`](https://codemirror.net/6/docs/ref/#commands.selectLineStart) with Shift)
21274 - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](https://codemirror.net/6/docs/ref/#commands.cursorLineEnd) ([`selectLineEnd`](https://codemirror.net/6/docs/ref/#commands.selectLineEnd) with Shift)
21275 - ArrowUp: [`cursorLineUp`](https://codemirror.net/6/docs/ref/#commands.cursorLineUp) ([`selectLineUp`](https://codemirror.net/6/docs/ref/#commands.selectLineUp) with Shift)
21276 - ArrowDown: [`cursorLineDown`](https://codemirror.net/6/docs/ref/#commands.cursorLineDown) ([`selectLineDown`](https://codemirror.net/6/docs/ref/#commands.selectLineDown) with Shift)
21277 - Cmd-ArrowUp (on macOS): [`cursorDocStart`](https://codemirror.net/6/docs/ref/#commands.cursorDocStart) ([`selectDocStart`](https://codemirror.net/6/docs/ref/#commands.selectDocStart) with Shift)
21278 - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](https://codemirror.net/6/docs/ref/#commands.cursorDocEnd) ([`selectDocEnd`](https://codemirror.net/6/docs/ref/#commands.selectDocEnd) with Shift)
21279 - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
21280 - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
21281 - PageUp: [`cursorPageUp`](https://codemirror.net/6/docs/ref/#commands.cursorPageUp) ([`selectPageUp`](https://codemirror.net/6/docs/ref/#commands.selectPageUp) with Shift)
21282 - PageDown: [`cursorPageDown`](https://codemirror.net/6/docs/ref/#commands.cursorPageDown) ([`selectPageDown`](https://codemirror.net/6/docs/ref/#commands.selectPageDown) with Shift)
21283 - Home: [`cursorLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryBackward) with Shift)
21284 - End: [`cursorLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](https://codemirror.net/6/docs/ref/#commands.selectLineBoundaryForward) with Shift)
21285 - 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)
21286 - 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)
21287 - Enter: [`insertNewlineAndIndent`](https://codemirror.net/6/docs/ref/#commands.insertNewlineAndIndent)
21288 - Ctrl-a (Cmd-a on macOS): [`selectAll`](https://codemirror.net/6/docs/ref/#commands.selectAll)
21289 - Backspace: [`deleteCharBackward`](https://codemirror.net/6/docs/ref/#commands.deleteCharBackward)
21290 - Delete: [`deleteCharForward`](https://codemirror.net/6/docs/ref/#commands.deleteCharForward)
21291 - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupBackward)
21292 - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](https://codemirror.net/6/docs/ref/#commands.deleteGroupForward)
21293 - Cmd-Backspace (macOS): [`deleteToLineStart`](https://codemirror.net/6/docs/ref/#commands.deleteToLineStart).
21294 - Cmd-Delete (macOS): [`deleteToLineEnd`](https://codemirror.net/6/docs/ref/#commands.deleteToLineEnd).
21295 */
21296 const standardKeymap = /*@__PURE__*/[
21297 { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: true },
21298 { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: true },
21299 { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: true },
21300 { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: true },
21301 { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: true },
21302 { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: true },
21303 { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: true },
21304 { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
21305 { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
21306 { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: true },
21307 { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
21308 { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
21309 { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
21310 { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
21311 { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: true },
21312 { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
21313 { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: true },
21314 { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
21315 { key: "Enter", run: insertNewlineAndIndent },
21316 { key: "Mod-a", run: selectAll },
21317 { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward },
21318 { key: "Delete", run: deleteCharForward },
21319 { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
21320 { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
21321 { mac: "Mod-Backspace", run: deleteToLineStart },
21322 { mac: "Mod-Delete", run: deleteToLineEnd }
21323 ].concat(/*@__PURE__*/emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));
21324 /**
21325 The default keymap. Includes all bindings from
21326 [`standardKeymap`](https://codemirror.net/6/docs/ref/#commands.standardKeymap) plus the following:
21327
21328 - 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)
21329 - 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)
21330 - Alt-ArrowUp: [`moveLineUp`](https://codemirror.net/6/docs/ref/#commands.moveLineUp)
21331 - Alt-ArrowDown: [`moveLineDown`](https://codemirror.net/6/docs/ref/#commands.moveLineDown)
21332 - Shift-Alt-ArrowUp: [`copyLineUp`](https://codemirror.net/6/docs/ref/#commands.copyLineUp)
21333 - Shift-Alt-ArrowDown: [`copyLineDown`](https://codemirror.net/6/docs/ref/#commands.copyLineDown)
21334 - Escape: [`simplifySelection`](https://codemirror.net/6/docs/ref/#commands.simplifySelection)
21335 - Ctrl-Enter (Cmd-Enter on macOS): [`insertBlankLine`](https://codemirror.net/6/docs/ref/#commands.insertBlankLine)
21336 - Alt-l (Ctrl-l on macOS): [`selectLine`](https://codemirror.net/6/docs/ref/#commands.selectLine)
21337 - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](https://codemirror.net/6/docs/ref/#commands.selectParentSyntax)
21338 - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess)
21339 - Ctrl-] (Cmd-] on macOS): [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore)
21340 - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](https://codemirror.net/6/docs/ref/#commands.indentSelection)
21341 - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](https://codemirror.net/6/docs/ref/#commands.deleteLine)
21342 - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](https://codemirror.net/6/docs/ref/#commands.cursorMatchingBracket)
21343 - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](https://codemirror.net/6/docs/ref/#commands.toggleComment).
21344 - Shift-Alt-a: [`toggleBlockComment`](https://codemirror.net/6/docs/ref/#commands.toggleBlockComment).
21345 */
21346 const defaultKeymap = /*@__PURE__*/[
21347 { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
21348 { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
21349 { key: "Alt-ArrowUp", run: moveLineUp },
21350 { key: "Shift-Alt-ArrowUp", run: copyLineUp },
21351 { key: "Alt-ArrowDown", run: moveLineDown },
21352 { key: "Shift-Alt-ArrowDown", run: copyLineDown },
21353 { key: "Escape", run: simplifySelection },
21354 { key: "Mod-Enter", run: insertBlankLine },
21355 { key: "Alt-l", mac: "Ctrl-l", run: selectLine },
21356 { key: "Mod-i", run: selectParentSyntax, preventDefault: true },
21357 { key: "Mod-[", run: indentLess },
21358 { key: "Mod-]", run: indentMore },
21359 { key: "Mod-Alt-\\", run: indentSelection },
21360 { key: "Shift-Mod-k", run: deleteLine },
21361 { key: "Shift-Mod-\\", run: cursorMatchingBracket },
21362 { key: "Mod-/", run: toggleComment },
21363 { key: "Alt-A", run: toggleBlockComment }
21364 ].concat(standardKeymap);
21365 /**
21366 A binding that binds Tab to [`indentMore`](https://codemirror.net/6/docs/ref/#commands.indentMore) and
21367 Shift-Tab to [`indentLess`](https://codemirror.net/6/docs/ref/#commands.indentLess).
21368 Please see the [Tab example](../../examples/tab/) before using
21369 this.
21370 */
21371 const indentWithTab = { key: "Tab", run: indentMore, shift: indentLess };
21372
21373 function crelt() {
21374 var elt = arguments[0];
21375 if (typeof elt == "string") elt = document.createElement(elt);
21376 var i = 1, next = arguments[1];
21377 if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
21378 for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
21379 var value = next[name];
21380 if (typeof value == "string") elt.setAttribute(name, value);
21381 else if (value != null) elt[name] = value;
21382 }
21383 i++;
21384 }
21385 for (; i < arguments.length; i++) add(elt, arguments[i]);
21386 return elt
21387 }
21388
21389 function add(elt, child) {
21390 if (typeof child == "string") {
21391 elt.appendChild(document.createTextNode(child));
21392 } else if (child == null) ; else if (child.nodeType != null) {
21393 elt.appendChild(child);
21394 } else if (Array.isArray(child)) {
21395 for (var i = 0; i < child.length; i++) add(elt, child[i]);
21396 } else {
21397 throw new RangeError("Unsupported child node: " + child)
21398 }
21399 }
21400
21401 const basicNormalize = typeof String.prototype.normalize == "function"
21402 ? x => x.normalize("NFKD") : x => x;
21403 /**
21404 A search cursor provides an iterator over text matches in a
21405 document.
21406 */
21407 class SearchCursor {
21408 /**
21409 Create a text cursor. The query is the search string, `from` to
21410 `to` provides the region to search.
21411
21412 When `normalize` is given, it will be called, on both the query
21413 string and the content it is matched against, before comparing.
21414 You can, for example, create a case-insensitive search by
21415 passing `s => s.toLowerCase()`.
21416
21417 Text is always normalized with
21418 [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
21419 (when supported).
21420 */
21421 constructor(text, query, from = 0, to = text.length, normalize, test) {
21422 this.test = test;
21423 /**
21424 The current match (only holds a meaningful value after
21425 [`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when
21426 `done` is false).
21427 */
21428 this.value = { from: 0, to: 0 };
21429 /**
21430 Whether the end of the iterated region has been reached.
21431 */
21432 this.done = false;
21433 this.matches = [];
21434 this.buffer = "";
21435 this.bufferPos = 0;
21436 this.iter = text.iterRange(from, to);
21437 this.bufferStart = from;
21438 this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
21439 this.query = this.normalize(query);
21440 }
21441 peek() {
21442 if (this.bufferPos == this.buffer.length) {
21443 this.bufferStart += this.buffer.length;
21444 this.iter.next();
21445 if (this.iter.done)
21446 return -1;
21447 this.bufferPos = 0;
21448 this.buffer = this.iter.value;
21449 }
21450 return codePointAt(this.buffer, this.bufferPos);
21451 }
21452 /**
21453 Look for the next match. Updates the iterator's
21454 [`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
21455 [`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
21456 at least once before using the cursor.
21457 */
21458 next() {
21459 while (this.matches.length)
21460 this.matches.pop();
21461 return this.nextOverlapping();
21462 }
21463 /**
21464 The `next` method will ignore matches that partially overlap a
21465 previous match. This method behaves like `next`, but includes
21466 such matches.
21467 */
21468 nextOverlapping() {
21469 for (;;) {
21470 let next = this.peek();
21471 if (next < 0) {
21472 this.done = true;
21473 return this;
21474 }
21475 let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos;
21476 this.bufferPos += codePointSize(next);
21477 let norm = this.normalize(str);
21478 for (let i = 0, pos = start;; i++) {
21479 let code = norm.charCodeAt(i);
21480 let match = this.match(code, pos, this.bufferPos + this.bufferStart);
21481 if (i == norm.length - 1) {
21482 if (match) {
21483 this.value = match;
21484 return this;
21485 }
21486 break;
21487 }
21488 if (pos == start && i < str.length && str.charCodeAt(i) == code)
21489 pos++;
21490 }
21491 }
21492 }
21493 match(code, pos, end) {
21494 let match = null;
21495 for (let i = 0; i < this.matches.length; i += 2) {
21496 let index = this.matches[i], keep = false;
21497 if (this.query.charCodeAt(index) == code) {
21498 if (index == this.query.length - 1) {
21499 match = { from: this.matches[i + 1], to: end };
21500 }
21501 else {
21502 this.matches[i]++;
21503 keep = true;
21504 }
21505 }
21506 if (!keep) {
21507 this.matches.splice(i, 2);
21508 i -= 2;
21509 }
21510 }
21511 if (this.query.charCodeAt(0) == code) {
21512 if (this.query.length == 1)
21513 match = { from: pos, to: end };
21514 else
21515 this.matches.push(1, pos);
21516 }
21517 if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart))
21518 match = null;
21519 return match;
21520 }
21521 }
21522 if (typeof Symbol != "undefined")
21523 SearchCursor.prototype[Symbol.iterator] = function () { return this; };
21524
21525 const empty = { from: -1, to: -1, match: /*@__PURE__*//.*/.exec("") };
21526 const baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
21527 /**
21528 This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor)
21529 but searches for a regular expression pattern instead of a plain
21530 string.
21531 */
21532 class RegExpCursor {
21533 /**
21534 Create a cursor that will search the given range in the given
21535 document. `query` should be the raw pattern (as you'd pass it to
21536 `new RegExp`).
21537 */
21538 constructor(text, query, options, from = 0, to = text.length) {
21539 this.text = text;
21540 this.to = to;
21541 this.curLine = "";
21542 /**
21543 Set to `true` when the cursor has reached the end of the search
21544 range.
21545 */
21546 this.done = false;
21547 /**
21548 Will contain an object with the extent of the match and the
21549 match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)
21550 sucessfully finds a match.
21551 */
21552 this.value = empty;
21553 if (/\\[sWDnr]|\n|\r|\[\^/.test(query))
21554 return new MultilineRegExpCursor(text, query, options, from, to);
21555 this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21556 this.test = options === null || options === void 0 ? void 0 : options.test;
21557 this.iter = text.iter();
21558 let startLine = text.lineAt(from);
21559 this.curLineStart = startLine.from;
21560 this.matchPos = toCharEnd(text, from);
21561 this.getLine(this.curLineStart);
21562 }
21563 getLine(skip) {
21564 this.iter.next(skip);
21565 if (this.iter.lineBreak) {
21566 this.curLine = "";
21567 }
21568 else {
21569 this.curLine = this.iter.value;
21570 if (this.curLineStart + this.curLine.length > this.to)
21571 this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
21572 this.iter.next();
21573 }
21574 }
21575 nextLine() {
21576 this.curLineStart = this.curLineStart + this.curLine.length + 1;
21577 if (this.curLineStart > this.to)
21578 this.curLine = "";
21579 else
21580 this.getLine(0);
21581 }
21582 /**
21583 Move to the next match, if there is one.
21584 */
21585 next() {
21586 for (let off = this.matchPos - this.curLineStart;;) {
21587 this.re.lastIndex = off;
21588 let match = this.matchPos <= this.to && this.re.exec(this.curLine);
21589 if (match) {
21590 let from = this.curLineStart + match.index, to = from + match[0].length;
21591 this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21592 if (from == this.curLineStart + this.curLine.length)
21593 this.nextLine();
21594 if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
21595 this.value = { from, to, match };
21596 return this;
21597 }
21598 off = this.matchPos - this.curLineStart;
21599 }
21600 else if (this.curLineStart + this.curLine.length < this.to) {
21601 this.nextLine();
21602 off = 0;
21603 }
21604 else {
21605 this.done = true;
21606 return this;
21607 }
21608 }
21609 }
21610 }
21611 const flattened = /*@__PURE__*/new WeakMap();
21612 // Reusable (partially) flattened document strings
21613 class FlattenedDoc {
21614 constructor(from, text) {
21615 this.from = from;
21616 this.text = text;
21617 }
21618 get to() { return this.from + this.text.length; }
21619 static get(doc, from, to) {
21620 let cached = flattened.get(doc);
21621 if (!cached || cached.from >= to || cached.to <= from) {
21622 let flat = new FlattenedDoc(from, doc.sliceString(from, to));
21623 flattened.set(doc, flat);
21624 return flat;
21625 }
21626 if (cached.from == from && cached.to == to)
21627 return cached;
21628 let { text, from: cachedFrom } = cached;
21629 if (cachedFrom > from) {
21630 text = doc.sliceString(from, cachedFrom) + text;
21631 cachedFrom = from;
21632 }
21633 if (cached.to < to)
21634 text += doc.sliceString(cached.to, to);
21635 flattened.set(doc, new FlattenedDoc(cachedFrom, text));
21636 return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom));
21637 }
21638 }
21639 class MultilineRegExpCursor {
21640 constructor(text, query, options, from, to) {
21641 this.text = text;
21642 this.to = to;
21643 this.done = false;
21644 this.value = empty;
21645 this.matchPos = toCharEnd(text, from);
21646 this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
21647 this.test = options === null || options === void 0 ? void 0 : options.test;
21648 this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5000 /* Chunk.Base */));
21649 }
21650 chunkEnd(pos) {
21651 return pos >= this.to ? this.to : this.text.lineAt(pos).to;
21652 }
21653 next() {
21654 for (;;) {
21655 let off = this.re.lastIndex = this.matchPos - this.flat.from;
21656 let match = this.re.exec(this.flat.text);
21657 // Skip empty matches directly after the last match
21658 if (match && !match[0] && match.index == off) {
21659 this.re.lastIndex = off + 1;
21660 match = this.re.exec(this.flat.text);
21661 }
21662 if (match) {
21663 let from = this.flat.from + match.index, to = from + match[0].length;
21664 // If a match goes almost to the end of a noncomplete chunk, try
21665 // again, since it'll likely be able to match more
21666 if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) &&
21667 (!this.test || this.test(from, to, match))) {
21668 this.value = { from, to, match };
21669 this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
21670 return this;
21671 }
21672 }
21673 if (this.flat.to == this.to) {
21674 this.done = true;
21675 return this;
21676 }
21677 // Grow the flattened doc
21678 this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
21679 }
21680 }
21681 }
21682 if (typeof Symbol != "undefined") {
21683 RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] =
21684 function () { return this; };
21685 }
21686 function validRegExp(source) {
21687 try {
21688 new RegExp(source, baseFlags);
21689 return true;
21690 }
21691 catch (_a) {
21692 return false;
21693 }
21694 }
21695 function toCharEnd(text, pos) {
21696 if (pos >= text.length)
21697 return pos;
21698 let line = text.lineAt(pos), next;
21699 while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 0xDC00 && next < 0xE000)
21700 pos++;
21701 return pos;
21702 }
21703
21704 function createLineDialog(view) {
21705 let line = String(view.state.doc.lineAt(view.state.selection.main.head).number);
21706 let input = crelt("input", { class: "cm-textfield", name: "line", value: line });
21707 let dom = crelt("form", {
21708 class: "cm-gotoLine",
21709 onkeydown: (event) => {
21710 if (event.keyCode == 27) { // Escape
21711 event.preventDefault();
21712 view.dispatch({ effects: dialogEffect.of(false) });
21713 view.focus();
21714 }
21715 else if (event.keyCode == 13) { // Enter
21716 event.preventDefault();
21717 go();
21718 }
21719 },
21720 onsubmit: (event) => {
21721 event.preventDefault();
21722 go();
21723 }
21724 }, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", { class: "cm-button", type: "submit" }, view.state.phrase("go")));
21725 function go() {
21726 let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
21727 if (!match)
21728 return;
21729 let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
21730 let [, sign, ln, cl, percent] = match;
21731 let col = cl ? +cl.slice(1) : 0;
21732 let line = ln ? +ln : startLine.number;
21733 if (ln && percent) {
21734 let pc = line / 100;
21735 if (sign)
21736 pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines);
21737 line = Math.round(state.doc.lines * pc);
21738 }
21739 else if (ln && sign) {
21740 line = line * (sign == "-" ? -1 : 1) + startLine.number;
21741 }
21742 let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
21743 let selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
21744 view.dispatch({
21745 effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection.from, { y: 'center' })],
21746 selection,
21747 });
21748 view.focus();
21749 }
21750 return { dom };
21751 }
21752 const dialogEffect = /*@__PURE__*/StateEffect.define();
21753 const dialogField = /*@__PURE__*/StateField.define({
21754 create() { return true; },
21755 update(value, tr) {
21756 for (let e of tr.effects)
21757 if (e.is(dialogEffect))
21758 value = e.value;
21759 return value;
21760 },
21761 provide: f => showPanel.from(f, val => val ? createLineDialog : null)
21762 });
21763 /**
21764 Command that shows a dialog asking the user for a line number, and
21765 when a valid position is provided, moves the cursor to that line.
21766
21767 Supports line numbers, relative line offsets prefixed with `+` or
21768 `-`, document percentages suffixed with `%`, and an optional
21769 column position by adding `:` and a second number after the line
21770 number.
21771 */
21772 const gotoLine = view => {
21773 let panel = getPanel(view, createLineDialog);
21774 if (!panel) {
21775 let effects = [dialogEffect.of(true)];
21776 if (view.state.field(dialogField, false) == null)
21777 effects.push(StateEffect.appendConfig.of([dialogField, baseTheme$1]));
21778 view.dispatch({ effects });
21779 panel = getPanel(view, createLineDialog);
21780 }
21781 if (panel)
21782 panel.dom.querySelector("input").select();
21783 return true;
21784 };
21785 const baseTheme$1 = /*@__PURE__*/EditorView.baseTheme({
21786 ".cm-panel.cm-gotoLine": {
21787 padding: "2px 6px 4px",
21788 "& label": { fontSize: "80%" }
21789 }
21790 });
21791
21792 const defaultHighlightOptions = {
21793 highlightWordAroundCursor: false,
21794 minSelectionLength: 1,
21795 maxMatches: 100,
21796 wholeWords: false
21797 };
21798 const highlightConfig = /*@__PURE__*/Facet.define({
21799 combine(options) {
21800 return combineConfig(options, defaultHighlightOptions, {
21801 highlightWordAroundCursor: (a, b) => a || b,
21802 minSelectionLength: Math.min,
21803 maxMatches: Math.min
21804 });
21805 }
21806 });
21807 /**
21808 This extension highlights text that matches the selection. It uses
21809 the `"cm-selectionMatch"` class for the highlighting. When
21810 `highlightWordAroundCursor` is enabled, the word at the cursor
21811 itself will be highlighted with `"cm-selectionMatch-main"`.
21812 */
21813 function highlightSelectionMatches(options) {
21814 let ext = [defaultTheme, matchHighlighter];
21815 if (options)
21816 ext.push(highlightConfig.of(options));
21817 return ext;
21818 }
21819 const matchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch" });
21820 const mainMatchDeco = /*@__PURE__*/Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" });
21821 // Whether the characters directly outside the given positions are non-word characters
21822 function insideWordBoundaries(check, state, from, to) {
21823 return (from == 0 || check(state.sliceDoc(from - 1, from)) != exports.CharCategory.Word) &&
21824 (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != exports.CharCategory.Word);
21825 }
21826 // Whether the characters directly at the given positions are word characters
21827 function insideWord(check, state, from, to) {
21828 return check(state.sliceDoc(from, from + 1)) == exports.CharCategory.Word
21829 && check(state.sliceDoc(to - 1, to)) == exports.CharCategory.Word;
21830 }
21831 const matchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
21832 constructor(view) {
21833 this.decorations = this.getDeco(view);
21834 }
21835 update(update) {
21836 if (update.selectionSet || update.docChanged || update.viewportChanged)
21837 this.decorations = this.getDeco(update.view);
21838 }
21839 getDeco(view) {
21840 let conf = view.state.facet(highlightConfig);
21841 let { state } = view, sel = state.selection;
21842 if (sel.ranges.length > 1)
21843 return Decoration.none;
21844 let range = sel.main, query, check = null;
21845 if (range.empty) {
21846 if (!conf.highlightWordAroundCursor)
21847 return Decoration.none;
21848 let word = state.wordAt(range.head);
21849 if (!word)
21850 return Decoration.none;
21851 check = state.charCategorizer(range.head);
21852 query = state.sliceDoc(word.from, word.to);
21853 }
21854 else {
21855 let len = range.to - range.from;
21856 if (len < conf.minSelectionLength || len > 200)
21857 return Decoration.none;
21858 if (conf.wholeWords) {
21859 query = state.sliceDoc(range.from, range.to); // TODO: allow and include leading/trailing space?
21860 check = state.charCategorizer(range.head);
21861 if (!(insideWordBoundaries(check, state, range.from, range.to) &&
21862 insideWord(check, state, range.from, range.to)))
21863 return Decoration.none;
21864 }
21865 else {
21866 query = state.sliceDoc(range.from, range.to);
21867 if (!query)
21868 return Decoration.none;
21869 }
21870 }
21871 let deco = [];
21872 for (let part of view.visibleRanges) {
21873 let cursor = new SearchCursor(state.doc, query, part.from, part.to);
21874 while (!cursor.next().done) {
21875 let { from, to } = cursor.value;
21876 if (!check || insideWordBoundaries(check, state, from, to)) {
21877 if (range.empty && from <= range.from && to >= range.to)
21878 deco.push(mainMatchDeco.range(from, to));
21879 else if (from >= range.to || to <= range.from)
21880 deco.push(matchDeco.range(from, to));
21881 if (deco.length > conf.maxMatches)
21882 return Decoration.none;
21883 }
21884 }
21885 }
21886 return Decoration.set(deco);
21887 }
21888 }, {
21889 decorations: v => v.decorations
21890 });
21891 const defaultTheme = /*@__PURE__*/EditorView.baseTheme({
21892 ".cm-selectionMatch": { backgroundColor: "#99ff7780" },
21893 ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" }
21894 });
21895 // Select the words around the cursors.
21896 const selectWord = ({ state, dispatch }) => {
21897 let { selection } = state;
21898 let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex);
21899 if (newSel.eq(selection))
21900 return false;
21901 dispatch(state.update({ selection: newSel }));
21902 return true;
21903 };
21904 // Find next occurrence of query relative to last cursor. Wrap around
21905 // the document if there are no more matches.
21906 function findNextOccurrence(state, query) {
21907 let { main, ranges } = state.selection;
21908 let word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to;
21909 for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) {
21910 cursor.next();
21911 if (cursor.done) {
21912 if (cycled)
21913 return null;
21914 cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
21915 cycled = true;
21916 }
21917 else {
21918 if (cycled && ranges.some(r => r.from == cursor.value.from))
21919 continue;
21920 if (fullWord) {
21921 let word = state.wordAt(cursor.value.from);
21922 if (!word || word.from != cursor.value.from || word.to != cursor.value.to)
21923 continue;
21924 }
21925 return cursor.value;
21926 }
21927 }
21928 }
21929 /**
21930 Select next occurrence of the current selection. Expand selection
21931 to the surrounding word when the selection is empty.
21932 */
21933 const selectNextOccurrence = ({ state, dispatch }) => {
21934 let { ranges } = state.selection;
21935 if (ranges.some(sel => sel.from === sel.to))
21936 return selectWord({ state, dispatch });
21937 let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
21938 if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText))
21939 return false;
21940 let range = findNextOccurrence(state, searchedText);
21941 if (!range)
21942 return false;
21943 dispatch(state.update({
21944 selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false),
21945 effects: EditorView.scrollIntoView(range.to)
21946 }));
21947 return true;
21948 };
21949
21950 const searchConfigFacet = /*@__PURE__*/Facet.define({
21951 combine(configs) {
21952 return combineConfig(configs, {
21953 top: false,
21954 caseSensitive: false,
21955 literal: false,
21956 regexp: false,
21957 wholeWord: false,
21958 createPanel: view => new SearchPanel(view),
21959 scrollToMatch: range => EditorView.scrollIntoView(range)
21960 });
21961 }
21962 });
21963 /**
21964 Add search state to the editor configuration, and optionally
21965 configure the search extension.
21966 ([`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) will automatically
21967 enable this if it isn't already on).
21968 */
21969 function search(config) {
21970 return config ? [searchConfigFacet.of(config), searchExtensions] : searchExtensions;
21971 }
21972 /**
21973 A search query. Part of the editor's search state.
21974 */
21975 class SearchQuery {
21976 /**
21977 Create a query object.
21978 */
21979 constructor(config) {
21980 this.search = config.search;
21981 this.caseSensitive = !!config.caseSensitive;
21982 this.literal = !!config.literal;
21983 this.regexp = !!config.regexp;
21984 this.replace = config.replace || "";
21985 this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
21986 this.unquoted = this.unquote(this.search);
21987 this.wholeWord = !!config.wholeWord;
21988 }
21989 /**
21990 @internal
21991 */
21992 unquote(text) {
21993 return this.literal ? text :
21994 text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? "\t" : "\\");
21995 }
21996 /**
21997 Compare this query to another query.
21998 */
21999 eq(other) {
22000 return this.search == other.search && this.replace == other.replace &&
22001 this.caseSensitive == other.caseSensitive && this.regexp == other.regexp &&
22002 this.wholeWord == other.wholeWord;
22003 }
22004 /**
22005 @internal
22006 */
22007 create() {
22008 return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
22009 }
22010 /**
22011 Get a search cursor for this query, searching through the given
22012 range in the given state.
22013 */
22014 getCursor(state, from = 0, to) {
22015 let st = state.doc ? state : EditorState.create({ doc: state });
22016 if (to == null)
22017 to = st.doc.length;
22018 return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
22019 }
22020 }
22021 class QueryType {
22022 constructor(spec) {
22023 this.spec = spec;
22024 }
22025 }
22026 function stringCursor(spec, state, from, to) {
22027 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);
22028 }
22029 function stringWordTest(doc, categorizer) {
22030 return (from, to, buf, bufPos) => {
22031 if (bufPos > from || bufPos + buf.length < to) {
22032 bufPos = Math.max(0, from - 2);
22033 buf = doc.sliceString(bufPos, Math.min(doc.length, to + 2));
22034 }
22035 return (categorizer(charBefore(buf, from - bufPos)) != exports.CharCategory.Word ||
22036 categorizer(charAfter(buf, from - bufPos)) != exports.CharCategory.Word) &&
22037 (categorizer(charAfter(buf, to - bufPos)) != exports.CharCategory.Word ||
22038 categorizer(charBefore(buf, to - bufPos)) != exports.CharCategory.Word);
22039 };
22040 }
22041 class StringQuery extends QueryType {
22042 constructor(spec) {
22043 super(spec);
22044 }
22045 nextMatch(state, curFrom, curTo) {
22046 let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
22047 if (cursor.done)
22048 cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping();
22049 return cursor.done ? null : cursor.value;
22050 }
22051 // Searching in reverse is, rather than implementing an inverted search
22052 // cursor, done by scanning chunk after chunk forward.
22053 prevMatchInRange(state, from, to) {
22054 for (let pos = to;;) {
22055 let start = Math.max(from, pos - 10000 /* FindPrev.ChunkSize */ - this.spec.unquoted.length);
22056 let cursor = stringCursor(this.spec, state, start, pos), range = null;
22057 while (!cursor.nextOverlapping().done)
22058 range = cursor.value;
22059 if (range)
22060 return range;
22061 if (start == from)
22062 return null;
22063 pos -= 10000 /* FindPrev.ChunkSize */;
22064 }
22065 }
22066 prevMatch(state, curFrom, curTo) {
22067 return this.prevMatchInRange(state, 0, curFrom) ||
22068 this.prevMatchInRange(state, curTo, state.doc.length);
22069 }
22070 getReplacement(_result) { return this.spec.unquote(this.spec.replace); }
22071 matchAll(state, limit) {
22072 let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = [];
22073 while (!cursor.next().done) {
22074 if (ranges.length >= limit)
22075 return null;
22076 ranges.push(cursor.value);
22077 }
22078 return ranges;
22079 }
22080 highlight(state, from, to, add) {
22081 let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
22082 while (!cursor.next().done)
22083 add(cursor.value.from, cursor.value.to);
22084 }
22085 }
22086 function regexpCursor(spec, state, from, to) {
22087 return new RegExpCursor(state.doc, spec.search, {
22088 ignoreCase: !spec.caseSensitive,
22089 test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : undefined
22090 }, from, to);
22091 }
22092 function charBefore(str, index) {
22093 return str.slice(findClusterBreak(str, index, false), index);
22094 }
22095 function charAfter(str, index) {
22096 return str.slice(index, findClusterBreak(str, index));
22097 }
22098 function regexpWordTest(categorizer) {
22099 return (_from, _to, match) => !match[0].length ||
22100 (categorizer(charBefore(match.input, match.index)) != exports.CharCategory.Word ||
22101 categorizer(charAfter(match.input, match.index)) != exports.CharCategory.Word) &&
22102 (categorizer(charAfter(match.input, match.index + match[0].length)) != exports.CharCategory.Word ||
22103 categorizer(charBefore(match.input, match.index + match[0].length)) != exports.CharCategory.Word);
22104 }
22105 class RegExpQuery extends QueryType {
22106 nextMatch(state, curFrom, curTo) {
22107 let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
22108 if (cursor.done)
22109 cursor = regexpCursor(this.spec, state, 0, curFrom).next();
22110 return cursor.done ? null : cursor.value;
22111 }
22112 prevMatchInRange(state, from, to) {
22113 for (let size = 1;; size++) {
22114 let start = Math.max(from, to - size * 10000 /* FindPrev.ChunkSize */);
22115 let cursor = regexpCursor(this.spec, state, start, to), range = null;
22116 while (!cursor.next().done)
22117 range = cursor.value;
22118 if (range && (start == from || range.from > start + 10))
22119 return range;
22120 if (start == from)
22121 return null;
22122 }
22123 }
22124 prevMatch(state, curFrom, curTo) {
22125 return this.prevMatchInRange(state, 0, curFrom) ||
22126 this.prevMatchInRange(state, curTo, state.doc.length);
22127 }
22128 getReplacement(result) {
22129 return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i) => i == "$" ? "$"
22130 : i == "&" ? result.match[0]
22131 : i != "0" && +i < result.match.length ? result.match[i]
22132 : m);
22133 }
22134 matchAll(state, limit) {
22135 let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = [];
22136 while (!cursor.next().done) {
22137 if (ranges.length >= limit)
22138 return null;
22139 ranges.push(cursor.value);
22140 }
22141 return ranges;
22142 }
22143 highlight(state, from, to, add) {
22144 let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250 /* RegExp.HighlightMargin */), Math.min(to + 250 /* RegExp.HighlightMargin */, state.doc.length));
22145 while (!cursor.next().done)
22146 add(cursor.value.from, cursor.value.to);
22147 }
22148 }
22149 /**
22150 A state effect that updates the current search query. Note that
22151 this only has an effect if the search state has been initialized
22152 (by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or
22153 by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least
22154 once).
22155 */
22156 const setSearchQuery = /*@__PURE__*/StateEffect.define();
22157 const togglePanel = /*@__PURE__*/StateEffect.define();
22158 const searchState = /*@__PURE__*/StateField.define({
22159 create(state) {
22160 return new SearchState(defaultQuery(state).create(), null);
22161 },
22162 update(value, tr) {
22163 for (let effect of tr.effects) {
22164 if (effect.is(setSearchQuery))
22165 value = new SearchState(effect.value.create(), value.panel);
22166 else if (effect.is(togglePanel))
22167 value = new SearchState(value.query, effect.value ? createSearchPanel : null);
22168 }
22169 return value;
22170 },
22171 provide: f => showPanel.from(f, val => val.panel)
22172 });
22173 /**
22174 Get the current search query from an editor state.
22175 */
22176 function getSearchQuery(state) {
22177 let curState = state.field(searchState, false);
22178 return curState ? curState.query.spec : defaultQuery(state);
22179 }
22180 /**
22181 Query whether the search panel is open in the given editor state.
22182 */
22183 function searchPanelOpen(state) {
22184 var _a;
22185 return ((_a = state.field(searchState, false)) === null || _a === void 0 ? void 0 : _a.panel) != null;
22186 }
22187 class SearchState {
22188 constructor(query, panel) {
22189 this.query = query;
22190 this.panel = panel;
22191 }
22192 }
22193 const matchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = /*@__PURE__*/Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" });
22194 const searchHighlighter = /*@__PURE__*/ViewPlugin.fromClass(class {
22195 constructor(view) {
22196 this.view = view;
22197 this.decorations = this.highlight(view.state.field(searchState));
22198 }
22199 update(update) {
22200 let state = update.state.field(searchState);
22201 if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged)
22202 this.decorations = this.highlight(state);
22203 }
22204 highlight({ query, panel }) {
22205 if (!panel || !query.spec.valid)
22206 return Decoration.none;
22207 let { view } = this;
22208 let builder = new RangeSetBuilder();
22209 for (let i = 0, ranges = view.visibleRanges, l = ranges.length; i < l; i++) {
22210 let { from, to } = ranges[i];
22211 while (i < l - 1 && to > ranges[i + 1].from - 2 * 250 /* RegExp.HighlightMargin */)
22212 to = ranges[++i].to;
22213 query.highlight(view.state, from, to, (from, to) => {
22214 let selected = view.state.selection.ranges.some(r => r.from == from && r.to == to);
22215 builder.add(from, to, selected ? selectedMatchMark : matchMark);
22216 });
22217 }
22218 return builder.finish();
22219 }
22220 }, {
22221 decorations: v => v.decorations
22222 });
22223 function searchCommand(f) {
22224 return view => {
22225 let state = view.state.field(searchState, false);
22226 return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
22227 };
22228 }
22229 /**
22230 Open the search panel if it isn't already open, and move the
22231 selection to the first match after the current main selection.
22232 Will wrap around to the start of the document when it reaches the
22233 end.
22234 */
22235 const findNext = /*@__PURE__*/searchCommand((view, { query }) => {
22236 let { to } = view.state.selection.main;
22237 let next = query.nextMatch(view.state, to, to);
22238 if (!next)
22239 return false;
22240 let selection = EditorSelection.single(next.from, next.to);
22241 let config = view.state.facet(searchConfigFacet);
22242 view.dispatch({
22243 selection,
22244 effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)],
22245 userEvent: "select.search"
22246 });
22247 selectSearchInput(view);
22248 return true;
22249 });
22250 /**
22251 Move the selection to the previous instance of the search query,
22252 before the current main selection. Will wrap past the start
22253 of the document to start searching at the end again.
22254 */
22255 const findPrevious = /*@__PURE__*/searchCommand((view, { query }) => {
22256 let { state } = view, { from } = state.selection.main;
22257 let prev = query.prevMatch(state, from, from);
22258 if (!prev)
22259 return false;
22260 let selection = EditorSelection.single(prev.from, prev.to);
22261 let config = view.state.facet(searchConfigFacet);
22262 view.dispatch({
22263 selection,
22264 effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)],
22265 userEvent: "select.search"
22266 });
22267 selectSearchInput(view);
22268 return true;
22269 });
22270 /**
22271 Select all instances of the search query.
22272 */
22273 const selectMatches = /*@__PURE__*/searchCommand((view, { query }) => {
22274 let ranges = query.matchAll(view.state, 1000);
22275 if (!ranges || !ranges.length)
22276 return false;
22277 view.dispatch({
22278 selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))),
22279 userEvent: "select.search.matches"
22280 });
22281 return true;
22282 });
22283 /**
22284 Select all instances of the currently selected text.
22285 */
22286 const selectSelectionMatches = ({ state, dispatch }) => {
22287 let sel = state.selection;
22288 if (sel.ranges.length > 1 || sel.main.empty)
22289 return false;
22290 let { from, to } = sel.main;
22291 let ranges = [], main = 0;
22292 for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) {
22293 if (ranges.length > 1000)
22294 return false;
22295 if (cur.value.from == from)
22296 main = ranges.length;
22297 ranges.push(EditorSelection.range(cur.value.from, cur.value.to));
22298 }
22299 dispatch(state.update({
22300 selection: EditorSelection.create(ranges, main),
22301 userEvent: "select.search.matches"
22302 }));
22303 return true;
22304 };
22305 /**
22306 Replace the current match of the search query.
22307 */
22308 const replaceNext = /*@__PURE__*/searchCommand((view, { query }) => {
22309 let { state } = view, { from, to } = state.selection.main;
22310 if (state.readOnly)
22311 return false;
22312 let next = query.nextMatch(state, from, from);
22313 if (!next)
22314 return false;
22315 let changes = [], selection, replacement;
22316 let effects = [];
22317 if (next.from == from && next.to == to) {
22318 replacement = state.toText(query.getReplacement(next));
22319 changes.push({ from: next.from, to: next.to, insert: replacement });
22320 next = query.nextMatch(state, next.from, next.to);
22321 effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
22322 }
22323 if (next) {
22324 let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length;
22325 selection = EditorSelection.single(next.from - off, next.to - off);
22326 effects.push(announceMatch(view, next));
22327 effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
22328 }
22329 view.dispatch({
22330 changes, selection, effects,
22331 userEvent: "input.replace"
22332 });
22333 return true;
22334 });
22335 /**
22336 Replace all instances of the search query with the given
22337 replacement.
22338 */
22339 const replaceAll = /*@__PURE__*/searchCommand((view, { query }) => {
22340 if (view.state.readOnly)
22341 return false;
22342 let changes = query.matchAll(view.state, 1e9).map(match => {
22343 let { from, to } = match;
22344 return { from, to, insert: query.getReplacement(match) };
22345 });
22346 if (!changes.length)
22347 return false;
22348 let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
22349 view.dispatch({
22350 changes,
22351 effects: EditorView.announce.of(announceText),
22352 userEvent: "input.replace.all"
22353 });
22354 return true;
22355 });
22356 function createSearchPanel(view) {
22357 return view.state.facet(searchConfigFacet).createPanel(view);
22358 }
22359 function defaultQuery(state, fallback) {
22360 var _a, _b, _c, _d, _e;
22361 let sel = state.selection.main;
22362 let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
22363 if (fallback && !selText)
22364 return fallback;
22365 let config = state.facet(searchConfigFacet);
22366 return new SearchQuery({
22367 search: ((_a = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a !== void 0 ? _a : config.literal) ? selText : selText.replace(/\n/g, "\\n"),
22368 caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config.caseSensitive,
22369 literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config.literal,
22370 regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config.regexp,
22371 wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config.wholeWord
22372 });
22373 }
22374 function getSearchInput(view) {
22375 let panel = getPanel(view, createSearchPanel);
22376 return panel && panel.dom.querySelector("[main-field]");
22377 }
22378 function selectSearchInput(view) {
22379 let input = getSearchInput(view);
22380 if (input && input == view.root.activeElement)
22381 input.select();
22382 }
22383 /**
22384 Make sure the search panel is open and focused.
22385 */
22386 const openSearchPanel = view => {
22387 let state = view.state.field(searchState, false);
22388 if (state && state.panel) {
22389 let searchInput = getSearchInput(view);
22390 if (searchInput && searchInput != view.root.activeElement) {
22391 let query = defaultQuery(view.state, state.query.spec);
22392 if (query.valid)
22393 view.dispatch({ effects: setSearchQuery.of(query) });
22394 searchInput.focus();
22395 searchInput.select();
22396 }
22397 }
22398 else {
22399 view.dispatch({ effects: [
22400 togglePanel.of(true),
22401 state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)
22402 ] });
22403 }
22404 return true;
22405 };
22406 /**
22407 Close the search panel.
22408 */
22409 const closeSearchPanel = view => {
22410 let state = view.state.field(searchState, false);
22411 if (!state || !state.panel)
22412 return false;
22413 let panel = getPanel(view, createSearchPanel);
22414 if (panel && panel.dom.contains(view.root.activeElement))
22415 view.focus();
22416 view.dispatch({ effects: togglePanel.of(false) });
22417 return true;
22418 };
22419 /**
22420 Default search-related key bindings.
22421
22422 - Mod-f: [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel)
22423 - F3, Mod-g: [`findNext`](https://codemirror.net/6/docs/ref/#search.findNext)
22424 - Shift-F3, Shift-Mod-g: [`findPrevious`](https://codemirror.net/6/docs/ref/#search.findPrevious)
22425 - Mod-Alt-g: [`gotoLine`](https://codemirror.net/6/docs/ref/#search.gotoLine)
22426 - Mod-d: [`selectNextOccurrence`](https://codemirror.net/6/docs/ref/#search.selectNextOccurrence)
22427 */
22428 const searchKeymap = [
22429 { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
22430 { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22431 { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: true },
22432 { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
22433 { key: "Mod-Shift-l", run: selectSelectionMatches },
22434 { key: "Mod-Alt-g", run: gotoLine },
22435 { key: "Mod-d", run: selectNextOccurrence, preventDefault: true },
22436 ];
22437 class SearchPanel {
22438 constructor(view) {
22439 this.view = view;
22440 let query = this.query = view.state.field(searchState).query.spec;
22441 this.commit = this.commit.bind(this);
22442 this.searchField = crelt("input", {
22443 value: query.search,
22444 placeholder: phrase(view, "Find"),
22445 "aria-label": phrase(view, "Find"),
22446 class: "cm-textfield",
22447 name: "search",
22448 form: "",
22449 "main-field": "true",
22450 onchange: this.commit,
22451 onkeyup: this.commit
22452 });
22453 this.replaceField = crelt("input", {
22454 value: query.replace,
22455 placeholder: phrase(view, "Replace"),
22456 "aria-label": phrase(view, "Replace"),
22457 class: "cm-textfield",
22458 name: "replace",
22459 form: "",
22460 onchange: this.commit,
22461 onkeyup: this.commit
22462 });
22463 this.caseField = crelt("input", {
22464 type: "checkbox",
22465 name: "case",
22466 form: "",
22467 checked: query.caseSensitive,
22468 onchange: this.commit
22469 });
22470 this.reField = crelt("input", {
22471 type: "checkbox",
22472 name: "re",
22473 form: "",
22474 checked: query.regexp,
22475 onchange: this.commit
22476 });
22477 this.wordField = crelt("input", {
22478 type: "checkbox",
22479 name: "word",
22480 form: "",
22481 checked: query.wholeWord,
22482 onchange: this.commit
22483 });
22484 function button(name, onclick, content) {
22485 return crelt("button", { class: "cm-button", name, onclick, type: "button" }, content);
22486 }
22487 this.dom = crelt("div", { onkeydown: (e) => this.keydown(e), class: "cm-search" }, [
22488 this.searchField,
22489 button("next", () => findNext(view), [phrase(view, "next")]),
22490 button("prev", () => findPrevious(view), [phrase(view, "previous")]),
22491 button("select", () => selectMatches(view), [phrase(view, "all")]),
22492 crelt("label", null, [this.caseField, phrase(view, "match case")]),
22493 crelt("label", null, [this.reField, phrase(view, "regexp")]),
22494 crelt("label", null, [this.wordField, phrase(view, "by word")]),
22495 ...view.state.readOnly ? [] : [
22496 crelt("br"),
22497 this.replaceField,
22498 button("replace", () => replaceNext(view), [phrase(view, "replace")]),
22499 button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])
22500 ],
22501 crelt("button", {
22502 name: "close",
22503 onclick: () => closeSearchPanel(view),
22504 "aria-label": phrase(view, "close"),
22505 type: "button"
22506 }, ["×"])
22507 ]);
22508 }
22509 commit() {
22510 let query = new SearchQuery({
22511 search: this.searchField.value,
22512 caseSensitive: this.caseField.checked,
22513 regexp: this.reField.checked,
22514 wholeWord: this.wordField.checked,
22515 replace: this.replaceField.value,
22516 });
22517 if (!query.eq(this.query)) {
22518 this.query = query;
22519 this.view.dispatch({ effects: setSearchQuery.of(query) });
22520 }
22521 }
22522 keydown(e) {
22523 if (runScopeHandlers(this.view, e, "search-panel")) {
22524 e.preventDefault();
22525 }
22526 else if (e.keyCode == 13 && e.target == this.searchField) {
22527 e.preventDefault();
22528 (e.shiftKey ? findPrevious : findNext)(this.view);
22529 }
22530 else if (e.keyCode == 13 && e.target == this.replaceField) {
22531 e.preventDefault();
22532 replaceNext(this.view);
22533 }
22534 }
22535 update(update) {
22536 for (let tr of update.transactions)
22537 for (let effect of tr.effects) {
22538 if (effect.is(setSearchQuery) && !effect.value.eq(this.query))
22539 this.setQuery(effect.value);
22540 }
22541 }
22542 setQuery(query) {
22543 this.query = query;
22544 this.searchField.value = query.search;
22545 this.replaceField.value = query.replace;
22546 this.caseField.checked = query.caseSensitive;
22547 this.reField.checked = query.regexp;
22548 this.wordField.checked = query.wholeWord;
22549 }
22550 mount() {
22551 this.searchField.select();
22552 }
22553 get pos() { return 80; }
22554 get top() { return this.view.state.facet(searchConfigFacet).top; }
22555 }
22556 function phrase(view, phrase) { return view.state.phrase(phrase); }
22557 const AnnounceMargin = 30;
22558 const Break = /[\s\.,:;?!]/;
22559 function announceMatch(view, { from, to }) {
22560 let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to;
22561 let start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
22562 let text = view.state.sliceDoc(start, end);
22563 if (start != line.from) {
22564 for (let i = 0; i < AnnounceMargin; i++)
22565 if (!Break.test(text[i + 1]) && Break.test(text[i])) {
22566 text = text.slice(i);
22567 break;
22568 }
22569 }
22570 if (end != lineEnd) {
22571 for (let i = text.length - 1; i > text.length - AnnounceMargin; i--)
22572 if (!Break.test(text[i - 1]) && Break.test(text[i])) {
22573 text = text.slice(0, i);
22574 break;
22575 }
22576 }
22577 return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`);
22578 }
22579 const baseTheme = /*@__PURE__*/EditorView.baseTheme({
22580 ".cm-panel.cm-search": {
22581 padding: "2px 6px 4px",
22582 position: "relative",
22583 "& [name=close]": {
22584 position: "absolute",
22585 top: "0",
22586 right: "4px",
22587 backgroundColor: "inherit",
22588 border: "none",
22589 font: "inherit",
22590 padding: 0,
22591 margin: 0
22592 },
22593 "& input, & button, & label": {
22594 margin: ".2em .6em .2em 0"
22595 },
22596 "& input[type=checkbox]": {
22597 marginRight: ".2em"
22598 },
22599 "& label": {
22600 fontSize: "80%",
22601 whiteSpace: "pre"
22602 }
22603 },
22604 "&light .cm-searchMatch": { backgroundColor: "#ffff0054" },
22605 "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" },
22606 "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" },
22607 "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" }
22608 });
22609 const searchExtensions = [
22610 searchState,
22611 /*@__PURE__*/Prec.low(searchHighlighter),
22612 baseTheme
22613 ];
22614
22615 exports.Annotation = Annotation;
22616 exports.AnnotationType = AnnotationType;
22617 exports.BidiSpan = BidiSpan;
22618 exports.BlockInfo = BlockInfo;
22619 exports.ChangeDesc = ChangeDesc;
22620 exports.ChangeSet = ChangeSet;
22621 exports.Compartment = Compartment;
22622 exports.Decoration = Decoration;
22623 exports.DocInput = DocInput;
22624 exports.EditorSelection = EditorSelection;
22625 exports.EditorState = EditorState;
22626 exports.EditorView = EditorView;
22627 exports.Facet = Facet;
22628 exports.GutterMarker = GutterMarker;
22629 exports.HighlightStyle = HighlightStyle;
22630 exports.IndentContext = IndentContext;
22631 exports.LRLanguage = LRLanguage;
22632 exports.Language = Language;
22633 exports.LanguageDescription = LanguageDescription;
22634 exports.LanguageSupport = LanguageSupport;
22635 exports.Line = Line;
22636 exports.MatchDecorator = MatchDecorator;
22637 exports.ParseContext = ParseContext;
22638 exports.Prec = Prec;
22639 exports.Range = Range$1;
22640 exports.RangeSet = RangeSet;
22641 exports.RangeSetBuilder = RangeSetBuilder;
22642 exports.RangeValue = RangeValue;
22643 exports.RectangleMarker = RectangleMarker;
22644 exports.RegExpCursor = RegExpCursor;
22645 exports.SearchCursor = SearchCursor;
22646 exports.SearchQuery = SearchQuery;
22647 exports.SelectionRange = SelectionRange;
22648 exports.StateEffect = StateEffect;
22649 exports.StateEffectType = StateEffectType;
22650 exports.StateField = StateField;
22651 exports.StreamLanguage = StreamLanguage;
22652 exports.StringStream = StringStream;
22653 exports.Tag = Tag;
22654 exports.Text = Text;
22655 exports.Transaction = Transaction;
22656 exports.TreeIndentContext = TreeIndentContext;
22657 exports.ViewPlugin = ViewPlugin;
22658 exports.ViewUpdate = ViewUpdate;
22659 exports.WidgetType = WidgetType;
22660 exports.__test = __test;
22661 exports.blockComment = blockComment;
22662 exports.blockUncomment = blockUncomment;
22663 exports.bracketMatching = bracketMatching;
22664 exports.bracketMatchingHandle = bracketMatchingHandle;
22665 exports.classHighlighter = classHighlighter;
22666 exports.closeHoverTooltips = closeHoverTooltips;
22667 exports.closeSearchPanel = closeSearchPanel;
22668 exports.codeFolding = codeFolding;
22669 exports.codePointAt = codePointAt;
22670 exports.codePointSize = codePointSize;
22671 exports.combineConfig = combineConfig;
22672 exports.continuedIndent = continuedIndent;
22673 exports.copyLineDown = copyLineDown;
22674 exports.copyLineUp = copyLineUp;
22675 exports.countColumn = countColumn;
22676 exports.crosshairCursor = crosshairCursor;
22677 exports.cursorCharBackward = cursorCharBackward;
22678 exports.cursorCharForward = cursorCharForward;
22679 exports.cursorCharLeft = cursorCharLeft;
22680 exports.cursorCharRight = cursorCharRight;
22681 exports.cursorDocEnd = cursorDocEnd;
22682 exports.cursorDocStart = cursorDocStart;
22683 exports.cursorGroupBackward = cursorGroupBackward;
22684 exports.cursorGroupForward = cursorGroupForward;
22685 exports.cursorGroupLeft = cursorGroupLeft;
22686 exports.cursorGroupRight = cursorGroupRight;
22687 exports.cursorLineBoundaryBackward = cursorLineBoundaryBackward;
22688 exports.cursorLineBoundaryForward = cursorLineBoundaryForward;
22689 exports.cursorLineBoundaryLeft = cursorLineBoundaryLeft;
22690 exports.cursorLineBoundaryRight = cursorLineBoundaryRight;
22691 exports.cursorLineDown = cursorLineDown;
22692 exports.cursorLineEnd = cursorLineEnd;
22693 exports.cursorLineStart = cursorLineStart;
22694 exports.cursorLineUp = cursorLineUp;
22695 exports.cursorMatchingBracket = cursorMatchingBracket;
22696 exports.cursorPageDown = cursorPageDown;
22697 exports.cursorPageUp = cursorPageUp;
22698 exports.cursorSubwordBackward = cursorSubwordBackward;
22699 exports.cursorSubwordForward = cursorSubwordForward;
22700 exports.cursorSyntaxLeft = cursorSyntaxLeft;
22701 exports.cursorSyntaxRight = cursorSyntaxRight;
22702 exports.defaultHighlightStyle = defaultHighlightStyle;
22703 exports.defaultKeymap = defaultKeymap;
22704 exports.defineLanguageFacet = defineLanguageFacet;
22705 exports.deleteCharBackward = deleteCharBackward;
22706 exports.deleteCharForward = deleteCharForward;
22707 exports.deleteGroupBackward = deleteGroupBackward;
22708 exports.deleteGroupForward = deleteGroupForward;
22709 exports.deleteLine = deleteLine;
22710 exports.deleteToLineEnd = deleteToLineEnd;
22711 exports.deleteToLineStart = deleteToLineStart;
22712 exports.deleteTrailingWhitespace = deleteTrailingWhitespace;
22713 exports.delimitedIndent = delimitedIndent;
22714 exports.drawSelection = drawSelection;
22715 exports.dropCursor = dropCursor;
22716 exports.emacsStyleKeymap = emacsStyleKeymap;
22717 exports.ensureSyntaxTree = ensureSyntaxTree;
22718 exports.findClusterBreak = findClusterBreak;
22719 exports.findColumn = findColumn;
22720 exports.findNext = findNext;
22721 exports.findPrevious = findPrevious;
22722 exports.flatIndent = flatIndent;
22723 exports.foldAll = foldAll;
22724 exports.foldCode = foldCode;
22725 exports.foldEffect = foldEffect;
22726 exports.foldGutter = foldGutter;
22727 exports.foldInside = foldInside;
22728 exports.foldKeymap = foldKeymap;
22729 exports.foldNodeProp = foldNodeProp;
22730 exports.foldService = foldService;
22731 exports.foldState = foldState;
22732 exports.foldable = foldable;
22733 exports.foldedRanges = foldedRanges;
22734 exports.forceParsing = forceParsing;
22735 exports.fromCodePoint = fromCodePoint;
22736 exports.getDrawSelectionConfig = getDrawSelectionConfig;
22737 exports.getIndentUnit = getIndentUnit;
22738 exports.getIndentation = getIndentation;
22739 exports.getPanel = getPanel;
22740 exports.getSearchQuery = getSearchQuery;
22741 exports.getStyleTags = getStyleTags;
22742 exports.getTooltip = getTooltip;
22743 exports.gotoLine = gotoLine;
22744 exports.gutter = gutter;
22745 exports.gutterLineClass = gutterLineClass;
22746 exports.gutters = gutters;
22747 exports.hasHoverTooltips = hasHoverTooltips;
22748 exports.highlightActiveLine = highlightActiveLine;
22749 exports.highlightActiveLineGutter = highlightActiveLineGutter;
22750 exports.highlightCode = highlightCode;
22751 exports.highlightSelectionMatches = highlightSelectionMatches;
22752 exports.highlightSpecialChars = highlightSpecialChars;
22753 exports.highlightTrailingWhitespace = highlightTrailingWhitespace;
22754 exports.highlightTree = highlightTree;
22755 exports.highlightWhitespace = highlightWhitespace;
22756 exports.highlightingFor = highlightingFor;
22757 exports.history = history;
22758 exports.historyField = historyField;
22759 exports.historyKeymap = historyKeymap;
22760 exports.hoverTooltip = hoverTooltip;
22761 exports.indentLess = indentLess;
22762 exports.indentMore = indentMore;
22763 exports.indentNodeProp = indentNodeProp;
22764 exports.indentOnInput = indentOnInput;
22765 exports.indentRange = indentRange;
22766 exports.indentSelection = indentSelection;
22767 exports.indentService = indentService;
22768 exports.indentString = indentString;
22769 exports.indentUnit = indentUnit;
22770 exports.indentWithTab = indentWithTab;
22771 exports.insertBlankLine = insertBlankLine;
22772 exports.insertNewline = insertNewline;
22773 exports.insertNewlineAndIndent = insertNewlineAndIndent;
22774 exports.insertTab = insertTab;
22775 exports.invertedEffects = invertedEffects;
22776 exports.isolateHistory = isolateHistory;
22777 exports.keymap = keymap;
22778 exports.language = language;
22779 exports.languageDataProp = languageDataProp;
22780 exports.layer = layer;
22781 exports.lineComment = lineComment;
22782 exports.lineNumberMarkers = lineNumberMarkers;
22783 exports.lineNumbers = lineNumbers;
22784 exports.lineUncomment = lineUncomment;
22785 exports.logException = logException;
22786 exports.matchBrackets = matchBrackets;
22787 exports.moveLineDown = moveLineDown;
22788 exports.moveLineUp = moveLineUp;
22789 exports.openSearchPanel = openSearchPanel;
22790 exports.panels = panels;
22791 exports.placeholder = placeholder;
22792 exports.rectangularSelection = rectangularSelection;
22793 exports.redo = redo;
22794 exports.redoDepth = redoDepth;
22795 exports.redoSelection = redoSelection;
22796 exports.replaceAll = replaceAll;
22797 exports.replaceNext = replaceNext;
22798 exports.repositionTooltips = repositionTooltips;
22799 exports.runScopeHandlers = runScopeHandlers;
22800 exports.scrollPastEnd = scrollPastEnd;
22801 exports.search = search;
22802 exports.searchKeymap = searchKeymap;
22803 exports.searchPanelOpen = searchPanelOpen;
22804 exports.selectAll = selectAll;
22805 exports.selectCharBackward = selectCharBackward;
22806 exports.selectCharForward = selectCharForward;
22807 exports.selectCharLeft = selectCharLeft;
22808 exports.selectCharRight = selectCharRight;
22809 exports.selectDocEnd = selectDocEnd;
22810 exports.selectDocStart = selectDocStart;
22811 exports.selectGroupBackward = selectGroupBackward;
22812 exports.selectGroupForward = selectGroupForward;
22813 exports.selectGroupLeft = selectGroupLeft;
22814 exports.selectGroupRight = selectGroupRight;
22815 exports.selectLine = selectLine;
22816 exports.selectLineBoundaryBackward = selectLineBoundaryBackward;
22817 exports.selectLineBoundaryForward = selectLineBoundaryForward;
22818 exports.selectLineBoundaryLeft = selectLineBoundaryLeft;
22819 exports.selectLineBoundaryRight = selectLineBoundaryRight;
22820 exports.selectLineDown = selectLineDown;
22821 exports.selectLineEnd = selectLineEnd;
22822 exports.selectLineStart = selectLineStart;
22823 exports.selectLineUp = selectLineUp;
22824 exports.selectMatches = selectMatches;
22825 exports.selectMatchingBracket = selectMatchingBracket;
22826 exports.selectNextOccurrence = selectNextOccurrence;
22827 exports.selectPageDown = selectPageDown;
22828 exports.selectPageUp = selectPageUp;
22829 exports.selectParentSyntax = selectParentSyntax;
22830 exports.selectSelectionMatches = selectSelectionMatches;
22831 exports.selectSubwordBackward = selectSubwordBackward;
22832 exports.selectSubwordForward = selectSubwordForward;
22833 exports.selectSyntaxLeft = selectSyntaxLeft;
22834 exports.selectSyntaxRight = selectSyntaxRight;
22835 exports.setSearchQuery = setSearchQuery;
22836 exports.showPanel = showPanel;
22837 exports.showTooltip = showTooltip;
22838 exports.simplifySelection = simplifySelection;
22839 exports.splitLine = splitLine;
22840 exports.standardKeymap = standardKeymap;
22841 exports.styleTags = styleTags;
22842 exports.sublanguageProp = sublanguageProp;
22843 exports.syntaxHighlighting = syntaxHighlighting;
22844 exports.syntaxParserRunning = syntaxParserRunning;
22845 exports.syntaxTree = syntaxTree;
22846 exports.syntaxTreeAvailable = syntaxTreeAvailable;
22847 exports.tagHighlighter = tagHighlighter;
22848 exports.tags = tags;
22849 exports.toggleBlockComment = toggleBlockComment;
22850 exports.toggleBlockCommentByLine = toggleBlockCommentByLine;
22851 exports.toggleComment = toggleComment;
22852 exports.toggleFold = toggleFold;
22853 exports.toggleLineComment = toggleLineComment;
22854 exports.tooltips = tooltips;
22855 exports.transposeChars = transposeChars;
22856 exports.undo = undo;
22857 exports.undoDepth = undoDepth;
22858 exports.undoSelection = undoSelection;
22859 exports.unfoldAll = unfoldAll;
22860 exports.unfoldCode = unfoldCode;
22861 exports.unfoldEffect = unfoldEffect;