You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

20979 lines
986 KiB

  1. (function () {
  2. 'use strict';
  3. // Compressed representation of the Grapheme_Cluster_Break=Extend
  4. // information from
  5. // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
  6. // Each pair of elements represents a range, as an offet from the
  7. // previous range and a length. Numbers are in base-36, with the empty
  8. // string being a shorthand for 1.
  9. let extend = "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);
  10. // Convert offsets into absolute values
  11. for (let i = 1; i < extend.length; i++)
  12. extend[i] += extend[i - 1];
  13. function isExtendingChar(code) {
  14. for (let i = 1; i < extend.length; i += 2)
  15. if (extend[i] > code)
  16. return extend[i - 1] <= code;
  17. return false;
  18. }
  19. function isRegionalIndicator(code) {
  20. return code >= 0x1F1E6 && code <= 0x1F1FF;
  21. }
  22. const ZWJ = 0x200d;
  23. /// Returns a next grapheme cluster break _after_ (not equal to)
  24. /// `pos`, if `forward` is true, or before otherwise. Returns `pos`
  25. /// itself if no further cluster break is available in the string.
  26. /// Moves across surrogate pairs, extending characters, characters
  27. /// joined with zero-width joiners, and flag emoji.
  28. function findClusterBreak(str, pos, forward = true) {
  29. return (forward ? nextClusterBreak : prevClusterBreak)(str, pos);
  30. }
  31. function nextClusterBreak(str, pos) {
  32. if (pos == str.length)
  33. return pos;
  34. // If pos is in the middle of a surrogate pair, move to its start
  35. if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
  36. pos--;
  37. let prev = codePointAt(str, pos);
  38. pos += codePointSize(prev);
  39. while (pos < str.length) {
  40. let next = codePointAt(str, pos);
  41. if (prev == ZWJ || next == ZWJ || isExtendingChar(next)) {
  42. pos += codePointSize(next);
  43. prev = next;
  44. }
  45. else if (isRegionalIndicator(next)) {
  46. let countBefore = 0, i = pos - 2;
  47. while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
  48. countBefore++;
  49. i -= 2;
  50. }
  51. if (countBefore % 2 == 0)
  52. break;
  53. else
  54. pos += 2;
  55. }
  56. else {
  57. break;
  58. }
  59. }
  60. return pos;
  61. }
  62. function prevClusterBreak(str, pos) {
  63. while (pos > 0) {
  64. let found = nextClusterBreak(str, pos - 2);
  65. if (found < pos)
  66. return found;
  67. pos--;
  68. }
  69. return 0;
  70. }
  71. function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
  72. function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
  73. /// Find the code point at the given position in a string (like the
  74. /// [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
  75. /// string method).
  76. function codePointAt(str, pos) {
  77. let code0 = str.charCodeAt(pos);
  78. if (!surrogateHigh(code0) || pos + 1 == str.length)
  79. return code0;
  80. let code1 = str.charCodeAt(pos + 1);
  81. if (!surrogateLow(code1))
  82. return code0;
  83. return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
  84. }
  85. /// Given a Unicode codepoint, return the JavaScript string that
  86. /// respresents it (like
  87. /// [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
  88. function fromCodePoint(code) {
  89. if (code <= 0xffff)
  90. return String.fromCharCode(code);
  91. code -= 0x10000;
  92. return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
  93. }
  94. /// The first character that takes up two positions in a JavaScript
  95. /// string. It is often useful to compare with this after calling
  96. /// `codePointAt`, to figure out whether your character takes up 1 or
  97. /// 2 index positions.
  98. function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
  99. /// Count the column position at the given offset into the string,
  100. /// taking extending characters and tab size into account.
  101. function countColumn(string, n, tabSize) {
  102. for (let i = 0; i < string.length;) {
  103. if (string.charCodeAt(i) == 9) {
  104. n += tabSize - (n % tabSize);
  105. i++;
  106. }
  107. else {
  108. n++;
  109. i = findClusterBreak(string, i);
  110. }
  111. }
  112. return n;
  113. }
  114. /// Find the offset that corresponds to the given column position in a
  115. /// string, taking extending characters and tab size into account.
  116. function findColumn(string, n, col, tabSize) {
  117. for (let i = 0; i < string.length;) {
  118. if (n >= col)
  119. return { offset: i, leftOver: 0 };
  120. n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
  121. i = findClusterBreak(string, i);
  122. }
  123. return { offset: string.length, leftOver: col - n };
  124. }
  125. /// The data structure for documents.
  126. class Text {
  127. /// @internal
  128. constructor() { }
  129. /// Get the line description around the given position.
  130. lineAt(pos) {
  131. if (pos < 0 || pos > this.length)
  132. throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
  133. return this.lineInner(pos, false, 1, 0);
  134. }
  135. /// Get the description for the given (1-based) line number.
  136. line(n) {
  137. if (n < 1 || n > this.lines)
  138. throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
  139. return this.lineInner(n, true, 1, 0);
  140. }
  141. /// Replace a range of the text with the given content.
  142. replace(from, to, text) {
  143. let parts = [];
  144. this.decompose(0, from, parts, 2 /* To */);
  145. if (text.length)
  146. text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */);
  147. this.decompose(to, this.length, parts, 1 /* From */);
  148. return TextNode.from(parts, this.length - (to - from) + text.length);
  149. }
  150. /// Append another document to this one.
  151. append(other) {
  152. return this.replace(this.length, this.length, other);
  153. }
  154. /// Retrieve the text between the given points.
  155. slice(from, to = this.length) {
  156. let parts = [];
  157. this.decompose(from, to, parts, 0);
  158. return TextNode.from(parts, to - from);
  159. }
  160. /// Test whether this text is equal to another instance.
  161. eq(other) {
  162. if (other == this)
  163. return true;
  164. if (other.length != this.length || other.lines != this.lines)
  165. return false;
  166. let a = new RawTextCursor(this), b = new RawTextCursor(other);
  167. for (;;) {
  168. a.next();
  169. b.next();
  170. if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
  171. return false;
  172. if (a.done)
  173. return true;
  174. }
  175. }
  176. /// Iterate over the text. When `dir` is `-1`, iteration happens
  177. /// from end to start. This will return lines and the breaks between
  178. /// them as separate strings, and for long lines, might split lines
  179. /// themselves into multiple chunks as well.
  180. iter(dir = 1) { return new RawTextCursor(this, dir); }
  181. /// Iterate over a range of the text. When `from` > `to`, the
  182. /// iterator will run in reverse.
  183. iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
  184. /// @internal
  185. toString() { return this.sliceString(0); }
  186. /// Convert the document to an array of lines (which can be
  187. /// deserialized again via [`Text.of`](#text.Text^of)).
  188. toJSON() {
  189. let lines = [];
  190. this.flatten(lines);
  191. return lines;
  192. }
  193. /// Create a `Text` instance for the given array of lines.
  194. static of(text) {
  195. if (text.length == 0)
  196. throw new RangeError("A document must have at least one line");
  197. if (text.length == 1 && !text[0])
  198. return Text.empty;
  199. return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
  200. }
  201. }
  202. if (typeof Symbol != "undefined")
  203. Text.prototype[Symbol.iterator] = function () { return this.iter(); };
  204. // Leaves store an array of line strings. There are always line breaks
  205. // between these strings. Leaves are limited in size and have to be
  206. // contained in TextNode instances for bigger documents.
  207. class TextLeaf extends Text {
  208. constructor(text, length = textLength(text)) {
  209. super();
  210. this.text = text;
  211. this.length = length;
  212. }
  213. get lines() { return this.text.length; }
  214. get children() { return null; }
  215. lineInner(target, isLine, line, offset) {
  216. for (let i = 0;; i++) {
  217. let string = this.text[i], end = offset + string.length;
  218. if ((isLine ? line : end) >= target)
  219. return new Line(offset, end, line, string);
  220. offset = end + 1;
  221. line++;
  222. }
  223. }
  224. decompose(from, to, target, open) {
  225. let text = from <= 0 && to >= this.length ? this
  226. : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
  227. if (open & 1 /* From */) {
  228. let prev = target.pop();
  229. let joined = appendText(text.text, prev.text.slice(), 0, text.length);
  230. if (joined.length <= 32 /* Branch */) {
  231. target.push(new TextLeaf(joined, prev.length + text.length));
  232. }
  233. else {
  234. let mid = joined.length >> 1;
  235. target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
  236. }
  237. }
  238. else {
  239. target.push(text);
  240. }
  241. }
  242. replace(from, to, text) {
  243. if (!(text instanceof TextLeaf))
  244. return super.replace(from, to, text);
  245. let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
  246. let newLen = this.length + text.length - (to - from);
  247. if (lines.length <= 32 /* Branch */)
  248. return new TextLeaf(lines, newLen);
  249. return TextNode.from(TextLeaf.split(lines, []), newLen);
  250. }
  251. sliceString(from, to = this.length, lineSep = "\n") {
  252. let result = "";
  253. for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
  254. let line = this.text[i], end = pos + line.length;
  255. if (pos > from && i)
  256. result += lineSep;
  257. if (from < end && to > pos)
  258. result += line.slice(Math.max(0, from - pos), to - pos);
  259. pos = end + 1;
  260. }
  261. return result;
  262. }
  263. flatten(target) {
  264. for (let line of this.text)
  265. target.push(line);
  266. }
  267. static split(text, target) {
  268. let part = [], len = -1;
  269. for (let line of text) {
  270. part.push(line);
  271. len += line.length + 1;
  272. if (part.length == 32 /* Branch */) {
  273. target.push(new TextLeaf(part, len));
  274. part = [];
  275. len = -1;
  276. }
  277. }
  278. if (len > -1)
  279. target.push(new TextLeaf(part, len));
  280. return target;
  281. }
  282. }
  283. // Nodes provide the tree structure of the `Text` type. They store a
  284. // number of other nodes or leaves, taking care to balance themselves
  285. // on changes. There are implied line breaks _between_ the children of
  286. // a node (but not before the first or after the last child).
  287. class TextNode extends Text {
  288. constructor(children, length) {
  289. super();
  290. this.children = children;
  291. this.length = length;
  292. this.lines = 0;
  293. for (let child of children)
  294. this.lines += child.lines;
  295. }
  296. lineInner(target, isLine, line, offset) {
  297. for (let i = 0;; i++) {
  298. let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
  299. if ((isLine ? endLine : end) >= target)
  300. return child.lineInner(target, isLine, line, offset);
  301. offset = end + 1;
  302. line = endLine + 1;
  303. }
  304. }
  305. decompose(from, to, target, open) {
  306. for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
  307. let child = this.children[i], end = pos + child.length;
  308. if (from <= end && to >= pos) {
  309. let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0));
  310. if (pos >= from && end <= to && !childOpen)
  311. target.push(child);
  312. else
  313. child.decompose(from - pos, to - pos, target, childOpen);
  314. }
  315. pos = end + 1;
  316. }
  317. }
  318. replace(from, to, text) {
  319. if (text.lines < this.lines)
  320. for (let i = 0, pos = 0; i < this.children.length; i++) {
  321. let child = this.children[i], end = pos + child.length;
  322. // Fast path: if the change only affects one child and the
  323. // child's size remains in the acceptable range, only update
  324. // that child
  325. if (from >= pos && to <= end) {
  326. let updated = child.replace(from - pos, to - pos, text);
  327. let totalLines = this.lines - child.lines + updated.lines;
  328. if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) &&
  329. updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) {
  330. let copy = this.children.slice();
  331. copy[i] = updated;
  332. return new TextNode(copy, this.length - (to - from) + text.length);
  333. }
  334. return super.replace(pos, end, updated);
  335. }
  336. pos = end + 1;
  337. }
  338. return super.replace(from, to, text);
  339. }
  340. sliceString(from, to = this.length, lineSep = "\n") {
  341. let result = "";
  342. for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
  343. let child = this.children[i], end = pos + child.length;
  344. if (pos > from && i)
  345. result += lineSep;
  346. if (from < end && to > pos)
  347. result += child.sliceString(from - pos, to - pos, lineSep);
  348. pos = end + 1;
  349. }
  350. return result;
  351. }
  352. flatten(target) {
  353. for (let child of this.children)
  354. child.flatten(target);
  355. }
  356. static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
  357. let lines = 0;
  358. for (let ch of children)
  359. lines += ch.lines;
  360. if (lines < 32 /* Branch */) {
  361. let flat = [];
  362. for (let ch of children)
  363. ch.flatten(flat);
  364. return new TextLeaf(flat, length);
  365. }
  366. let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
  367. let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
  368. function add(child) {
  369. let last;
  370. if (child.lines > maxChunk && child instanceof TextNode) {
  371. for (let node of child.children)
  372. add(node);
  373. }
  374. else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
  375. flush();
  376. chunked.push(child);
  377. }
  378. else if (child instanceof TextLeaf && currentLines &&
  379. (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
  380. child.lines + last.lines <= 32 /* Branch */) {
  381. currentLines += child.lines;
  382. currentLen += child.length + 1;
  383. currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
  384. }
  385. else {
  386. if (currentLines + child.lines > chunk)
  387. flush();
  388. currentLines += child.lines;
  389. currentLen += child.length + 1;
  390. currentChunk.push(child);
  391. }
  392. }
  393. function flush() {
  394. if (currentLines == 0)
  395. return;
  396. chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
  397. currentLen = -1;
  398. currentLines = currentChunk.length = 0;
  399. }
  400. for (let child of children)
  401. add(child);
  402. flush();
  403. return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
  404. }
  405. }
  406. Text.empty = new TextLeaf([""], 0);
  407. function textLength(text) {
  408. let length = -1;
  409. for (let line of text)
  410. length += line.length + 1;
  411. return length;
  412. }
  413. function appendText(text, target, from = 0, to = 1e9) {
  414. for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
  415. let line = text[i], end = pos + line.length;
  416. if (end >= from) {
  417. if (end > to)
  418. line = line.slice(0, to - pos);
  419. if (pos < from)
  420. line = line.slice(from - pos);
  421. if (first) {
  422. target[target.length - 1] += line;
  423. first = false;
  424. }
  425. else
  426. target.push(line);
  427. }
  428. pos = end + 1;
  429. }
  430. return target;
  431. }
  432. function sliceText(text, from, to) {
  433. return appendText(text, [""], from, to);
  434. }
  435. class RawTextCursor {
  436. constructor(text, dir = 1) {
  437. this.dir = dir;
  438. this.done = false;
  439. this.lineBreak = false;
  440. this.value = "";
  441. this.nodes = [text];
  442. this.offsets = [dir > 0 ? 0 : text instanceof TextLeaf ? text.text.length : text.children.length];
  443. }
  444. next(skip = 0) {
  445. for (;;) {
  446. let last = this.nodes.length - 1;
  447. if (last < 0) {
  448. this.done = true;
  449. this.value = "";
  450. this.lineBreak = false;
  451. return this;
  452. }
  453. let top = this.nodes[last], offset = this.offsets[last];
  454. let size = top instanceof TextLeaf ? top.text.length : top.children.length;
  455. if (offset == (this.dir > 0 ? size : 0)) {
  456. this.nodes.pop();
  457. this.offsets.pop();
  458. }
  459. else if (!this.lineBreak && offset != (this.dir > 0 ? 0 : size)) {
  460. // Internal offset with lineBreak == false means we have to
  461. // count the line break at this position
  462. this.lineBreak = true;
  463. if (skip == 0) {
  464. this.value = "\n";
  465. return this;
  466. }
  467. skip--;
  468. }
  469. else if (top instanceof TextLeaf) {
  470. // Move to the next string
  471. let next = top.text[offset - (this.dir < 0 ? 1 : 0)];
  472. this.offsets[last] = (offset += this.dir);
  473. this.lineBreak = false;
  474. if (next.length > Math.max(0, skip)) {
  475. this.value = skip == 0 ? next : this.dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
  476. return this;
  477. }
  478. skip -= next.length;
  479. }
  480. else {
  481. let next = top.children[this.dir > 0 ? offset : offset - 1];
  482. this.offsets[last] = offset + this.dir;
  483. this.lineBreak = false;
  484. if (skip > next.length) {
  485. skip -= next.length;
  486. }
  487. else {
  488. this.nodes.push(next);
  489. this.offsets.push(this.dir > 0 ? 0 : next instanceof TextLeaf ? next.text.length : next.children.length);
  490. }
  491. }
  492. }
  493. }
  494. }
  495. class PartialTextCursor {
  496. constructor(text, start, end) {
  497. this.value = "";
  498. this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
  499. if (start > end) {
  500. this.skip = text.length - start;
  501. this.limit = start - end;
  502. }
  503. else {
  504. this.skip = start;
  505. this.limit = end - start;
  506. }
  507. }
  508. next(skip = 0) {
  509. if (this.limit <= 0) {
  510. this.limit = -1;
  511. }
  512. else {
  513. let { value, lineBreak, done } = this.cursor.next(this.skip + skip);
  514. this.skip = 0;
  515. this.value = value;
  516. let len = lineBreak ? 1 : value.length;
  517. if (len > this.limit)
  518. this.value = this.cursor.dir > 0 ? value.slice(0, this.limit) : value.slice(len - this.limit);
  519. if (done || this.value.length == 0)
  520. this.limit = -1;
  521. else
  522. this.limit -= this.value.length;
  523. }
  524. return this;
  525. }
  526. get lineBreak() { return this.cursor.lineBreak; }
  527. get done() { return this.limit < 0; }
  528. }
  529. /// This type describes a line in the document. It is created
  530. /// on-demand when lines are [queried](#text.Text.lineAt).
  531. class Line {
  532. /// @internal
  533. constructor(
  534. /// The position of the start of the line.
  535. from,
  536. /// The position at the end of the line (_before_ the line break,
  537. /// or at the end of document for the last line).
  538. to,
  539. /// This line's line number (1-based).
  540. number,
  541. /// The line's content.
  542. text) {
  543. this.from = from;
  544. this.to = to;
  545. this.number = number;
  546. this.text = text;
  547. }
  548. /// The length of the line (not including any line break after it).
  549. get length() { return this.to - this.from; }
  550. }
  551. const DefaultSplit = /\r\n?|\n/;
  552. /// Distinguishes different ways in which positions can be mapped.
  553. var MapMode;
  554. (function (MapMode) {
  555. /// Map a position to a valid new position, even when its context
  556. /// was deleted.
  557. MapMode[MapMode["Simple"] = 0] = "Simple";
  558. /// Return null if deletion happens across the position.
  559. MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
  560. /// Return null if the character _before_ the position is deleted.
  561. MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
  562. /// Return null if the character _after_ the position is deleted.
  563. MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
  564. })(MapMode || (MapMode = {}));
  565. /// A change description is a variant of [change set](#state.ChangeSet)
  566. /// that doesn't store the inserted text. As such, it can't be
  567. /// applied, but is cheaper to store and manipulate.
  568. class ChangeDesc {
  569. // Sections are encoded as pairs of integers. The first is the
  570. // length in the current document, and the second is -1 for
  571. // unaffected sections, and the length of the replacement content
  572. // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
  573. // 0), and a replacement two positive numbers.
  574. /// @internal
  575. constructor(
  576. /// @internal
  577. sections) {
  578. this.sections = sections;
  579. }
  580. /// The length of the document before the change.
  581. get length() {
  582. let result = 0;
  583. for (let i = 0; i < this.sections.length; i += 2)
  584. result += this.sections[i];
  585. return result;
  586. }
  587. /// The length of the document after the change.
  588. get newLength() {
  589. let result = 0;
  590. for (let i = 0; i < this.sections.length; i += 2) {
  591. let ins = this.sections[i + 1];
  592. result += ins < 0 ? this.sections[i] : ins;
  593. }
  594. return result;
  595. }
  596. /// False when there are actual changes in this set.
  597. get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
  598. /// Iterate over the unchanged parts left by these changes.
  599. iterGaps(f) {
  600. for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
  601. let len = this.sections[i++], ins = this.sections[i++];
  602. if (ins < 0) {
  603. f(posA, posB, len);
  604. posB += len;
  605. }
  606. else {
  607. posB += ins;
  608. }
  609. posA += len;
  610. }
  611. }
  612. /// Iterate over the ranges changed by these changes. (See
  613. /// [`ChangeSet.iterChanges`](#state.ChangeSet.iterChanges) for a
  614. /// variant that also provides you with the inserted text.)
  615. ///
  616. /// When `individual` is true, adjacent changes (which are kept
  617. /// separate for [position mapping](#state.ChangeDesc.mapPos)) are
  618. /// reported separately.
  619. iterChangedRanges(f, individual = false) {
  620. iterChanges(this, f, individual);
  621. }
  622. /// Get a description of the inverted form of these changes.
  623. get invertedDesc() {
  624. let sections = [];
  625. for (let i = 0; i < this.sections.length;) {
  626. let len = this.sections[i++], ins = this.sections[i++];
  627. if (ins < 0)
  628. sections.push(len, ins);
  629. else
  630. sections.push(ins, len);
  631. }
  632. return new ChangeDesc(sections);
  633. }
  634. /// Compute the combined effect of applying another set of changes
  635. /// after this one. The length of the document after this set should
  636. /// match the length before `other`.
  637. composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
  638. /// Map this description, which should start with the same document
  639. /// as `other`, over another set of changes, so that it can be
  640. /// applied after it. When `before` is true, map as if the changes
  641. /// in `other` happened before the ones in `this`.
  642. mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
  643. mapPos(pos, assoc = -1, mode = MapMode.Simple) {
  644. let posA = 0, posB = 0;
  645. for (let i = 0; i < this.sections.length;) {
  646. let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
  647. if (ins < 0) {
  648. if (endA > pos)
  649. return posB + (pos - posA);
  650. posB += len;
  651. }
  652. else {
  653. if (mode != MapMode.Simple && endA >= pos &&
  654. (mode == MapMode.TrackDel && posA < pos && endA > pos ||
  655. mode == MapMode.TrackBefore && posA < pos ||
  656. mode == MapMode.TrackAfter && endA > pos))
  657. return null;
  658. if (endA > pos || endA == pos && assoc < 0 && !len)
  659. return pos == posA || assoc < 0 ? posB : posB + ins;
  660. posB += ins;
  661. }
  662. posA = endA;
  663. }
  664. if (pos > posA)
  665. throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
  666. return posB;
  667. }
  668. /// Check whether these changes touch a given range. When one of the
  669. /// changes entirely covers the range, the string `"cover"` is
  670. /// returned.
  671. touchesRange(from, to = from) {
  672. for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
  673. let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
  674. if (ins >= 0 && pos <= to && end >= from)
  675. return pos < from && end > to ? "cover" : true;
  676. pos = end;
  677. }
  678. return false;
  679. }
  680. /// @internal
  681. toString() {
  682. let result = "";
  683. for (let i = 0; i < this.sections.length;) {
  684. let len = this.sections[i++], ins = this.sections[i++];
  685. result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
  686. }
  687. return result;
  688. }
  689. }
  690. /// A change set represents a group of modifications to a document. It
  691. /// stores the document length, and can only be applied to documents
  692. /// with exactly that length.
  693. class ChangeSet extends ChangeDesc {
  694. /// @internal
  695. constructor(sections,
  696. /// @internal
  697. inserted) {
  698. super(sections);
  699. this.inserted = inserted;
  700. }
  701. /// Apply the changes to a document, returning the modified
  702. /// document.
  703. apply(doc) {
  704. if (this.length != doc.length)
  705. throw new RangeError("Applying change set to a document with the wrong length");
  706. iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
  707. return doc;
  708. }
  709. mapDesc(other, before = false) { return mapSet(this, other, before, true); }
  710. /// Given the document as it existed _before_ the changes, return a
  711. /// change set that represents the inverse of this set, which could
  712. /// be used to go from the document created by the changes back to
  713. /// the document as it existed before the changes.
  714. invert(doc) {
  715. let sections = this.sections.slice(), inserted = [];
  716. for (let i = 0, pos = 0; i < sections.length; i += 2) {
  717. let len = sections[i], ins = sections[i + 1];
  718. if (ins >= 0) {
  719. sections[i] = ins;
  720. sections[i + 1] = len;
  721. let index = i >> 1;
  722. while (inserted.length < index)
  723. inserted.push(Text.empty);
  724. inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
  725. }
  726. pos += len;
  727. }
  728. return new ChangeSet(sections, inserted);
  729. }
  730. /// Combine two subsequent change sets into a single set. `other`
  731. /// must start in the document produced by `this`. If `this` goes
  732. /// `docA` → `docB` and `other` represents `docB` → `docC`, the
  733. /// returned value will represent the change `docA` → `docC`.
  734. compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
  735. /// Given another change set starting in the same document, maps this
  736. /// change set over the other, producing a new change set that can be
  737. /// applied to the document produced by applying `other`. When
  738. /// `before` is `true`, order changes as if `this` comes before
  739. /// `other`, otherwise (the default) treat `other` as coming first.
  740. ///
  741. /// Given two changes `A` and `B`, `A.compose(B.map(A))` and
  742. /// `B.compose(A.map(B, true))` will produce the same document. This
  743. /// provides a basic form of [operational
  744. /// transformation](https://en.wikipedia.org/wiki/Operational_transformation),
  745. /// and can be used for collaborative editing.
  746. map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
  747. /// Iterate over the changed ranges in the document, calling `f` for
  748. /// each.
  749. ///
  750. /// When `individual` is true, adjacent changes are reported
  751. /// separately.
  752. iterChanges(f, individual = false) {
  753. iterChanges(this, f, individual);
  754. }
  755. /// Get a [change description](#state.ChangeDesc) for this change
  756. /// set.
  757. get desc() { return new ChangeDesc(this.sections); }
  758. /// @internal
  759. filter(ranges) {
  760. let resultSections = [], resultInserted = [], filteredSections = [];
  761. let iter = new SectionIter(this);
  762. done: for (let i = 0, pos = 0;;) {
  763. let next = i == ranges.length ? 1e9 : ranges[i++];
  764. while (pos < next || pos == next && iter.len == 0) {
  765. if (iter.done)
  766. break done;
  767. let len = Math.min(iter.len, next - pos);
  768. addSection(filteredSections, len, -1);
  769. let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
  770. addSection(resultSections, len, ins);
  771. if (ins > 0)
  772. addInsert(resultInserted, resultSections, iter.text);
  773. iter.forward(len);
  774. pos += len;
  775. }
  776. let end = ranges[i++];
  777. while (pos < end) {
  778. if (iter.done)
  779. break done;
  780. let len = Math.min(iter.len, end - pos);
  781. addSection(resultSections, len, -1);
  782. addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
  783. iter.forward(len);
  784. pos += len;
  785. }
  786. }
  787. return { changes: new ChangeSet(resultSections, resultInserted),
  788. filtered: new ChangeDesc(filteredSections) };
  789. }
  790. /// Serialize this change set to a JSON-representable value.
  791. toJSON() {
  792. let parts = [];
  793. for (let i = 0; i < this.sections.length; i += 2) {
  794. let len = this.sections[i], ins = this.sections[i + 1];
  795. if (ins < 0)
  796. parts.push(len);
  797. else if (ins == 0)
  798. parts.push([len]);
  799. else
  800. parts.push([len].concat(this.inserted[i >> 1].toJSON()));
  801. }
  802. return parts;
  803. }
  804. /// Create a change set for the given changes, for a document of the
  805. /// given length, using `lineSep` as line separator.
  806. static of(changes, length, lineSep) {
  807. let sections = [], inserted = [], pos = 0;
  808. let total = null;
  809. function flush(force = false) {
  810. if (!force && !sections.length)
  811. return;
  812. if (pos < length)
  813. addSection(sections, length - pos, -1);
  814. let set = new ChangeSet(sections, inserted);
  815. total = total ? total.compose(set.map(total)) : set;
  816. sections = [];
  817. inserted = [];
  818. pos = 0;
  819. }
  820. function process(spec) {
  821. if (Array.isArray(spec)) {
  822. for (let sub of spec)
  823. process(sub);
  824. }
  825. else if (spec instanceof ChangeSet) {
  826. if (spec.length != length)
  827. throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
  828. flush();
  829. total = total ? total.compose(spec.map(total)) : spec;
  830. }
  831. else {
  832. let { from, to = from, insert } = spec;
  833. if (from > to || from < 0 || to > length)
  834. throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
  835. let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
  836. let insLen = insText.length;
  837. if (from == to && insLen == 0)
  838. return;
  839. if (from < pos)
  840. flush();
  841. if (from > pos)
  842. addSection(sections, from - pos, -1);
  843. addSection(sections, to - from, insLen);
  844. addInsert(inserted, sections, insText);
  845. pos = to;
  846. }
  847. }
  848. process(changes);
  849. flush(!total);
  850. return total;
  851. }
  852. /// Create an empty changeset of the given length.
  853. static empty(length) {
  854. return new ChangeSet(length ? [length, -1] : [], []);
  855. }
  856. /// Create a changeset from its JSON representation (as produced by
  857. /// [`toJSON`](#state.ChangeSet.toJSON).
  858. static fromJSON(json) {
  859. if (!Array.isArray(json))
  860. throw new RangeError("Invalid JSON representation of ChangeSet");
  861. let sections = [], inserted = [];
  862. for (let i = 0; i < json.length; i++) {
  863. let part = json[i];
  864. if (typeof part == "number") {
  865. sections.push(part, -1);
  866. }
  867. else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
  868. throw new RangeError("Invalid JSON representation of ChangeSet");
  869. }
  870. else if (part.length == 1) {
  871. sections.push(part[0], 0);
  872. }
  873. else {
  874. while (inserted.length < i)
  875. inserted.push(Text.empty);
  876. inserted[i] = Text.of(part.slice(1));
  877. sections.push(part[0], inserted[i].length);
  878. }
  879. }
  880. return new ChangeSet(sections, inserted);
  881. }
  882. }
  883. function addSection(sections, len, ins, forceJoin = false) {
  884. if (len == 0 && ins <= 0)
  885. return;
  886. let last = sections.length - 2;
  887. if (last >= 0 && ins <= 0 && ins == sections[last + 1])
  888. sections[last] += len;
  889. else if (len == 0 && sections[last] == 0)
  890. sections[last + 1] += ins;
  891. else if (forceJoin) {
  892. sections[last] += len;
  893. sections[last + 1] += ins;
  894. }
  895. else
  896. sections.push(len, ins);
  897. }
  898. function addInsert(values, sections, value) {
  899. if (value.length == 0)
  900. return;
  901. let index = (sections.length - 2) >> 1;
  902. if (index < values.length) {
  903. values[values.length - 1] = values[values.length - 1].append(value);
  904. }
  905. else {
  906. while (values.length < index)
  907. values.push(Text.empty);
  908. values.push(value);
  909. }
  910. }
  911. function iterChanges(desc, f, individual) {
  912. let inserted = desc.inserted;
  913. for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
  914. let len = desc.sections[i++], ins = desc.sections[i++];
  915. if (ins < 0) {
  916. posA += len;
  917. posB += len;
  918. }
  919. else {
  920. let endA = posA, endB = posB, text = Text.empty;
  921. for (;;) {
  922. endA += len;
  923. endB += ins;
  924. if (ins && inserted)
  925. text = text.append(inserted[(i - 2) >> 1]);
  926. if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
  927. break;
  928. len = desc.sections[i++];
  929. ins = desc.sections[i++];
  930. }
  931. f(posA, endA, posB, endB, text);
  932. posA = endA;
  933. posB = endB;
  934. }
  935. }
  936. }
  937. function mapSet(setA, setB, before, mkSet = false) {
  938. let sections = [], insert = mkSet ? [] : null;
  939. let a = new SectionIter(setA), b = new SectionIter(setB);
  940. for (let posA = 0, posB = 0;;) {
  941. if (a.ins == -1) {
  942. posA += a.len;
  943. a.next();
  944. }
  945. else if (b.ins == -1 && posB < posA) {
  946. let skip = Math.min(b.len, posA - posB);
  947. b.forward(skip);
  948. addSection(sections, skip, -1);
  949. posB += skip;
  950. }
  951. else if (b.ins >= 0 && (a.done || posB < posA || posB == posA && (b.len < a.len || b.len == a.len && !before))) {
  952. addSection(sections, b.ins, -1);
  953. while (posA > posB && !a.done && posA + a.len < posB + b.len) {
  954. posA += a.len;
  955. a.next();
  956. }
  957. posB += b.len;
  958. b.next();
  959. }
  960. else if (a.ins >= 0) {
  961. let len = 0, end = posA + a.len;
  962. for (;;) {
  963. if (b.ins >= 0 && posB > posA && posB + b.len < end) {
  964. len += b.ins;
  965. posB += b.len;
  966. b.next();
  967. }
  968. else if (b.ins == -1 && posB < end) {
  969. let skip = Math.min(b.len, end - posB);
  970. len += skip;
  971. b.forward(skip);
  972. posB += skip;
  973. }
  974. else {
  975. break;
  976. }
  977. }
  978. addSection(sections, len, a.ins);
  979. if (insert)
  980. addInsert(insert, sections, a.text);
  981. posA = end;
  982. a.next();
  983. }
  984. else if (a.done && b.done) {
  985. return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections);
  986. }
  987. else {
  988. throw new Error("Mismatched change set lengths");
  989. }
  990. }
  991. }
  992. function composeSets(setA, setB, mkSet = false) {
  993. let sections = [];
  994. let insert = mkSet ? [] : null;
  995. let a = new SectionIter(setA), b = new SectionIter(setB);
  996. for (let open = false;;) {
  997. if (a.done && b.done) {
  998. return insert ? new ChangeSet(sections, insert) : new ChangeDesc(sections);
  999. }
  1000. else if (a.ins == 0) { // Deletion in A
  1001. addSection(sections, a.len, 0, open);
  1002. a.next();
  1003. }
  1004. else if (b.len == 0 && !b.done) { // Insertion in B
  1005. addSection(sections, 0, b.ins, open);
  1006. if (insert)
  1007. addInsert(insert, sections, b.text);
  1008. b.next();
  1009. }
  1010. else if (a.done || b.done) {
  1011. throw new Error("Mismatched change set lengths");
  1012. }
  1013. else {
  1014. let len = Math.min(a.len2, b.len), sectionLen = sections.length;
  1015. if (a.ins == -1) {
  1016. let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
  1017. addSection(sections, len, insB, open);
  1018. if (insert && insB)
  1019. addInsert(insert, sections, b.text);
  1020. }
  1021. else if (b.ins == -1) {
  1022. addSection(sections, a.off ? 0 : a.len, len, open);
  1023. if (insert)
  1024. addInsert(insert, sections, a.textBit(len));
  1025. }
  1026. else {
  1027. addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
  1028. if (insert && !b.off)
  1029. addInsert(insert, sections, b.text);
  1030. }
  1031. open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
  1032. a.forward2(len);
  1033. b.forward(len);
  1034. }
  1035. }
  1036. }
  1037. class SectionIter {
  1038. constructor(set) {
  1039. this.set = set;
  1040. this.i = 0;
  1041. this.next();
  1042. }
  1043. next() {
  1044. let { sections } = this.set;
  1045. if (this.i < sections.length) {
  1046. this.len = sections[this.i++];
  1047. this.ins = sections[this.i++];
  1048. }
  1049. else {
  1050. this.len = 0;
  1051. this.ins = -2;
  1052. }
  1053. this.off = 0;
  1054. }
  1055. get done() { return this.ins == -2; }
  1056. get len2() { return this.ins < 0 ? this.len : this.ins; }
  1057. get text() {
  1058. let { inserted } = this.set, index = (this.i - 2) >> 1;
  1059. return index >= inserted.length ? Text.empty : inserted[index];
  1060. }
  1061. textBit(len) {
  1062. let { inserted } = this.set, index = (this.i - 2) >> 1;
  1063. return index >= inserted.length && !len ? Text.empty
  1064. : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
  1065. }
  1066. forward(len) {
  1067. if (len == this.len)
  1068. this.next();
  1069. else {
  1070. this.len -= len;
  1071. this.off += len;
  1072. }
  1073. }
  1074. forward2(len) {
  1075. if (this.ins == -1)
  1076. this.forward(len);
  1077. else if (len == this.ins)
  1078. this.next();
  1079. else {
  1080. this.ins -= len;
  1081. this.off += len;
  1082. }
  1083. }
  1084. }
  1085. /// A single selection range. When
  1086. /// [`allowMultipleSelections`](#state.EditorState^allowMultipleSelections)
  1087. /// is enabled, a [selection](#state.EditorSelection) may hold
  1088. /// multiple ranges. By default, selections hold exactly one range.
  1089. class SelectionRange {
  1090. /// @internal
  1091. constructor(
  1092. /// The lower boundary of the range.
  1093. from,
  1094. /// The upper boundary of the range.
  1095. to, flags) {
  1096. this.from = from;
  1097. this.to = to;
  1098. this.flags = flags;
  1099. }
  1100. /// The anchor of the range—the side that doesn't move when you
  1101. /// extend it.
  1102. get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; }
  1103. /// The head of the range, which is moved when the range is
  1104. /// [extended](#state.SelectionRange.extend).
  1105. get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; }
  1106. /// True when `anchor` and `head` are at the same position.
  1107. get empty() { return this.from == this.to; }
  1108. /// If this is a cursor that is explicitly associated with the
  1109. /// character on one of its sides, this returns the side. -1 means
  1110. /// the character before its position, 1 the character after, and 0
  1111. /// means no association.
  1112. get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; }
  1113. /// The bidirectional text level associated with this cursor, if
  1114. /// any.
  1115. get bidiLevel() {
  1116. let level = this.flags & 3 /* BidiLevelMask */;
  1117. return level == 3 ? null : level;
  1118. }
  1119. /// The goal column (stored vertical offset) associated with a
  1120. /// cursor. This is used to preserve the vertical position when
  1121. /// [moving](#view.EditorView.moveVertically) across
  1122. /// lines of different length.
  1123. get goalColumn() {
  1124. let value = this.flags >> 5 /* GoalColumnOffset */;
  1125. return value == 33554431 /* NoGoalColumn */ ? undefined : value;
  1126. }
  1127. /// Map this range through a change, producing a valid range in the
  1128. /// updated document.
  1129. map(change) {
  1130. let from = change.mapPos(this.from), to = change.mapPos(this.to);
  1131. return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
  1132. }
  1133. /// Extend this range to cover at least `from` to `to`.
  1134. extend(from, to = from) {
  1135. if (from <= this.anchor && to >= this.anchor)
  1136. return EditorSelection.range(from, to);
  1137. let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
  1138. return EditorSelection.range(this.anchor, head);
  1139. }
  1140. /// Compare this range to another range.
  1141. eq(other) {
  1142. return this.anchor == other.anchor && this.head == other.head;
  1143. }
  1144. /// Return a JSON-serializable object representing the range.
  1145. toJSON() { return { anchor: this.anchor, head: this.head }; }
  1146. /// Convert a JSON representation of a range to a `SelectionRange`
  1147. /// instance.
  1148. static fromJSON(json) {
  1149. if (!json || typeof json.anchor != "number" || typeof json.head != "number")
  1150. throw new RangeError("Invalid JSON representation for SelectionRange");
  1151. return EditorSelection.range(json.anchor, json.head);
  1152. }
  1153. }
  1154. /// An editor selection holds one or more selection ranges.
  1155. class EditorSelection {
  1156. /// @internal
  1157. constructor(
  1158. /// The ranges in the selection, sorted by position. Ranges cannot
  1159. /// overlap (but they may touch, if they aren't empty).
  1160. ranges,
  1161. /// The index of the _main_ range in the selection (which is
  1162. /// usually the range that was added last).
  1163. mainIndex = 0) {
  1164. this.ranges = ranges;
  1165. this.mainIndex = mainIndex;
  1166. }
  1167. /// Map a selection through a change. Used to adjust the selection
  1168. /// position for changes.
  1169. map(change) {
  1170. if (change.empty)
  1171. return this;
  1172. return EditorSelection.create(this.ranges.map(r => r.map(change)), this.mainIndex);
  1173. }
  1174. /// Compare this selection to another selection.
  1175. eq(other) {
  1176. if (this.ranges.length != other.ranges.length ||
  1177. this.mainIndex != other.mainIndex)
  1178. return false;
  1179. for (let i = 0; i < this.ranges.length; i++)
  1180. if (!this.ranges[i].eq(other.ranges[i]))
  1181. return false;
  1182. return true;
  1183. }
  1184. /// Get the primary selection range. Usually, you should make sure
  1185. /// your code applies to _all_ ranges, by using methods like
  1186. /// [`changeByRange`](#state.EditorState.changeByRange).
  1187. get main() { return this.ranges[this.mainIndex]; }
  1188. /// Make sure the selection only has one range. Returns a selection
  1189. /// holding only the main range from this selection.
  1190. asSingle() {
  1191. return this.ranges.length == 1 ? this : new EditorSelection([this.main]);
  1192. }
  1193. /// Extend this selection with an extra range.
  1194. addRange(range, main = true) {
  1195. return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
  1196. }
  1197. /// Replace a given range with another range, and then normalize the
  1198. /// selection to merge and sort ranges if necessary.
  1199. replaceRange(range, which = this.mainIndex) {
  1200. let ranges = this.ranges.slice();
  1201. ranges[which] = range;
  1202. return EditorSelection.create(ranges, this.mainIndex);
  1203. }
  1204. /// Convert this selection to an object that can be serialized to
  1205. /// JSON.
  1206. toJSON() {
  1207. return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
  1208. }
  1209. /// Create a selection from a JSON representation.
  1210. static fromJSON(json) {
  1211. if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
  1212. throw new RangeError("Invalid JSON representation for EditorSelection");
  1213. return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
  1214. }
  1215. /// Create a selection holding a single range.
  1216. static single(anchor, head = anchor) {
  1217. return new EditorSelection([EditorSelection.range(anchor, head)], 0);
  1218. }
  1219. /// Sort and merge the given set of ranges, creating a valid
  1220. /// selection.
  1221. static create(ranges, mainIndex = 0) {
  1222. if (ranges.length == 0)
  1223. throw new RangeError("A selection needs at least one range");
  1224. for (let pos = 0, i = 0; i < ranges.length; i++) {
  1225. let range = ranges[i];
  1226. if (range.empty ? range.from <= pos : range.from < pos)
  1227. return normalized(ranges.slice(), mainIndex);
  1228. pos = range.to;
  1229. }
  1230. return new EditorSelection(ranges, mainIndex);
  1231. }
  1232. /// Create a cursor selection range at the given position. You can
  1233. /// safely ignore the optional arguments in most situations.
  1234. static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
  1235. return new SelectionRange(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) |
  1236. (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) |
  1237. ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */));
  1238. }
  1239. /// Create a selection range.
  1240. static range(anchor, head, goalColumn) {
  1241. let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */;
  1242. return head < anchor ? new SelectionRange(head, anchor, 16 /* Inverted */ | goal) : new SelectionRange(anchor, head, goal);
  1243. }
  1244. }
  1245. function normalized(ranges, mainIndex = 0) {
  1246. let main = ranges[mainIndex];
  1247. ranges.sort((a, b) => a.from - b.from);
  1248. mainIndex = ranges.indexOf(main);
  1249. for (let i = 1; i < ranges.length; i++) {
  1250. let range = ranges[i], prev = ranges[i - 1];
  1251. if (range.empty ? range.from <= prev.to : range.from < prev.to) {
  1252. let from = prev.from, to = Math.max(range.to, prev.to);
  1253. if (i <= mainIndex)
  1254. mainIndex--;
  1255. ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
  1256. }
  1257. }
  1258. return new EditorSelection(ranges, mainIndex);
  1259. }
  1260. function checkSelection(selection, docLength) {
  1261. for (let range of selection.ranges)
  1262. if (range.to > docLength)
  1263. throw new RangeError("Selection points outside of document");
  1264. }
  1265. let nextID = 0;
  1266. /// A facet is a labeled value that is associated with an editor
  1267. /// state. It takes inputs from any number of extensions, and combines
  1268. /// those into a single output value.
  1269. ///
  1270. /// Examples of facets are the [theme](#view.EditorView^theme) styles
  1271. /// associated with an editor or the [tab
  1272. /// size](#state.EditorState^tabSize) (which is reduced to a single
  1273. /// value, using the input with the hightest precedence).
  1274. class Facet {
  1275. constructor(
  1276. /// @internal
  1277. combine,
  1278. /// @internal
  1279. compareInput,
  1280. /// @internal
  1281. compare, isStatic,
  1282. /// @internal
  1283. extensions) {
  1284. this.combine = combine;
  1285. this.compareInput = compareInput;
  1286. this.compare = compare;
  1287. this.isStatic = isStatic;
  1288. this.extensions = extensions;
  1289. /// @internal
  1290. this.id = nextID++;
  1291. this.default = combine([]);
  1292. }
  1293. /// Define a new facet.
  1294. static define(config = {}) {
  1295. return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);
  1296. }
  1297. /// Returns an extension that adds the given value for this facet.
  1298. of(value) {
  1299. return new FacetProvider([], this, 0 /* Static */, value);
  1300. }
  1301. /// Create an extension that computes a value for the facet from a
  1302. /// state. You must take care to declare the parts of the state that
  1303. /// this value depends on, since your function is only called again
  1304. /// for a new state when one of those parts changed.
  1305. ///
  1306. /// In most cases, you'll want to use the
  1307. /// [`provide`](#state.StateField^define^config.provide) option when
  1308. /// defining a field instead.
  1309. compute(deps, get) {
  1310. if (this.isStatic)
  1311. throw new Error("Can't compute a static facet");
  1312. return new FacetProvider(deps, this, 1 /* Single */, get);
  1313. }
  1314. /// Create an extension that computes zero or more values for this
  1315. /// facet from a state.
  1316. computeN(deps, get) {
  1317. if (this.isStatic)
  1318. throw new Error("Can't compute a static facet");
  1319. return new FacetProvider(deps, this, 2 /* Multi */, get);
  1320. }
  1321. from(field, get) {
  1322. if (!get)
  1323. get = x => x;
  1324. return this.compute([field], state => get(state.field(field)));
  1325. }
  1326. }
  1327. function sameArray(a, b) {
  1328. return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
  1329. }
  1330. class FacetProvider {
  1331. constructor(dependencies, facet, type, value) {
  1332. this.dependencies = dependencies;
  1333. this.facet = facet;
  1334. this.type = type;
  1335. this.value = value;
  1336. this.id = nextID++;
  1337. }
  1338. dynamicSlot(addresses) {
  1339. var _a;
  1340. let getter = this.value;
  1341. let compare = this.facet.compareInput;
  1342. let idx = addresses[this.id] >> 1, multi = this.type == 2 /* Multi */;
  1343. let depDoc = false, depSel = false, depAddrs = [];
  1344. for (let dep of this.dependencies) {
  1345. if (dep == "doc")
  1346. depDoc = true;
  1347. else if (dep == "selection")
  1348. depSel = true;
  1349. else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
  1350. depAddrs.push(addresses[dep.id]);
  1351. }
  1352. return (state, tr) => {
  1353. if (!tr || tr.reconfigure) {
  1354. state.values[idx] = getter(state);
  1355. return 1 /* Changed */;
  1356. }
  1357. else {
  1358. let depChanged = (depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) ||
  1359. depAddrs.some(addr => (ensureAddr(state, addr) & 1 /* Changed */) > 0);
  1360. if (!depChanged)
  1361. return 0;
  1362. let newVal = getter(state), oldVal = tr.startState.values[idx];
  1363. if (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))
  1364. return 0;
  1365. state.values[idx] = newVal;
  1366. return 1 /* Changed */;
  1367. }
  1368. };
  1369. }
  1370. }
  1371. function compareArray(a, b, compare) {
  1372. if (a.length != b.length)
  1373. return false;
  1374. for (let i = 0; i < a.length; i++)
  1375. if (!compare(a[i], b[i]))
  1376. return false;
  1377. return true;
  1378. }
  1379. function dynamicFacetSlot(addresses, facet, providers) {
  1380. let providerAddrs = providers.map(p => addresses[p.id]);
  1381. let providerTypes = providers.map(p => p.type);
  1382. let dynamic = providerAddrs.filter(p => !(p & 1));
  1383. let idx = addresses[facet.id] >> 1;
  1384. return (state, tr) => {
  1385. let oldAddr = !tr ? null : tr.reconfigure ? tr.startState.config.address[facet.id] : idx << 1;
  1386. let changed = oldAddr == null;
  1387. for (let dynAddr of dynamic) {
  1388. if (ensureAddr(state, dynAddr) & 1 /* Changed */)
  1389. changed = true;
  1390. }
  1391. if (!changed)
  1392. return 0;
  1393. let values = [];
  1394. for (let i = 0; i < providerAddrs.length; i++) {
  1395. let value = getAddr(state, providerAddrs[i]);
  1396. if (providerTypes[i] == 2 /* Multi */)
  1397. for (let val of value)
  1398. values.push(val);
  1399. else
  1400. values.push(value);
  1401. }
  1402. let newVal = facet.combine(values);
  1403. if (oldAddr != null && facet.compare(newVal, getAddr(tr.startState, oldAddr)))
  1404. return 0;
  1405. state.values[idx] = newVal;
  1406. return 1 /* Changed */;
  1407. };
  1408. }
  1409. function maybeIndex(state, id) {
  1410. let found = state.config.address[id];
  1411. return found == null ? null : found >> 1;
  1412. }
  1413. const initField = Facet.define({ static: true });
  1414. /// Fields can store additional information in an editor state, and
  1415. /// keep it in sync with the rest of the state.
  1416. class StateField {
  1417. constructor(
  1418. /// @internal
  1419. id, createF, updateF, compareF,
  1420. /// @internal
  1421. spec) {
  1422. this.id = id;
  1423. this.createF = createF;
  1424. this.updateF = updateF;
  1425. this.compareF = compareF;
  1426. this.spec = spec;
  1427. /// @internal
  1428. this.provides = undefined;
  1429. }
  1430. /// Define a state field.
  1431. static define(config) {
  1432. let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
  1433. if (config.provide)
  1434. field.provides = config.provide(field);
  1435. return field;
  1436. }
  1437. create(state) {
  1438. let init = state.facet(initField).find(i => i.field == this);
  1439. return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
  1440. }
  1441. /// @internal
  1442. slot(addresses) {
  1443. let idx = addresses[this.id] >> 1;
  1444. return (state, tr) => {
  1445. if (!tr) {
  1446. state.values[idx] = this.create(state);
  1447. return 1 /* Changed */;
  1448. }
  1449. let oldVal, changed = 0;
  1450. if (tr.reconfigure) {
  1451. let oldIdx = maybeIndex(tr.startState, this.id);
  1452. oldVal = oldIdx == null ? this.create(tr.startState) : tr.startState.values[oldIdx];
  1453. changed = 1 /* Changed */;
  1454. }
  1455. else {
  1456. oldVal = tr.startState.values[idx];
  1457. }
  1458. let value = this.updateF(oldVal, tr);
  1459. if (!changed && !this.compareF(oldVal, value))
  1460. changed = 1 /* Changed */;
  1461. if (changed)
  1462. state.values[idx] = value;
  1463. return changed;
  1464. };
  1465. }
  1466. /// Returns an extension that enables this field and overrides the
  1467. /// way it is initialized. Can be useful when you need to provide a
  1468. /// non-default starting value for the field.
  1469. init(create) {
  1470. return [this, initField.of({ field: this, create })];
  1471. }
  1472. }
  1473. const Prec_ = { fallback: 3, default: 2, extend: 1, override: 0 };
  1474. function prec(value) {
  1475. return (ext) => new PrecExtension(ext, value);
  1476. }
  1477. /// By default extensions are registered in the order they are found
  1478. /// in the flattened form of nested array that was provided.
  1479. /// Individual extension values can be assigned a precedence to
  1480. /// override this. Extensions that do not have a precedence set get
  1481. /// the precedence of the nearest parent with a precedence, or
  1482. /// [`default`](#state.Prec.default) if there is no such parent. The
  1483. /// final ordering of extensions is determined by first sorting by
  1484. /// precedence and then by order within each precedence.
  1485. const Prec = {
  1486. /// A precedence below the default precedence, which will cause
  1487. /// default-precedence extensions to override it even if they are
  1488. /// specified later in the extension ordering.
  1489. fallback: prec(Prec_.fallback),
  1490. /// The regular default precedence.
  1491. default: prec(Prec_.default),
  1492. /// A higher-than-default precedence.
  1493. extend: prec(Prec_.extend),
  1494. /// Precedence above the `default` and `extend` precedences.
  1495. override: prec(Prec_.override)
  1496. };
  1497. class PrecExtension {
  1498. constructor(inner, prec) {
  1499. this.inner = inner;
  1500. this.prec = prec;
  1501. }
  1502. }
  1503. class TaggedExtension {
  1504. constructor(tag, inner) {
  1505. this.tag = tag;
  1506. this.inner = inner;
  1507. }
  1508. }
  1509. /// Tagged extensions can be used to make a configuration dynamic.
  1510. /// Tagging an extension allows you to later
  1511. /// [replace](#state.TransactionSpec.reconfigure) it with
  1512. /// another extension. A given tag may only occur once within a given
  1513. /// configuration.
  1514. function tagExtension(tag, extension) {
  1515. return new TaggedExtension(tag, extension);
  1516. }
  1517. class Configuration {
  1518. constructor(source, replacements, dynamicSlots, address, staticValues) {
  1519. this.source = source;
  1520. this.replacements = replacements;
  1521. this.dynamicSlots = dynamicSlots;
  1522. this.address = address;
  1523. this.staticValues = staticValues;
  1524. this.statusTemplate = [];
  1525. while (this.statusTemplate.length < dynamicSlots.length)
  1526. this.statusTemplate.push(0 /* Uninitialized */);
  1527. }
  1528. staticFacet(facet) {
  1529. let addr = this.address[facet.id];
  1530. return addr == null ? facet.default : this.staticValues[addr >> 1];
  1531. }
  1532. static resolve(extension, replacements = Object.create(null), oldState) {
  1533. let fields = [];
  1534. let facets = Object.create(null);
  1535. for (let ext of flatten(extension, replacements)) {
  1536. if (ext instanceof StateField)
  1537. fields.push(ext);
  1538. else
  1539. (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
  1540. }
  1541. let address = Object.create(null);
  1542. let staticValues = [];
  1543. let dynamicSlots = [];
  1544. for (let field of fields) {
  1545. address[field.id] = dynamicSlots.length << 1;
  1546. dynamicSlots.push(a => field.slot(a));
  1547. }
  1548. for (let id in facets) {
  1549. let providers = facets[id], facet = providers[0].facet;
  1550. if (providers.every(p => p.type == 0 /* Static */)) {
  1551. address[facet.id] = (staticValues.length << 1) | 1;
  1552. let value = facet.combine(providers.map(p => p.value));
  1553. let oldAddr = oldState ? oldState.config.address[facet.id] : null;
  1554. if (oldAddr != null) {
  1555. let oldVal = getAddr(oldState, oldAddr);
  1556. if (facet.compare(value, oldVal))
  1557. value = oldVal;
  1558. }
  1559. staticValues.push(value);
  1560. }
  1561. else {
  1562. for (let p of providers) {
  1563. if (p.type == 0 /* Static */) {
  1564. address[p.id] = (staticValues.length << 1) | 1;
  1565. staticValues.push(p.value);
  1566. }
  1567. else {
  1568. address[p.id] = dynamicSlots.length << 1;
  1569. dynamicSlots.push(a => p.dynamicSlot(a));
  1570. }
  1571. }
  1572. address[facet.id] = dynamicSlots.length << 1;
  1573. dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
  1574. }
  1575. }
  1576. return new Configuration(extension, replacements, dynamicSlots.map(f => f(address)), address, staticValues);
  1577. }
  1578. }
  1579. function allKeys(obj) {
  1580. return (Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(obj) : []).concat(Object.keys(obj));
  1581. }
  1582. function flatten(extension, replacements) {
  1583. let result = [[], [], [], []];
  1584. let seen = new Map();
  1585. let tagsSeen = Object.create(null);
  1586. function inner(ext, prec) {
  1587. let known = seen.get(ext);
  1588. if (known != null) {
  1589. if (known >= prec)
  1590. return;
  1591. let found = result[known].indexOf(ext);
  1592. if (found > -1)
  1593. result[known].splice(found, 1);
  1594. }
  1595. seen.set(ext, prec);
  1596. if (Array.isArray(ext)) {
  1597. for (let e of ext)
  1598. inner(e, prec);
  1599. }
  1600. else if (ext instanceof TaggedExtension) {
  1601. if (ext.tag in tagsSeen)
  1602. throw new RangeError(`Duplicate use of tag '${String(ext.tag)}' in extensions`);
  1603. tagsSeen[ext.tag] = true;
  1604. inner(replacements[ext.tag] || ext.inner, prec);
  1605. }
  1606. else if (ext instanceof PrecExtension) {
  1607. inner(ext.inner, ext.prec);
  1608. }
  1609. else if (ext instanceof StateField) {
  1610. result[prec].push(ext);
  1611. if (ext.provides)
  1612. inner(ext.provides, prec);
  1613. }
  1614. else if (ext instanceof FacetProvider) {
  1615. result[prec].push(ext);
  1616. if (ext.facet.extensions)
  1617. inner(ext.facet.extensions, prec);
  1618. }
  1619. else {
  1620. inner(ext.extension, prec);
  1621. }
  1622. }
  1623. inner(extension, Prec_.default);
  1624. for (let key of allKeys(replacements))
  1625. if (!(key in tagsSeen) && key != "full" && replacements[key]) {
  1626. tagsSeen[key] = true;
  1627. inner(replacements[key], Prec_.default);
  1628. }
  1629. return result.reduce((a, b) => a.concat(b));
  1630. }
  1631. function ensureAddr(state, addr) {
  1632. if (addr & 1)
  1633. return 2 /* Computed */;
  1634. let idx = addr >> 1;
  1635. let status = state.status[idx];
  1636. if (status == 4 /* Computing */)
  1637. throw new Error("Cyclic dependency between fields and/or facets");
  1638. if (status & 2 /* Computed */)
  1639. return status;
  1640. state.status[idx] = 4 /* Computing */;
  1641. let changed = state.config.dynamicSlots[idx](state, state.applying);
  1642. return state.status[idx] = 2 /* Computed */ | changed;
  1643. }
  1644. function getAddr(state, addr) {
  1645. return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
  1646. }
  1647. const languageData = Facet.define();
  1648. const allowMultipleSelections = Facet.define({
  1649. combine: values => values.some(v => v),
  1650. static: true
  1651. });
  1652. const lineSeparator = Facet.define({
  1653. combine: values => values.length ? values[0] : undefined,
  1654. static: true
  1655. });
  1656. const changeFilter = Facet.define();
  1657. const transactionFilter = Facet.define();
  1658. const transactionExtender = Facet.define();
  1659. /// Annotations are tagged values that are used to add metadata to
  1660. /// transactions in an extensible way. They should be used to model
  1661. /// things that effect the entire transaction (such as its [time
  1662. /// stamp](#state.Transaction^time) or information about its
  1663. /// [origin](#state.Transaction^userEvent)). For effects that happen
  1664. /// _alongside_ the other changes made by the transaction, [state
  1665. /// effects](#state.StateEffect) are more appropriate.
  1666. class Annotation {
  1667. /// @internal
  1668. constructor(
  1669. /// The annotation type.
  1670. type,
  1671. /// The value of this annotation.
  1672. value) {
  1673. this.type = type;
  1674. this.value = value;
  1675. }
  1676. /// Define a new type of annotation.
  1677. static define() { return new AnnotationType(); }
  1678. }
  1679. /// Marker that identifies a type of [annotation](#state.Annotation).
  1680. class AnnotationType {
  1681. /// Create an instance of this annotation.
  1682. of(value) { return new Annotation(this, value); }
  1683. }
  1684. /// State effects can be used to represent additional effects
  1685. /// associated with a [transaction](#state.Transaction.effects). They
  1686. /// are often useful to model changes to custom [state
  1687. /// fields](#state.StateField), when those changes aren't implicit in
  1688. /// document or selection changes.
  1689. class StateEffect {
  1690. /// @internal
  1691. constructor(
  1692. /// @internal
  1693. type,
  1694. /// The value of this effect.
  1695. value) {
  1696. this.type = type;
  1697. this.value = value;
  1698. }
  1699. /// Map this effect through a position mapping. Will return
  1700. /// `undefined` when that ends up deleting the effect.
  1701. map(mapping) {
  1702. let mapped = this.type.map(this.value, mapping);
  1703. return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
  1704. }
  1705. /// Tells you whether this effect object is of a given
  1706. /// [type](#state.StateEffectType).
  1707. is(type) { return this.type == type; }
  1708. /// Define a new effect type. The type parameter indicates the type
  1709. /// of values that his effect holds.
  1710. static define(spec = {}) {
  1711. return new StateEffectType(spec.map || (v => v));
  1712. }
  1713. /// Map an array of effects through a change set.
  1714. static mapEffects(effects, mapping) {
  1715. if (!effects.length)
  1716. return effects;
  1717. let result = [];
  1718. for (let effect of effects) {
  1719. let mapped = effect.map(mapping);
  1720. if (mapped)
  1721. result.push(mapped);
  1722. }
  1723. return result;
  1724. }
  1725. }
  1726. /// Representation of a type of state effect. Defined with
  1727. /// [`StateEffect.define`](#state.StateEffect^define).
  1728. class StateEffectType {
  1729. /// @internal
  1730. constructor(
  1731. // The `any` types in these function types are there to work
  1732. // around TypeScript issue #37631, where the type guard on
  1733. // `StateEffect.is` mysteriously stops working when these properly
  1734. // have type `Value`.
  1735. /// @internal
  1736. map) {
  1737. this.map = map;
  1738. }
  1739. /// Create a [state effect](#state.StateEffect) instance of this
  1740. /// type.
  1741. of(value) { return new StateEffect(this, value); }
  1742. }
  1743. /// Changes to the editor state are grouped into transactions.
  1744. /// Typically, a user action creates a single transaction, which may
  1745. /// contain any number of document changes, may change the selection,
  1746. /// or have other effects. Create a transaction by calling
  1747. /// [`EditorState.update`](#state.EditorState.update).
  1748. class Transaction {
  1749. /// @internal
  1750. constructor(
  1751. /// The state from which the transaction starts.
  1752. startState,
  1753. /// The document changes made by this transaction.
  1754. changes,
  1755. /// The selection set by this transaction, or undefined if it
  1756. /// doesn't explicitly set a selection.
  1757. selection,
  1758. /// The effects added to the transaction.
  1759. effects,
  1760. /// @internal
  1761. annotations,
  1762. /// Holds an object when this transaction
  1763. /// [reconfigures](#state.ReconfigurationSpec) the state.
  1764. reconfigure,
  1765. /// Whether the selection should be scrolled into view after this
  1766. /// transaction is dispatched.
  1767. scrollIntoView) {
  1768. this.startState = startState;
  1769. this.changes = changes;
  1770. this.selection = selection;
  1771. this.effects = effects;
  1772. this.annotations = annotations;
  1773. this.reconfigure = reconfigure;
  1774. this.scrollIntoView = scrollIntoView;
  1775. /// @internal
  1776. this._doc = null;
  1777. /// @internal
  1778. this._state = null;
  1779. if (selection)
  1780. checkSelection(selection, changes.newLength);
  1781. if (!annotations.some((a) => a.type == Transaction.time))
  1782. this.annotations = annotations.concat(Transaction.time.of(Date.now()));
  1783. }
  1784. /// The new document produced by the transaction. Contrary to
  1785. /// [`.state`](#state.Transaction.state)`.doc`, accessing this won't
  1786. /// force the entire new state to be computed right away, so it is
  1787. /// recommended that [transaction
  1788. /// filters](#state.EditorState^transactionFilter) use this getter
  1789. /// when they need to look at the new document.
  1790. get newDoc() {
  1791. return this._doc || (this._doc = this.changes.apply(this.startState.doc));
  1792. }
  1793. /// The new selection produced by the transaction. If
  1794. /// [`this.selection`](#state.Transaction.selection) is undefined,
  1795. /// this will [map](#state.EditorSelection.map) the start state's
  1796. /// current selection through the changes made by the transaction.
  1797. get newSelection() {
  1798. return this.selection || this.startState.selection.map(this.changes);
  1799. }
  1800. /// The new state created by the transaction. Computed on demand
  1801. /// (but retained for subsequent access), so itis recommended not to
  1802. /// access it in [transaction
  1803. /// filters](#state.EditorState^transactionFilter) when possible.
  1804. get state() {
  1805. if (!this._state)
  1806. this.startState.applyTransaction(this);
  1807. return this._state;
  1808. }
  1809. /// Get the value of the given annotation type, if any.
  1810. annotation(type) {
  1811. for (let ann of this.annotations)
  1812. if (ann.type == type)
  1813. return ann.value;
  1814. return undefined;
  1815. }
  1816. /// Indicates whether the transaction changed the document.
  1817. get docChanged() { return !this.changes.empty; }
  1818. }
  1819. /// Annotation used to store transaction timestamps.
  1820. Transaction.time = Annotation.define();
  1821. /// Annotation used to associate a transaction with a user interface
  1822. /// event. The view will set this to...
  1823. ///
  1824. /// - `"input"` when the user types text
  1825. /// - `"delete"` when the user deletes the selection or text near the selection
  1826. /// - `"keyboardselection"` when moving the selection via the keyboard
  1827. /// - `"pointerselection"` when moving the selection through the pointing device
  1828. /// - `"paste"` when pasting content
  1829. /// - `"cut"` when cutting
  1830. /// - `"drop"` when content is inserted via drag-and-drop
  1831. Transaction.userEvent = Annotation.define();
  1832. /// Annotation indicating whether a transaction should be added to
  1833. /// the undo history or not.
  1834. Transaction.addToHistory = Annotation.define();
  1835. function joinRanges(a, b) {
  1836. let result = [];
  1837. for (let iA = 0, iB = 0;;) {
  1838. let from, to;
  1839. if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
  1840. from = a[iA++];
  1841. to = a[iA++];
  1842. }
  1843. else if (iB < b.length) {
  1844. from = b[iB++];
  1845. to = b[iB++];
  1846. }
  1847. else
  1848. return result;
  1849. if (!result.length || result[result.length - 1] < from)
  1850. result.push(from, to);
  1851. else if (result[result.length - 1] < to)
  1852. result[result.length - 1] = to;
  1853. }
  1854. }
  1855. function mergeTransaction(a, b, sequential) {
  1856. var _a;
  1857. let mapForA, mapForB, changes;
  1858. if (sequential) {
  1859. mapForA = b.changes;
  1860. mapForB = ChangeSet.empty(b.changes.length);
  1861. changes = a.changes.compose(b.changes);
  1862. }
  1863. else {
  1864. mapForA = b.changes.map(a.changes);
  1865. mapForB = a.changes.mapDesc(b.changes, true);
  1866. changes = a.changes.compose(mapForA);
  1867. }
  1868. return {
  1869. changes,
  1870. selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
  1871. effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
  1872. annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
  1873. scrollIntoView: a.scrollIntoView || b.scrollIntoView,
  1874. reconfigure: !b.reconfigure ? a.reconfigure : b.reconfigure.full || !a.reconfigure ? b.reconfigure
  1875. : Object.assign({}, a.reconfigure, b.reconfigure)
  1876. };
  1877. }
  1878. function resolveTransactionInner(state, spec, docSize) {
  1879. let reconf = spec.reconfigure;
  1880. if (reconf && reconf.append) {
  1881. reconf = Object.assign({}, reconf);
  1882. let tag = typeof Symbol == "undefined" ? "__append" + Math.floor(Math.random() * 0xffffffff) : Symbol("appendConf");
  1883. reconf[tag] = reconf.append;
  1884. reconf.append = undefined;
  1885. }
  1886. let sel = spec.selection;
  1887. return {
  1888. changes: spec.changes instanceof ChangeSet ? spec.changes
  1889. : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
  1890. selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
  1891. effects: asArray(spec.effects),
  1892. annotations: asArray(spec.annotations),
  1893. scrollIntoView: !!spec.scrollIntoView,
  1894. reconfigure: reconf
  1895. };
  1896. }
  1897. function resolveTransaction(state, specs, filter) {
  1898. let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
  1899. if (specs.length && specs[0].filter === false)
  1900. filter = false;
  1901. for (let i = 1; i < specs.length; i++) {
  1902. if (specs[i].filter === false)
  1903. filter = false;
  1904. let seq = !!specs[i].sequential;
  1905. s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
  1906. }
  1907. let tr = new Transaction(state, s.changes, s.selection, s.effects, s.annotations, s.reconfigure, s.scrollIntoView);
  1908. return extendTransaction(filter ? filterTransaction(tr) : tr);
  1909. }
  1910. // Finish a transaction by applying filters if necessary.
  1911. function filterTransaction(tr) {
  1912. let state = tr.startState;
  1913. // Change filters
  1914. let result = true;
  1915. for (let filter of state.facet(changeFilter)) {
  1916. let value = filter(tr);
  1917. if (value === false) {
  1918. result = false;
  1919. break;
  1920. }
  1921. if (Array.isArray(value))
  1922. result = result === true ? value : joinRanges(result, value);
  1923. }
  1924. if (result !== true) {
  1925. let changes, back;
  1926. if (result === false) {
  1927. back = tr.changes.invertedDesc;
  1928. changes = ChangeSet.empty(state.doc.length);
  1929. }
  1930. else {
  1931. let filtered = tr.changes.filter(result);
  1932. changes = filtered.changes;
  1933. back = filtered.filtered.invertedDesc;
  1934. }
  1935. tr = new Transaction(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.reconfigure, tr.scrollIntoView);
  1936. }
  1937. // Transaction filters
  1938. let filters = state.facet(transactionFilter);
  1939. for (let i = filters.length - 1; i >= 0; i--) {
  1940. let filtered = filters[i](tr);
  1941. if (filtered instanceof Transaction)
  1942. tr = filtered;
  1943. else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
  1944. tr = filtered[0];
  1945. else
  1946. tr = resolveTransaction(state, asArray(filtered), false);
  1947. }
  1948. return tr;
  1949. }
  1950. function extendTransaction(tr) {
  1951. let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
  1952. for (let i = extenders.length - 1; i >= 0; i--) {
  1953. let extension = extenders[i](tr);
  1954. if (extension && Object.keys(extension).length)
  1955. spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true);
  1956. }
  1957. return spec == tr ? tr : new Transaction(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.reconfigure, spec.scrollIntoView);
  1958. }
  1959. const none = [];
  1960. function asArray(value) {
  1961. return value == null ? none : Array.isArray(value) ? value : [value];
  1962. }
  1963. /// The categories produced by a [character
  1964. /// categorizer](#state.EditorState.charCategorizer). These are used
  1965. /// do things like selecting by word.
  1966. var CharCategory;
  1967. (function (CharCategory) {
  1968. /// Word characters.
  1969. CharCategory[CharCategory["Word"] = 0] = "Word";
  1970. /// Whitespace.
  1971. CharCategory[CharCategory["Space"] = 1] = "Space";
  1972. /// Anything else.
  1973. CharCategory[CharCategory["Other"] = 2] = "Other";
  1974. })(CharCategory || (CharCategory = {}));
  1975. const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  1976. let wordChar;
  1977. try {
  1978. wordChar = new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
  1979. }
  1980. catch (_) { }
  1981. function hasWordChar(str) {
  1982. if (wordChar)
  1983. return wordChar.test(str);
  1984. for (let i = 0; i < str.length; i++) {
  1985. let ch = str[i];
  1986. if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
  1987. return true;
  1988. }
  1989. return false;
  1990. }
  1991. function makeCategorizer(wordChars) {
  1992. return (char) => {
  1993. if (!/\S/.test(char))
  1994. return CharCategory.Space;
  1995. if (hasWordChar(char))
  1996. return CharCategory.Word;
  1997. for (let i = 0; i < wordChars.length; i++)
  1998. if (char.indexOf(wordChars[i]) > -1)
  1999. return CharCategory.Word;
  2000. return CharCategory.Other;
  2001. };
  2002. }
  2003. /// The editor state class is a persistent (immutable) data structure.
  2004. /// To update a state, you [create](#state.EditorState.update) a
  2005. /// [transaction](#state.Transaction), which produces a _new_ state
  2006. /// instance, without modifying the original object.
  2007. ///
  2008. /// As such, _never_ mutate properties of a state directly. That'll
  2009. /// just break things.
  2010. class EditorState {
  2011. /// @internal
  2012. constructor(
  2013. /// @internal
  2014. config,
  2015. /// The current document.
  2016. doc,
  2017. /// The current selection.
  2018. selection, tr = null) {
  2019. this.config = config;
  2020. this.doc = doc;
  2021. this.selection = selection;
  2022. /// @internal
  2023. this.applying = null;
  2024. this.status = config.statusTemplate.slice();
  2025. if (tr && !tr.reconfigure) {
  2026. this.values = tr.startState.values.slice();
  2027. }
  2028. else {
  2029. this.values = config.dynamicSlots.map(_ => null);
  2030. // Copy over old values for shared facets/fields if this is a reconfigure
  2031. if (tr)
  2032. for (let id in config.address) {
  2033. let cur = config.address[id], prev = tr.startState.config.address[id];
  2034. if (prev != null && (cur & 1) == 0)
  2035. this.values[cur >> 1] = getAddr(tr.startState, prev);
  2036. }
  2037. }
  2038. this.applying = tr;
  2039. // Fill in the computed state immediately, so that further queries
  2040. // for it made during the update return this state
  2041. if (tr)
  2042. tr._state = this;
  2043. for (let i = 0; i < this.config.dynamicSlots.length; i++)
  2044. ensureAddr(this, i << 1);
  2045. this.applying = null;
  2046. }
  2047. field(field, require = true) {
  2048. let addr = this.config.address[field.id];
  2049. if (addr == null) {
  2050. if (require)
  2051. throw new RangeError("Field is not present in this state");
  2052. return undefined;
  2053. }
  2054. ensureAddr(this, addr);
  2055. return getAddr(this, addr);
  2056. }
  2057. /// Create a [transaction](#state.Transaction) that updates this
  2058. /// state. Any number of [transaction specs](#state.TransactionSpec)
  2059. /// can be passed. Unless
  2060. /// [`sequential`](#state.TransactionSpec.sequential) is set, the
  2061. /// [changes](#state.TransactionSpec.changes) (if any) of each spec
  2062. /// are assumed to start in the _current_ document (not the document
  2063. /// produced by previous specs), and its
  2064. /// [selection](#state.TransactionSpec.selection) and
  2065. /// [effects](#state.TransactionSpec.effects) are assumed to refer
  2066. /// to the document created by its _own_ changes. The resulting
  2067. /// transaction contains the combined effect of all the different
  2068. /// specs. For things like
  2069. /// [selection](#state.TransactionSpec.selection) or
  2070. /// [reconfiguration](#state.TransactionSpec.reconfigure), later
  2071. /// specs take precedence over earlier ones.
  2072. update(...specs) {
  2073. return resolveTransaction(this, specs, true);
  2074. }
  2075. /// @internal
  2076. applyTransaction(tr) {
  2077. let conf = this.config;
  2078. if (tr.reconfigure)
  2079. conf = Configuration.resolve(tr.reconfigure.full || conf.source, Object.assign(conf.replacements, tr.reconfigure, { full: undefined }), this);
  2080. new EditorState(conf, tr.newDoc, tr.newSelection, tr);
  2081. }
  2082. /// Create a [transaction spec](#state.TransactionSpec) that
  2083. /// replaces every selection range with the given content.
  2084. replaceSelection(text) {
  2085. if (typeof text == "string")
  2086. text = this.toText(text);
  2087. return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
  2088. range: EditorSelection.cursor(range.from + text.length) }));
  2089. }
  2090. /// Create a set of changes and a new selection by running the given
  2091. /// function for each range in the active selection. The function
  2092. /// can return an optional set of changes (in the coordinate space
  2093. /// of the start document), plus an updated range (in the coordinate
  2094. /// space of the document produced by the call's own changes). This
  2095. /// method will merge all the changes and ranges into a single
  2096. /// changeset and selection, and return it as a [transaction
  2097. /// spec](#state.TransactionSpec), which can be passed to
  2098. /// [`update`](#state.EditorState.update).
  2099. changeByRange(f) {
  2100. let sel = this.selection;
  2101. let result1 = f(sel.ranges[0]);
  2102. let changes = this.changes(result1.changes), ranges = [result1.range];
  2103. let effects = asArray(result1.effects);
  2104. for (let i = 1; i < sel.ranges.length; i++) {
  2105. let result = f(sel.ranges[i]);
  2106. let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
  2107. for (let j = 0; j < i; j++)
  2108. ranges[j] = ranges[j].map(newMapped);
  2109. let mapBy = changes.mapDesc(newChanges, true);
  2110. ranges.push(result.range.map(mapBy));
  2111. changes = changes.compose(newMapped);
  2112. effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
  2113. }
  2114. return {
  2115. changes,
  2116. selection: EditorSelection.create(ranges, sel.mainIndex),
  2117. effects
  2118. };
  2119. }
  2120. /// Create a [change set](#state.ChangeSet) from the given change
  2121. /// description, taking the state's document length and line
  2122. /// separator into account.
  2123. changes(spec = []) {
  2124. if (spec instanceof ChangeSet)
  2125. return spec;
  2126. return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
  2127. }
  2128. /// Using the state's [line
  2129. /// separator](#state.EditorState^lineSeparator), create a
  2130. /// [`Text`](#text.Text) instance from the given string.
  2131. toText(string) {
  2132. return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
  2133. }
  2134. /// Return the given range of the document as a string.
  2135. sliceDoc(from = 0, to = this.doc.length) {
  2136. return this.doc.sliceString(from, to, this.lineBreak);
  2137. }
  2138. /// Get the value of a state [facet](#state.Facet).
  2139. facet(facet) {
  2140. let addr = this.config.address[facet.id];
  2141. if (addr == null)
  2142. return facet.default;
  2143. ensureAddr(this, addr);
  2144. return getAddr(this, addr);
  2145. }
  2146. /// Convert this state to a JSON-serializable object. When custom
  2147. /// fields should be serialized, you can pass them in as an object
  2148. /// mapping property names (in the resulting object, which should
  2149. /// not use `doc` or `selection`) to fields.
  2150. toJSON(fields) {
  2151. let result = {
  2152. doc: this.sliceDoc(),
  2153. selection: this.selection.toJSON()
  2154. };
  2155. if (fields)
  2156. for (let prop in fields)
  2157. result[prop] = fields[prop].spec.toJSON(this.field(fields[prop]), this);
  2158. return result;
  2159. }
  2160. /// Deserialize a state from its JSON representation. When custom
  2161. /// fields should be deserialized, pass the same object you passed
  2162. /// to [`toJSON`](#state.EditorState.toJSON) when serializing as
  2163. /// third argument.
  2164. static fromJSON(json, config = {}, fields) {
  2165. if (!json || typeof json.doc != "string")
  2166. throw new RangeError("Invalid JSON representation for EditorState");
  2167. let fieldInit = [];
  2168. if (fields)
  2169. for (let prop in fields) {
  2170. let field = fields[prop], value = json[prop];
  2171. fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
  2172. }
  2173. return EditorState.create({
  2174. doc: json.doc,
  2175. selection: EditorSelection.fromJSON(json.selection),
  2176. extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
  2177. });
  2178. }
  2179. /// Create a new state. You'll usually only need this when
  2180. /// initializing an editor—updated states are created by applying
  2181. /// transactions.
  2182. static create(config = {}) {
  2183. let configuration = Configuration.resolve(config.extensions || []);
  2184. let doc = config.doc instanceof Text ? config.doc
  2185. : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
  2186. let selection = !config.selection ? EditorSelection.single(0)
  2187. : config.selection instanceof EditorSelection ? config.selection
  2188. : EditorSelection.single(config.selection.anchor, config.selection.head);
  2189. checkSelection(selection, doc.length);
  2190. if (!configuration.staticFacet(allowMultipleSelections))
  2191. selection = selection.asSingle();
  2192. return new EditorState(configuration, doc, selection);
  2193. }
  2194. /// The size (in columns) of a tab in the document, determined by
  2195. /// the [`tabSize`](#state.EditorState^tabSize) facet.
  2196. get tabSize() { return this.facet(EditorState.tabSize); }
  2197. /// Get the proper [line-break](#state.EditorState^lineSeparator)
  2198. /// string for this state.
  2199. get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
  2200. /// Look up a translation for the given phrase (via the
  2201. /// [`phrases`](#state.EditorState^phrases) facet), or return the
  2202. /// original string if no translation is found.
  2203. phrase(phrase) {
  2204. for (let map of this.facet(EditorState.phrases))
  2205. if (Object.prototype.hasOwnProperty.call(map, phrase))
  2206. return map[phrase];
  2207. return phrase;
  2208. }
  2209. /// Find the values for a given language data field, provided by the
  2210. /// the [`languageData`](#state.EditorState^languageData) facet.
  2211. languageDataAt(name, pos) {
  2212. let values = [];
  2213. for (let provider of this.facet(languageData)) {
  2214. for (let result of provider(this, pos)) {
  2215. if (Object.prototype.hasOwnProperty.call(result, name))
  2216. values.push(result[name]);
  2217. }
  2218. }
  2219. return values;
  2220. }
  2221. /// Return a function that can categorize strings (expected to
  2222. /// represent a single [grapheme cluster](#text.findClusterBreak))
  2223. /// into one of:
  2224. ///
  2225. /// - Word (contains an alphanumeric character or a character
  2226. /// explicitly listed in the local language's `"wordChars"`
  2227. /// language data, which should be a string)
  2228. /// - Space (contains only whitespace)
  2229. /// - Other (anything else)
  2230. charCategorizer(at) {
  2231. return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
  2232. }
  2233. }
  2234. /// A facet that, when enabled, causes the editor to allow multiple
  2235. /// ranges to be selected. Be careful though, because by default the
  2236. /// editor relies on the native DOM selection, which cannot handle
  2237. /// multiple selections. An extension like
  2238. /// [`drawSelection`](#view.drawSelection) can be used to make
  2239. /// secondary selections visible to the user.
  2240. EditorState.allowMultipleSelections = allowMultipleSelections;
  2241. /// Configures the tab size to use in this state. The first
  2242. /// (highest-precedence) value of the facet is used. If no value is
  2243. /// given, this defaults to 4.
  2244. EditorState.tabSize = Facet.define({
  2245. combine: values => values.length ? values[0] : 4
  2246. });
  2247. /// The line separator to use. By default, any of `"\n"`, `"\r\n"`
  2248. /// and `"\r"` is treated as a separator when splitting lines, and
  2249. /// lines are joined with `"\n"`.
  2250. ///
  2251. /// When you configure a value here, only that precise separator
  2252. /// will be used, allowing you to round-trip documents through the
  2253. /// editor without normalizing line separators.
  2254. EditorState.lineSeparator = lineSeparator;
  2255. /// Registers translation phrases. The
  2256. /// [`phrase`](#state.EditorState.phrase) method will look through
  2257. /// all objects registered with this facet to find translations for
  2258. /// its argument.
  2259. EditorState.phrases = Facet.define();
  2260. /// A facet used to register [language
  2261. /// data](#state.EditorState.languageDataAt) providers.
  2262. EditorState.languageData = languageData;
  2263. /// Facet used to register change filters, which are called for each
  2264. /// transaction (unless explicitly
  2265. /// [disabled](#state.TransactionSpec.filter)), and can suppress
  2266. /// part of the transaction's changes.
  2267. ///
  2268. /// Such a function can return `true` to indicate that it doesn't
  2269. /// want to do anything, `false` to completely stop the changes in
  2270. /// the transaction, or a set of ranges in which changes should be
  2271. /// suppressed. Such ranges are represented as an array of numbers,
  2272. /// with each pair of two number indicating the start and end of a
  2273. /// range. So for example `[10, 20, 100, 110]` suppresses changes
  2274. /// between 10 and 20, and between 100 and 110.
  2275. EditorState.changeFilter = changeFilter;
  2276. /// Facet used to register a hook that gets a chance to update or
  2277. /// replace transaction specs before they are applied. This will
  2278. /// only be applied for transactions that don't have
  2279. /// [`filter`](#state.TransactionSpec.filter) set to `false`. You
  2280. /// can either return a single (possibly the input transaction), or
  2281. /// an array of specs (which will be combined in the same way as the
  2282. /// arguments to [`EditorState.update`](#state.EditorState.update)).
  2283. ///
  2284. /// When possible, it is recommended to avoid accessing
  2285. /// [`Transaction.state`](#state.Transaction.state) in a filter,
  2286. /// since it will force creation of a state that will then be
  2287. /// discarded again, if the transaction is actually filtered.
  2288. ///
  2289. /// (This functionality should be used with care. Indiscriminately
  2290. /// modifying transaction is likely to break something or degrade
  2291. /// the user experience.)
  2292. EditorState.transactionFilter = transactionFilter;
  2293. /// This is a more limited form of
  2294. /// [`transactionFilter`](#state.EditorState^transactionFilter),
  2295. /// which can only add
  2296. /// [annotations](#state.TransactionSpec.annotations),
  2297. /// [effects](#state.TransactionSpec.effects), and
  2298. /// [configuration](#state.TransactionSpec.reconfigure) info. _But_,
  2299. /// this type of filter runs even the transaction has disabled
  2300. /// regular [filtering](#state.TransactionSpec.filter), making it
  2301. /// suitable for effects that don't need to touch the changes or
  2302. /// selection, but do want to process every transaction.
  2303. ///
  2304. /// Extenders run _after_ filters, when both are applied.
  2305. EditorState.transactionExtender = transactionExtender;
  2306. /// Utility function for combining behaviors to fill in a config
  2307. /// object from an array of provided configs. Will, by default, error
  2308. /// when a field gets two values that aren't `===`-equal, but you can
  2309. /// provide combine functions per field to do something else.
  2310. function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
  2311. combine = {}) {
  2312. let result = {};
  2313. for (let config of configs)
  2314. for (let key of Object.keys(config)) {
  2315. let value = config[key], current = result[key];
  2316. if (current === undefined)
  2317. result[key] = value;
  2318. else if (current === value || value === undefined) ; // No conflict
  2319. else if (Object.hasOwnProperty.call(combine, key))
  2320. result[key] = combine[key](current, value);
  2321. else
  2322. throw new Error("Config merge conflict for field " + key);
  2323. }
  2324. for (let key in defaults)
  2325. if (result[key] === undefined)
  2326. result[key] = defaults[key];
  2327. return result;
  2328. }
  2329. const C = "\u037c";
  2330. const COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
  2331. const SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
  2332. const top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
  2333. // :: - Style modules encapsulate a set of CSS rules defined from
  2334. // JavaScript. Their definitions are only available in a given DOM
  2335. // root after it has been _mounted_ there with `StyleModule.mount`.
  2336. //
  2337. // Style modules should be created once and stored somewhere, as
  2338. // opposed to re-creating them every time you need them. The amount of
  2339. // CSS rules generated for a given DOM root is bounded by the amount
  2340. // of style modules that were used. So to avoid leaking rules, don't
  2341. // create these dynamically, but treat them as one-time allocations.
  2342. class StyleModule {
  2343. // :: (Object<Style>, ?{process: (string) → string, extend: (string, string) → string})
  2344. // Create a style module from the given spec.
  2345. //
  2346. // When `process` is given, it is called on regular (non-`@`)
  2347. // selector properties to provide the actual selector. When `extend`
  2348. // is given, it is called when a property containing an `&` is
  2349. // found, and should somehow combine the `&`-template (its first
  2350. // argument) with the selector (its second argument) to produce an
  2351. // extended selector.
  2352. constructor(spec, options) {
  2353. this.rules = [];
  2354. let {process, extend} = options || {};
  2355. function processSelector(selector) {
  2356. if (/^@/.test(selector)) return [selector]
  2357. let selectors = selector.split(",");
  2358. return process ? selectors.map(process) : selectors
  2359. }
  2360. function render(selectors, spec, target) {
  2361. let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]);
  2362. if (isAt && spec == null) return target.push(selectors[0] + ";")
  2363. for (let prop in spec) {
  2364. let value = spec[prop];
  2365. if (/&/.test(prop)) {
  2366. render(selectors.map(s => extend ? extend(prop, s) : prop.replace(/&/, s)), value, target);
  2367. } else if (value && typeof value == "object") {
  2368. if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.")
  2369. render(isAt[1] == "keyframes" ? [prop] : processSelector(prop), value, local);
  2370. } else if (value != null) {
  2371. local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";");
  2372. }
  2373. }
  2374. if (local.length || isAt && isAt[1] == "keyframes") target.push(selectors.join(",") + " {" + local.join(" ") + "}");
  2375. }
  2376. for (let prop in spec) render(processSelector(prop), spec[prop], this.rules);
  2377. }
  2378. // :: () → string
  2379. // Returns a string containing the module's CSS rules.
  2380. getRules() { return this.rules.join("\n") }
  2381. // :: () → string
  2382. // Generate a new unique CSS class name.
  2383. static newName() {
  2384. let id = top[COUNT] || 1;
  2385. top[COUNT] = id + 1;
  2386. return C + id.toString(36)
  2387. }
  2388. // :: (union<Document, ShadowRoot>, union<[StyleModule], StyleModule>)
  2389. //
  2390. // Mount the given set of modules in the given DOM root, which ensures
  2391. // that the CSS rules defined by the module are available in that
  2392. // context.
  2393. //
  2394. // Rules are only added to the document once per root.
  2395. //
  2396. // Rule order will follow the order of the modules, so that rules from
  2397. // modules later in the array take precedence of those from earlier
  2398. // modules. If you call this function multiple times for the same root
  2399. // in a way that changes the order of already mounted modules, the old
  2400. // order will be changed.
  2401. static mount(root, modules) {
  2402. (root[SET] || new StyleSet(root)).mount(Array.isArray(modules) ? modules : [modules]);
  2403. }
  2404. }
  2405. let adoptedSet = null;
  2406. class StyleSet {
  2407. constructor(root) {
  2408. if (!root.head && root.adoptedStyleSheets && typeof CSSStyleSheet != "undefined") {
  2409. if (adoptedSet) {
  2410. root.adoptedStyleSheets = [adoptedSet.sheet].concat(root.adoptedStyleSheets);
  2411. return root[SET] = adoptedSet
  2412. }
  2413. this.sheet = new CSSStyleSheet;
  2414. root.adoptedStyleSheets = [this.sheet].concat(root.adoptedStyleSheets);
  2415. adoptedSet = this;
  2416. } else {
  2417. this.styleTag = (root.ownerDocument || root).createElement("style");
  2418. let target = root.head || root;
  2419. target.insertBefore(this.styleTag, target.firstChild);
  2420. }
  2421. this.modules = [];
  2422. root[SET] = this;
  2423. }
  2424. mount(modules) {
  2425. let sheet = this.sheet;
  2426. let pos = 0 /* Current rule offset */, j = 0; /* Index into this.modules */
  2427. for (let i = 0; i < modules.length; i++) {
  2428. let mod = modules[i], index = this.modules.indexOf(mod);
  2429. if (index < j && index > -1) { // Ordering conflict
  2430. this.modules.splice(index, 1);
  2431. j--;
  2432. index = -1;
  2433. }
  2434. if (index == -1) {
  2435. this.modules.splice(j++, 0, mod);
  2436. if (sheet) for (let k = 0; k < mod.rules.length; k++)
  2437. sheet.insertRule(mod.rules[k], pos++);
  2438. } else {
  2439. while (j < index) pos += this.modules[j++].rules.length;
  2440. pos += mod.rules.length;
  2441. j++;
  2442. }
  2443. }
  2444. if (!sheet) {
  2445. let text = "";
  2446. for (let i = 0; i < this.modules.length; i++)
  2447. text += this.modules[i].getRules() + "\n";
  2448. this.styleTag.textContent = text;
  2449. }
  2450. }
  2451. }
  2452. // Style::Object<union<Style,string>>
  2453. //
  2454. // A style is an object that, in the simple case, maps CSS property
  2455. // names to strings holding their values, as in `{color: "red",
  2456. // fontWeight: "bold"}`. The property names can be given in
  2457. // camel-case—the library will insert a dash before capital letters
  2458. // when converting them to CSS.
  2459. //
  2460. // If you include an underscore in a property name, it and everything
  2461. // after it will be removed from the output, which can be useful when
  2462. // providing a property multiple times, for browser compatibility
  2463. // reasons.
  2464. //
  2465. // A property in a style object can also be a sub-selector, which
  2466. // extends the current context to add a pseudo-selector or a child
  2467. // selector. Such a property should contain a `&` character, which
  2468. // will be replaced by the current selector. For example `{"&:before":
  2469. // {content: '"hi"'}}`. Sub-selectors and regular properties can
  2470. // freely be mixed in a given object. Any property containing a `&` is
  2471. // assumed to be a sub-selector.
  2472. //
  2473. // Finally, a property can specify an @-block to be wrapped around the
  2474. // styles defined inside the object that's the property's value. For
  2475. // example to create a media query you can do `{"@media screen and
  2476. // (min-width: 400px)": {...}}`.
  2477. /// Each range is associated with a value, which must inherit from
  2478. /// this class.
  2479. class RangeValue {
  2480. /// Compare this value with another value. The default
  2481. /// implementation compares by identity.
  2482. eq(other) { return this == other; }
  2483. /// Create a [range](#rangeset.Range) with this value.
  2484. range(from, to = from) { return new Range(from, to, this); }
  2485. }
  2486. RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
  2487. RangeValue.prototype.point = false;
  2488. RangeValue.prototype.mapMode = MapMode.TrackDel;
  2489. /// A range associates a value with a range of positions.
  2490. class Range {
  2491. /// @internal
  2492. constructor(
  2493. /// The range's start position.
  2494. from,
  2495. /// Its end position.
  2496. to,
  2497. /// The value associated with this range.
  2498. value) {
  2499. this.from = from;
  2500. this.to = to;
  2501. this.value = value;
  2502. }
  2503. }
  2504. function cmpRange(a, b) {
  2505. return a.from - b.from || a.value.startSide - b.value.startSide;
  2506. }
  2507. class Chunk {
  2508. constructor(from, to, value,
  2509. // Chunks are marked with the largest point that occurs
  2510. // in them (or -1 for no points), so that scans that are
  2511. // only interested in points (such as the
  2512. // heightmap-related logic) can skip range-only chunks.
  2513. maxPoint) {
  2514. this.from = from;
  2515. this.to = to;
  2516. this.value = value;
  2517. this.maxPoint = maxPoint;
  2518. }
  2519. get length() { return this.to[this.to.length - 1]; }
  2520. // With side == -1, return the first index where to >= pos. When
  2521. // side == 1, the first index where from > pos.
  2522. findIndex(pos, end, side = end * 1000000000 /* Far */, startAt = 0) {
  2523. if (pos <= 0)
  2524. return startAt;
  2525. let arr = end < 0 ? this.to : this.from;
  2526. for (let lo = startAt, hi = arr.length;;) {
  2527. if (lo == hi)
  2528. return lo;
  2529. let mid = (lo + hi) >> 1;
  2530. let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;
  2531. if (mid == lo)
  2532. return diff >= 0 ? lo : hi;
  2533. if (diff >= 0)
  2534. hi = mid;
  2535. else
  2536. lo = mid + 1;
  2537. }
  2538. }
  2539. between(offset, from, to, f) {
  2540. for (let i = this.findIndex(from, -1), e = this.findIndex(to, 1, undefined, i); i < e; i++)
  2541. if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
  2542. return false;
  2543. }
  2544. map(offset, changes) {
  2545. let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
  2546. for (let i = 0; i < this.value.length; i++) {
  2547. let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
  2548. if (curFrom == curTo) {
  2549. let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
  2550. if (mapped == null)
  2551. continue;
  2552. newFrom = newTo = mapped;
  2553. }
  2554. else {
  2555. newFrom = changes.mapPos(curFrom, val.startSide);
  2556. newTo = changes.mapPos(curTo, val.endSide);
  2557. if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
  2558. continue;
  2559. }
  2560. if ((newTo - newFrom || val.endSide - val.startSide) < 0)
  2561. continue;
  2562. if (newPos < 0)
  2563. newPos = newFrom;
  2564. if (val.point)
  2565. maxPoint = Math.max(maxPoint, newTo - newFrom);
  2566. value.push(val);
  2567. from.push(newFrom - newPos);
  2568. to.push(newTo - newPos);
  2569. }
  2570. return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
  2571. }
  2572. }
  2573. /// A range set stores a collection of [ranges](#rangeset.Range) in a
  2574. /// way that makes them efficient to [map](#rangeset.RangeSet.map) and
  2575. /// [update](#rangeset.RangeSet.update). This is an immutable data
  2576. /// structure.
  2577. class RangeSet {
  2578. /// @internal
  2579. constructor(
  2580. /// @internal
  2581. chunkPos,
  2582. /// @internal
  2583. chunk,
  2584. /// @internal
  2585. nextLayer = RangeSet.empty,
  2586. /// @internal
  2587. maxPoint) {
  2588. this.chunkPos = chunkPos;
  2589. this.chunk = chunk;
  2590. this.nextLayer = nextLayer;
  2591. this.maxPoint = maxPoint;
  2592. }
  2593. /// @internal
  2594. get length() {
  2595. let last = this.chunk.length - 1;
  2596. return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
  2597. }
  2598. /// The number of ranges in the set.
  2599. get size() {
  2600. if (this == RangeSet.empty)
  2601. return 0;
  2602. let size = this.nextLayer.size;
  2603. for (let chunk of this.chunk)
  2604. size += chunk.value.length;
  2605. return size;
  2606. }
  2607. /// @internal
  2608. chunkEnd(index) {
  2609. return this.chunkPos[index] + this.chunk[index].length;
  2610. }
  2611. /// Update the range set, optionally adding new ranges or filtering
  2612. /// out existing ones.
  2613. ///
  2614. /// (The extra type parameter is just there as a kludge to work
  2615. /// around TypeScript variance issues that prevented `RangeSet<X>`
  2616. /// from being a subtype of `RangeSet<Y>` when `X` is a subtype of
  2617. /// `Y`.)
  2618. update(updateSpec) {
  2619. let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
  2620. let filter = updateSpec.filter;
  2621. if (add.length == 0 && !filter)
  2622. return this;
  2623. if (sort)
  2624. add.slice().sort(cmpRange);
  2625. if (this == RangeSet.empty)
  2626. return add.length ? RangeSet.of(add) : this;
  2627. let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
  2628. let builder = new RangeSetBuilder();
  2629. while (cur.value || i < add.length) {
  2630. if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
  2631. let range = add[i++];
  2632. if (!builder.addInner(range.from, range.to, range.value))
  2633. spill.push(range);
  2634. }
  2635. else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
  2636. (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
  2637. (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
  2638. builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
  2639. cur.nextChunk();
  2640. }
  2641. else {
  2642. if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
  2643. if (!builder.addInner(cur.from, cur.to, cur.value))
  2644. spill.push(new Range(cur.from, cur.to, cur.value));
  2645. }
  2646. cur.next();
  2647. }
  2648. }
  2649. return builder.finishInner(this.nextLayer == RangeSet.empty && !spill.length ? RangeSet.empty
  2650. : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
  2651. }
  2652. /// Map this range set through a set of changes, return the new set.
  2653. map(changes) {
  2654. if (changes.length == 0 || this == RangeSet.empty)
  2655. return this;
  2656. let chunks = [], chunkPos = [], maxPoint = -1;
  2657. for (let i = 0; i < this.chunk.length; i++) {
  2658. let start = this.chunkPos[i], chunk = this.chunk[i];
  2659. let touch = changes.touchesRange(start, start + chunk.length);
  2660. if (touch === false) {
  2661. maxPoint = Math.max(maxPoint, chunk.maxPoint);
  2662. chunks.push(chunk);
  2663. chunkPos.push(changes.mapPos(start));
  2664. }
  2665. else if (touch === true) {
  2666. let { mapped, pos } = chunk.map(start, changes);
  2667. if (mapped) {
  2668. maxPoint = Math.max(maxPoint, mapped.maxPoint);
  2669. chunks.push(mapped);
  2670. chunkPos.push(pos);
  2671. }
  2672. }
  2673. }
  2674. let next = this.nextLayer.map(changes);
  2675. return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next, maxPoint);
  2676. }
  2677. /// Iterate over the ranges that touch the region `from` to `to`,
  2678. /// calling `f` for each. There is no guarantee that the ranges will
  2679. /// be reported in any specific order. When the callback returns
  2680. /// `false`, iteration stops.
  2681. between(from, to, f) {
  2682. if (this == RangeSet.empty)
  2683. return;
  2684. for (let i = 0; i < this.chunk.length; i++) {
  2685. let start = this.chunkPos[i], chunk = this.chunk[i];
  2686. if (to >= start && from <= start + chunk.length &&
  2687. chunk.between(start, from - start, to - start, f) === false)
  2688. return;
  2689. }
  2690. this.nextLayer.between(from, to, f);
  2691. }
  2692. /// Iterate over the ranges in this set, in order, including all
  2693. /// ranges that end at or after `from`.
  2694. iter(from = 0) {
  2695. return HeapCursor.from([this]).goto(from);
  2696. }
  2697. /// Iterate over the ranges in a collection of sets, in order,
  2698. /// starting from `from`.
  2699. static iter(sets, from = 0) {
  2700. return HeapCursor.from(sets).goto(from);
  2701. }
  2702. /// Iterate over two groups of sets, calling methods on `comparator`
  2703. /// to notify it of possible differences.
  2704. static compare(oldSets, newSets,
  2705. /// This indicates how the underlying data changed between these
  2706. /// ranges, and is needed to synchronize the iteration. `from` and
  2707. /// `to` are coordinates in the _new_ space, after these changes.
  2708. textDiff, comparator,
  2709. /// Can be used to ignore all non-point ranges, and points below
  2710. /// the given size. When -1, all ranges are compared.
  2711. minPointSize = -1) {
  2712. let a = oldSets.filter(set => set.maxPoint >= 500 /* BigPointSize */ ||
  2713. set != RangeSet.empty && newSets.indexOf(set) < 0 && set.maxPoint >= minPointSize);
  2714. let b = newSets.filter(set => set.maxPoint >= 500 /* BigPointSize */ ||
  2715. set != RangeSet.empty && oldSets.indexOf(set) < 0 && set.maxPoint >= minPointSize);
  2716. let sharedChunks = findSharedChunks(a, b);
  2717. let sideA = new SpanCursor(a, sharedChunks, minPointSize);
  2718. let sideB = new SpanCursor(b, sharedChunks, minPointSize);
  2719. textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
  2720. if (textDiff.empty && textDiff.length == 0)
  2721. compare(sideA, 0, sideB, 0, 0, comparator);
  2722. }
  2723. /// Iterate over a group of range sets at the same time, notifying
  2724. /// the iterator about the ranges covering every given piece of
  2725. /// content. Returns the open count (see
  2726. /// [`SpanIterator.span`](#rangeset.SpanIterator.span)) at the end
  2727. /// of the iteration.
  2728. static spans(sets, from, to, iterator,
  2729. /// When given and greater than -1, only points of at least this
  2730. /// size are taken into account.
  2731. minPointSize = -1) {
  2732. let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
  2733. let open = cursor.openStart;
  2734. for (;;) {
  2735. let curTo = Math.min(cursor.to, to);
  2736. if (cursor.point) {
  2737. iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open);
  2738. open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0);
  2739. }
  2740. else if (curTo > pos) {
  2741. iterator.span(pos, curTo, cursor.active, open);
  2742. open = cursor.openEnd(curTo);
  2743. }
  2744. if (cursor.to > to)
  2745. break;
  2746. pos = cursor.to;
  2747. cursor.next();
  2748. }
  2749. return open;
  2750. }
  2751. /// Create a range set for the given range or array of ranges. By
  2752. /// default, this expects the ranges to be _sorted_ (by start
  2753. /// position and, if two start at the same position,
  2754. /// `value.startSide`). You can pass `true` as second argument to
  2755. /// cause the method to sort them.
  2756. static of(ranges, sort = false) {
  2757. let build = new RangeSetBuilder();
  2758. for (let range of ranges instanceof Range ? [ranges] : sort ? ranges.slice().sort(cmpRange) : ranges)
  2759. build.add(range.from, range.to, range.value);
  2760. return build.finish();
  2761. }
  2762. }
  2763. /// The empty set of ranges.
  2764. RangeSet.empty = new RangeSet([], [], null, -1);
  2765. RangeSet.empty.nextLayer = RangeSet.empty;
  2766. /// A range set builder is a data structure that helps build up a
  2767. /// [range set](#rangeset.RangeSet) directly, without first allocating
  2768. /// an array of [`Range`](#rangeset.Range) objects.
  2769. class RangeSetBuilder {
  2770. /// Create an empty builder.
  2771. constructor() {
  2772. this.chunks = [];
  2773. this.chunkPos = [];
  2774. this.chunkStart = -1;
  2775. this.last = null;
  2776. this.lastFrom = -1000000000 /* Far */;
  2777. this.lastTo = -1000000000 /* Far */;
  2778. this.from = [];
  2779. this.to = [];
  2780. this.value = [];
  2781. this.maxPoint = -1;
  2782. this.setMaxPoint = -1;
  2783. this.nextLayer = null;
  2784. }
  2785. finishChunk(newArrays) {
  2786. this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
  2787. this.chunkPos.push(this.chunkStart);
  2788. this.chunkStart = -1;
  2789. this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
  2790. this.maxPoint = -1;
  2791. if (newArrays) {
  2792. this.from = [];
  2793. this.to = [];
  2794. this.value = [];
  2795. }
  2796. }
  2797. /// Add a range. Ranges should be added in sorted (by `from` and
  2798. /// `value.startSide`) order.
  2799. add(from, to, value) {
  2800. if (!this.addInner(from, to, value))
  2801. (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
  2802. }
  2803. /// @internal
  2804. addInner(from, to, value) {
  2805. let diff = from - this.lastTo || value.startSide - this.last.endSide;
  2806. if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
  2807. throw new Error("Ranges must be added sorted by `from` position and `startSide`");
  2808. if (diff < 0)
  2809. return false;
  2810. if (this.from.length == 250 /* ChunkSize */)
  2811. this.finishChunk(true);
  2812. if (this.chunkStart < 0)
  2813. this.chunkStart = from;
  2814. this.from.push(from - this.chunkStart);
  2815. this.to.push(to - this.chunkStart);
  2816. this.last = value;
  2817. this.lastFrom = from;
  2818. this.lastTo = to;
  2819. this.value.push(value);
  2820. if (value.point)
  2821. this.maxPoint = Math.max(this.maxPoint, to - from);
  2822. return true;
  2823. }
  2824. /// @internal
  2825. addChunk(from, chunk) {
  2826. if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
  2827. return false;
  2828. if (this.from.length)
  2829. this.finishChunk(true);
  2830. this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
  2831. this.chunks.push(chunk);
  2832. this.chunkPos.push(from);
  2833. let last = chunk.value.length - 1;
  2834. this.last = chunk.value[last];
  2835. this.lastFrom = chunk.from[last] + from;
  2836. this.lastTo = chunk.to[last] + from;
  2837. return true;
  2838. }
  2839. /// Finish the range set. Returns the new set. The builder can't be
  2840. /// used anymore after this has been called.
  2841. finish() { return this.finishInner(RangeSet.empty); }
  2842. /// @internal
  2843. finishInner(next) {
  2844. if (this.from.length)
  2845. this.finishChunk(false);
  2846. if (this.chunks.length == 0)
  2847. return next;
  2848. let result = new RangeSet(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
  2849. this.from = null; // Make sure further `add` calls produce errors
  2850. return result;
  2851. }
  2852. }
  2853. function findSharedChunks(a, b) {
  2854. let inA = new Map();
  2855. for (let set of a)
  2856. for (let i = 0; i < set.chunk.length; i++)
  2857. if (set.chunk[i].maxPoint < 500 /* BigPointSize */)
  2858. inA.set(set.chunk[i], set.chunkPos[i]);
  2859. let shared = new Set();
  2860. for (let set of b)
  2861. for (let i = 0; i < set.chunk.length; i++)
  2862. if (inA.get(set.chunk[i]) == set.chunkPos[i])
  2863. shared.add(set.chunk[i]);
  2864. return shared;
  2865. }
  2866. class LayerCursor {
  2867. constructor(layer, skip, minPoint, rank = 0) {
  2868. this.layer = layer;
  2869. this.skip = skip;
  2870. this.minPoint = minPoint;
  2871. this.rank = rank;
  2872. }
  2873. get startSide() { return this.value ? this.value.startSide : 0; }
  2874. get endSide() { return this.value ? this.value.endSide : 0; }
  2875. goto(pos, side = -1000000000 /* Far */) {
  2876. this.chunkIndex = this.rangeIndex = 0;
  2877. this.gotoInner(pos, side, false);
  2878. return this;
  2879. }
  2880. gotoInner(pos, side, forward) {
  2881. while (this.chunkIndex < this.layer.chunk.length) {
  2882. let next = this.layer.chunk[this.chunkIndex];
  2883. if (!(this.skip && this.skip.has(next) ||
  2884. this.layer.chunkEnd(this.chunkIndex) < pos ||
  2885. next.maxPoint < this.minPoint))
  2886. break;
  2887. this.chunkIndex++;
  2888. forward = false;
  2889. }
  2890. let rangeIndex = this.chunkIndex == this.layer.chunk.length ? 0
  2891. : this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], -1, side);
  2892. if (!forward || this.rangeIndex < rangeIndex)
  2893. this.rangeIndex = rangeIndex;
  2894. this.next();
  2895. }
  2896. forward(pos, side) {
  2897. if ((this.to - pos || this.endSide - side) < 0)
  2898. this.gotoInner(pos, side, true);
  2899. }
  2900. next() {
  2901. for (;;) {
  2902. if (this.chunkIndex == this.layer.chunk.length) {
  2903. this.from = this.to = 1000000000 /* Far */;
  2904. this.value = null;
  2905. break;
  2906. }
  2907. else {
  2908. let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
  2909. let from = chunkPos + chunk.from[this.rangeIndex];
  2910. this.from = from;
  2911. this.to = chunkPos + chunk.to[this.rangeIndex];
  2912. this.value = chunk.value[this.rangeIndex];
  2913. if (++this.rangeIndex == chunk.value.length) {
  2914. this.chunkIndex++;
  2915. if (this.skip) {
  2916. while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
  2917. this.chunkIndex++;
  2918. }
  2919. this.rangeIndex = 0;
  2920. }
  2921. if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
  2922. break;
  2923. }
  2924. }
  2925. }
  2926. nextChunk() {
  2927. this.chunkIndex++;
  2928. this.rangeIndex = 0;
  2929. this.next();
  2930. }
  2931. compare(other) {
  2932. return this.from - other.from || this.startSide - other.startSide || this.to - other.to || this.endSide - other.endSide;
  2933. }
  2934. }
  2935. class HeapCursor {
  2936. constructor(heap) {
  2937. this.heap = heap;
  2938. }
  2939. static from(sets, skip = null, minPoint = -1) {
  2940. let heap = [];
  2941. for (let i = 0; i < sets.length; i++) {
  2942. for (let cur = sets[i]; cur != RangeSet.empty; cur = cur.nextLayer) {
  2943. if (cur.maxPoint >= minPoint)
  2944. heap.push(new LayerCursor(cur, skip, minPoint, i));
  2945. }
  2946. }
  2947. return heap.length == 1 ? heap[0] : new HeapCursor(heap);
  2948. }
  2949. get startSide() { return this.value ? this.value.startSide : 0; }
  2950. goto(pos, side = -1000000000 /* Far */) {
  2951. for (let cur of this.heap)
  2952. cur.goto(pos, side);
  2953. for (let i = this.heap.length >> 1; i >= 0; i--)
  2954. heapBubble(this.heap, i);
  2955. this.next();
  2956. return this;
  2957. }
  2958. forward(pos, side) {
  2959. for (let cur of this.heap)
  2960. cur.forward(pos, side);
  2961. for (let i = this.heap.length >> 1; i >= 0; i--)
  2962. heapBubble(this.heap, i);
  2963. if ((this.to - pos || this.value.endSide - side) < 0)
  2964. this.next();
  2965. }
  2966. next() {
  2967. if (this.heap.length == 0) {
  2968. this.from = this.to = 1000000000 /* Far */;
  2969. this.value = null;
  2970. this.rank = -1;
  2971. }
  2972. else {
  2973. let top = this.heap[0];
  2974. this.from = top.from;
  2975. this.to = top.to;
  2976. this.value = top.value;
  2977. this.rank = top.rank;
  2978. if (top.value)
  2979. top.next();
  2980. heapBubble(this.heap, 0);
  2981. }
  2982. }
  2983. }
  2984. function heapBubble(heap, index) {
  2985. for (let cur = heap[index];;) {
  2986. let childIndex = (index << 1) + 1;
  2987. if (childIndex >= heap.length)
  2988. break;
  2989. let child = heap[childIndex];
  2990. if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
  2991. child = heap[childIndex + 1];
  2992. childIndex++;
  2993. }
  2994. if (cur.compare(child) < 0)
  2995. break;
  2996. heap[childIndex] = cur;
  2997. heap[index] = child;
  2998. index = childIndex;
  2999. }
  3000. }
  3001. class SpanCursor {
  3002. constructor(sets, skip, minPoint) {
  3003. this.minPoint = minPoint;
  3004. this.active = [];
  3005. this.activeTo = [];
  3006. this.activeRank = [];
  3007. this.minActive = -1;
  3008. // A currently active point range, if any
  3009. this.point = null;
  3010. this.pointFrom = 0;
  3011. this.pointRank = 0;
  3012. this.to = -1000000000 /* Far */;
  3013. this.endSide = 0;
  3014. this.openStart = -1;
  3015. this.cursor = HeapCursor.from(sets, skip, minPoint);
  3016. }
  3017. goto(pos, side = -1000000000 /* Far */) {
  3018. this.cursor.goto(pos, side);
  3019. this.active.length = this.activeTo.length = this.activeRank.length = 0;
  3020. this.minActive = -1;
  3021. this.to = pos;
  3022. this.endSide = side;
  3023. this.openStart = -1;
  3024. this.next();
  3025. return this;
  3026. }
  3027. forward(pos, side) {
  3028. while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
  3029. this.removeActive(this.minActive);
  3030. this.cursor.forward(pos, side);
  3031. }
  3032. removeActive(index) {
  3033. remove(this.active, index);
  3034. remove(this.activeTo, index);
  3035. remove(this.activeRank, index);
  3036. this.minActive = findMinIndex(this.active, this.activeTo);
  3037. }
  3038. addActive(trackOpen) {
  3039. let i = 0, { value, to, rank } = this.cursor;
  3040. while (i < this.activeRank.length && this.activeRank[i] <= rank)
  3041. i++;
  3042. insert(this.active, i, value);
  3043. insert(this.activeTo, i, to);
  3044. insert(this.activeRank, i, rank);
  3045. if (trackOpen)
  3046. insert(trackOpen, i, this.cursor.from);
  3047. this.minActive = findMinIndex(this.active, this.activeTo);
  3048. }
  3049. // After calling this, if `this.point` != null, the next range is a
  3050. // point. Otherwise, it's a regular range, covered by `this.active`.
  3051. next() {
  3052. let from = this.to;
  3053. this.point = null;
  3054. let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0;
  3055. for (;;) {
  3056. let a = this.minActive;
  3057. if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
  3058. if (this.activeTo[a] > from) {
  3059. this.to = this.activeTo[a];
  3060. this.endSide = this.active[a].endSide;
  3061. break;
  3062. }
  3063. this.removeActive(a);
  3064. if (trackOpen)
  3065. remove(trackOpen, a);
  3066. }
  3067. else if (!this.cursor.value) {
  3068. this.to = this.endSide = 1000000000 /* Far */;
  3069. break;
  3070. }
  3071. else if (this.cursor.from > from) {
  3072. this.to = this.cursor.from;
  3073. this.endSide = this.cursor.startSide;
  3074. break;
  3075. }
  3076. else {
  3077. let nextVal = this.cursor.value;
  3078. if (!nextVal.point) { // Opening a range
  3079. this.addActive(trackOpen);
  3080. this.cursor.next();
  3081. }
  3082. else { // New point
  3083. this.point = nextVal;
  3084. this.pointFrom = this.cursor.from;
  3085. this.pointRank = this.cursor.rank;
  3086. this.to = this.cursor.to;
  3087. this.endSide = nextVal.endSide;
  3088. if (this.cursor.from < from)
  3089. trackExtra = 1;
  3090. this.cursor.next();
  3091. if (this.to > from)
  3092. this.forward(this.to, this.endSide);
  3093. break;
  3094. }
  3095. }
  3096. }
  3097. if (trackOpen) {
  3098. let openStart = 0;
  3099. while (openStart < trackOpen.length && trackOpen[openStart] < from)
  3100. openStart++;
  3101. this.openStart = openStart + trackExtra;
  3102. }
  3103. }
  3104. activeForPoint(to) {
  3105. if (!this.active.length)
  3106. return this.active;
  3107. let active = [];
  3108. for (let i = 0; i < this.active.length; i++) {
  3109. if (this.activeRank[i] > this.pointRank)
  3110. break;
  3111. if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide > this.point.endSide)
  3112. active.push(this.active[i]);
  3113. }
  3114. return active;
  3115. }
  3116. openEnd(to) {
  3117. let open = 0;
  3118. while (open < this.activeTo.length && this.activeTo[open] > to)
  3119. open++;
  3120. return open;
  3121. }
  3122. }
  3123. function compare(a, startA, b, startB, length, comparator) {
  3124. a.goto(startA);
  3125. b.goto(startB);
  3126. let endB = startB + length;
  3127. let pos = startB, dPos = startB - startA;
  3128. for (;;) {
  3129. let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;
  3130. let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
  3131. if (a.point || b.point) {
  3132. if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point))))
  3133. comparator.comparePoint(pos, clipEnd, a.point, b.point);
  3134. }
  3135. else {
  3136. if (clipEnd > pos && !sameValues(a.active, b.active))
  3137. comparator.compareRange(pos, clipEnd, a.active, b.active);
  3138. }
  3139. if (end > endB)
  3140. break;
  3141. pos = end;
  3142. if (diff <= 0)
  3143. a.next();
  3144. if (diff >= 0)
  3145. b.next();
  3146. }
  3147. }
  3148. function sameValues(a, b) {
  3149. if (a.length != b.length)
  3150. return false;
  3151. for (let i = 0; i < a.length; i++)
  3152. if (a[i] != b[i] && !a[i].eq(b[i]))
  3153. return false;
  3154. return true;
  3155. }
  3156. function remove(array, index) {
  3157. for (let i = index, e = array.length - 1; i < e; i++)
  3158. array[i] = array[i + 1];
  3159. array.pop();
  3160. }
  3161. function insert(array, index, value) {
  3162. for (let i = array.length - 1; i >= index; i--)
  3163. array[i + 1] = array[i];
  3164. array[index] = value;
  3165. }
  3166. function findMinIndex(value, array) {
  3167. let found = -1, foundPos = 1000000000 /* Far */;
  3168. for (let i = 0; i < array.length; i++)
  3169. if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
  3170. found = i;
  3171. foundPos = array[i];
  3172. }
  3173. return found;
  3174. }
  3175. var base = {
  3176. 8: "Backspace",
  3177. 9: "Tab",
  3178. 10: "Enter",
  3179. 12: "NumLock",
  3180. 13: "Enter",
  3181. 16: "Shift",
  3182. 17: "Control",
  3183. 18: "Alt",
  3184. 20: "CapsLock",
  3185. 27: "Escape",
  3186. 32: " ",
  3187. 33: "PageUp",
  3188. 34: "PageDown",
  3189. 35: "End",
  3190. 36: "Home",
  3191. 37: "ArrowLeft",
  3192. 38: "ArrowUp",
  3193. 39: "ArrowRight",
  3194. 40: "ArrowDown",
  3195. 44: "PrintScreen",
  3196. 45: "Insert",
  3197. 46: "Delete",
  3198. 59: ";",
  3199. 61: "=",
  3200. 91: "Meta",
  3201. 92: "Meta",
  3202. 106: "*",
  3203. 107: "+",
  3204. 108: ",",
  3205. 109: "-",
  3206. 110: ".",
  3207. 111: "/",
  3208. 144: "NumLock",
  3209. 145: "ScrollLock",
  3210. 160: "Shift",
  3211. 161: "Shift",
  3212. 162: "Control",
  3213. 163: "Control",
  3214. 164: "Alt",
  3215. 165: "Alt",
  3216. 173: "-",
  3217. 186: ";",
  3218. 187: "=",
  3219. 188: ",",
  3220. 189: "-",
  3221. 190: ".",
  3222. 191: "/",
  3223. 192: "`",
  3224. 219: "[",
  3225. 220: "\\",
  3226. 221: "]",
  3227. 222: "'",
  3228. 229: "q"
  3229. };
  3230. var shift = {
  3231. 48: ")",
  3232. 49: "!",
  3233. 50: "@",
  3234. 51: "#",
  3235. 52: "$",
  3236. 53: "%",
  3237. 54: "^",
  3238. 55: "&",
  3239. 56: "*",
  3240. 57: "(",
  3241. 59: ":",
  3242. 61: "+",
  3243. 173: "_",
  3244. 186: ":",
  3245. 187: "+",
  3246. 188: "<",
  3247. 189: "_",
  3248. 190: ">",
  3249. 191: "?",
  3250. 192: "~",
  3251. 219: "{",
  3252. 220: "|",
  3253. 221: "}",
  3254. 222: "\"",
  3255. 229: "Q"
  3256. };
  3257. var chrome = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
  3258. var safari = typeof navigator != "undefined" && /Apple Computer/.test(navigator.vendor);
  3259. var gecko = typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
  3260. var mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
  3261. var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
  3262. var brokenModifierNames = chrome && (mac || +chrome[1] < 57) || gecko && mac;
  3263. // Fill in the digit keys
  3264. for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
  3265. // The function keys
  3266. for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
  3267. // And the alphabetic keys
  3268. for (var i = 65; i <= 90; i++) {
  3269. base[i] = String.fromCharCode(i + 32);
  3270. shift[i] = String.fromCharCode(i);
  3271. }
  3272. // For each code that doesn't have a shift-equivalent, copy the base name
  3273. for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
  3274. function keyName(event) {
  3275. // Don't trust event.key in Chrome when there are modifiers until
  3276. // they fix https://bugs.chromium.org/p/chromium/issues/detail?id=633838
  3277. var ignoreKey = brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) ||
  3278. (safari || ie) && event.shiftKey && event.key && event.key.length == 1;
  3279. var name = (!ignoreKey && event.key) ||
  3280. (event.shiftKey ? shift : base)[event.keyCode] ||
  3281. event.key || "Unidentified";
  3282. // Edge sometimes produces wrong names (Issue #3)
  3283. if (name == "Esc") name = "Escape";
  3284. if (name == "Del") name = "Delete";
  3285. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/
  3286. if (name == "Left") name = "ArrowLeft";
  3287. if (name == "Up") name = "ArrowUp";
  3288. if (name == "Right") name = "ArrowRight";
  3289. if (name == "Down") name = "ArrowDown";
  3290. return name
  3291. }
  3292. let [nav, doc] = typeof navigator != "undefined"
  3293. ? [navigator, document]
  3294. : [{ userAgent: "", vendor: "", platform: "" }, { documentElement: { style: {} } }];
  3295. const ie_edge = /Edge\/(\d+)/.exec(nav.userAgent);
  3296. const ie_upto10 = /MSIE \d/.test(nav.userAgent);
  3297. const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
  3298. const ie$1 = !!(ie_upto10 || ie_11up || ie_edge);
  3299. const gecko$1 = !ie$1 && /gecko\/(\d+)/i.test(nav.userAgent);
  3300. const chrome$1 = !ie$1 && /Chrome\/(\d+)/.exec(nav.userAgent);
  3301. const webkit = "webkitFontSmoothing" in doc.documentElement.style;
  3302. const safari$1 = !ie$1 && /Apple Computer/.test(nav.vendor);
  3303. var browser = {
  3304. mac: /Mac/.test(nav.platform),
  3305. ie: ie$1,
  3306. ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
  3307. gecko: gecko$1,
  3308. gecko_version: gecko$1 ? +(/Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
  3309. chrome: !!chrome$1,
  3310. chrome_version: chrome$1 ? +chrome$1[1] : 0,
  3311. ios: safari$1 && (/Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2),
  3312. android: /Android\b/.test(nav.userAgent),
  3313. webkit,
  3314. safari: safari$1,
  3315. webkit_version: webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
  3316. tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
  3317. };
  3318. function getSelection(root) {
  3319. return (root.getSelection ? root.getSelection() : document.getSelection());
  3320. }
  3321. // Work around Chrome issue https://bugs.chromium.org/p/chromium/issues/detail?id=447523
  3322. // (isCollapsed inappropriately returns true in shadow dom)
  3323. function selectionCollapsed(domSel) {
  3324. let collapsed = domSel.isCollapsed;
  3325. if (collapsed && browser.chrome && domSel.rangeCount && !domSel.getRangeAt(0).collapsed)
  3326. collapsed = false;
  3327. return collapsed;
  3328. }
  3329. function hasSelection(dom, selection) {
  3330. if (!selection.anchorNode)
  3331. return false;
  3332. try {
  3333. // Firefox will raise 'permission denied' errors when accessing
  3334. // properties of `sel.anchorNode` when it's in a generated CSS
  3335. // element.
  3336. return dom.contains(selection.anchorNode.nodeType == 3 ? selection.anchorNode.parentNode : selection.anchorNode);
  3337. }
  3338. catch (_) {
  3339. return false;
  3340. }
  3341. }
  3342. function clientRectsFor(dom) {
  3343. if (dom.nodeType == 3) {
  3344. let range = tempRange();
  3345. range.setEnd(dom, dom.nodeValue.length);
  3346. range.setStart(dom, 0);
  3347. return range.getClientRects();
  3348. }
  3349. else if (dom.nodeType == 1) {
  3350. return dom.getClientRects();
  3351. }
  3352. else {
  3353. return [];
  3354. }
  3355. }
  3356. // Scans forward and backward through DOM positions equivalent to the
  3357. // given one to see if the two are in the same place (i.e. after a
  3358. // text node vs at the end of that text node)
  3359. function isEquivalentPosition(node, off, targetNode, targetOff) {
  3360. return targetNode ? (scanFor(node, off, targetNode, targetOff, -1) ||
  3361. scanFor(node, off, targetNode, targetOff, 1)) : false;
  3362. }
  3363. function domIndex(node) {
  3364. for (var index = 0;; index++) {
  3365. node = node.previousSibling;
  3366. if (!node)
  3367. return index;
  3368. }
  3369. }
  3370. function scanFor(node, off, targetNode, targetOff, dir) {
  3371. for (;;) {
  3372. if (node == targetNode && off == targetOff)
  3373. return true;
  3374. if (off == (dir < 0 ? 0 : maxOffset(node))) {
  3375. if (node.nodeName == "DIV")
  3376. return false;
  3377. let parent = node.parentNode;
  3378. if (!parent || parent.nodeType != 1)
  3379. return false;
  3380. off = domIndex(node) + (dir < 0 ? 0 : 1);
  3381. node = parent;
  3382. }
  3383. else if (node.nodeType == 1) {
  3384. node = node.childNodes[off + (dir < 0 ? -1 : 0)];
  3385. off = dir < 0 ? maxOffset(node) : 0;
  3386. }
  3387. else {
  3388. return false;
  3389. }
  3390. }
  3391. }
  3392. function maxOffset(node) {
  3393. return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
  3394. }
  3395. function flattenRect(rect, left) {
  3396. let x = left ? rect.left : rect.right;
  3397. return { left: x, right: x, top: rect.top, bottom: rect.bottom };
  3398. }
  3399. function windowRect(win) {
  3400. return { left: 0, right: win.innerWidth,
  3401. top: 0, bottom: win.innerHeight };
  3402. }
  3403. const ScrollSpace = 5;
  3404. function scrollRectIntoView(dom, rect) {
  3405. let doc = dom.ownerDocument, win = doc.defaultView;
  3406. for (let cur = dom.parentNode; cur;) {
  3407. if (cur.nodeType == 1) { // Element
  3408. let bounding, top = cur == document.body;
  3409. if (top) {
  3410. bounding = windowRect(win);
  3411. }
  3412. else {
  3413. if (cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) {
  3414. cur = cur.parentNode;
  3415. continue;
  3416. }
  3417. let rect = cur.getBoundingClientRect();
  3418. // Make sure scrollbar width isn't included in the rectangle
  3419. bounding = { left: rect.left, right: rect.left + cur.clientWidth,
  3420. top: rect.top, bottom: rect.top + cur.clientHeight };
  3421. }
  3422. let moveX = 0, moveY = 0;
  3423. if (rect.top < bounding.top)
  3424. moveY = -(bounding.top - rect.top + ScrollSpace);
  3425. else if (rect.bottom > bounding.bottom)
  3426. moveY = rect.bottom - bounding.bottom + ScrollSpace;
  3427. if (rect.left < bounding.left)
  3428. moveX = -(bounding.left - rect.left + ScrollSpace);
  3429. else if (rect.right > bounding.right)
  3430. moveX = rect.right - bounding.right + ScrollSpace;
  3431. if (moveX || moveY) {
  3432. if (top) {
  3433. win.scrollBy(moveX, moveY);
  3434. }
  3435. else {
  3436. if (moveY) {
  3437. let start = cur.scrollTop;
  3438. cur.scrollTop += moveY;
  3439. moveY = cur.scrollTop - start;
  3440. }
  3441. if (moveX) {
  3442. let start = cur.scrollLeft;
  3443. cur.scrollLeft += moveX;
  3444. moveX = cur.scrollLeft - start;
  3445. }
  3446. rect = { left: rect.left - moveX, top: rect.top - moveY,
  3447. right: rect.right - moveX, bottom: rect.bottom - moveY };
  3448. }
  3449. }
  3450. if (top)
  3451. break;
  3452. cur = cur.parentNode;
  3453. }
  3454. else if (cur.nodeType == 11) { // A shadow root
  3455. cur = cur.host;
  3456. }
  3457. else {
  3458. break;
  3459. }
  3460. }
  3461. }
  3462. class DOMSelection {
  3463. constructor() {
  3464. this.anchorNode = null;
  3465. this.anchorOffset = 0;
  3466. this.focusNode = null;
  3467. this.focusOffset = 0;
  3468. }
  3469. eq(domSel) {
  3470. return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset &&
  3471. this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
  3472. }
  3473. set(domSel) {
  3474. this.anchorNode = domSel.anchorNode;
  3475. this.anchorOffset = domSel.anchorOffset;
  3476. this.focusNode = domSel.focusNode;
  3477. this.focusOffset = domSel.focusOffset;
  3478. }
  3479. }
  3480. let preventScrollSupported = null;
  3481. // Feature-detects support for .focus({preventScroll: true}), and uses
  3482. // a fallback kludge when not supported.
  3483. function focusPreventScroll(dom) {
  3484. if (dom.setActive)
  3485. return dom.setActive(); // in IE
  3486. if (preventScrollSupported)
  3487. return dom.focus(preventScrollSupported);
  3488. let stack = [];
  3489. for (let cur = dom; cur; cur = cur.parentNode) {
  3490. stack.push(cur, cur.scrollTop, cur.scrollLeft);
  3491. if (cur == cur.ownerDocument)
  3492. break;
  3493. }
  3494. dom.focus(preventScrollSupported == null ? {
  3495. get preventScroll() {
  3496. preventScrollSupported = { preventScroll: true };
  3497. return true;
  3498. }
  3499. } : undefined);
  3500. if (!preventScrollSupported) {
  3501. preventScrollSupported = false;
  3502. for (let i = 0; i < stack.length;) {
  3503. let elt = stack[i++], top = stack[i++], left = stack[i++];
  3504. if (elt.scrollTop != top)
  3505. elt.scrollTop = top;
  3506. if (elt.scrollLeft != left)
  3507. elt.scrollLeft = left;
  3508. }
  3509. }
  3510. }
  3511. let scratchRange;
  3512. function tempRange() { return scratchRange || (scratchRange = document.createRange()); }
  3513. class DOMPos {
  3514. constructor(node, offset, precise = true) {
  3515. this.node = node;
  3516. this.offset = offset;
  3517. this.precise = precise;
  3518. }
  3519. static before(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom), precise); }
  3520. static after(dom, precise) { return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise); }
  3521. }
  3522. const none$1 = [];
  3523. class ContentView {
  3524. constructor() {
  3525. this.parent = null;
  3526. this.dom = null;
  3527. this.dirty = 2 /* Node */;
  3528. }
  3529. get editorView() {
  3530. if (!this.parent)
  3531. throw new Error("Accessing view in orphan content view");
  3532. return this.parent.editorView;
  3533. }
  3534. get overrideDOMText() { return null; }
  3535. get posAtStart() {
  3536. return this.parent ? this.parent.posBefore(this) : 0;
  3537. }
  3538. get posAtEnd() {
  3539. return this.posAtStart + this.length;
  3540. }
  3541. posBefore(view) {
  3542. let pos = this.posAtStart;
  3543. for (let child of this.children) {
  3544. if (child == view)
  3545. return pos;
  3546. pos += child.length + child.breakAfter;
  3547. }
  3548. throw new RangeError("Invalid child in posBefore");
  3549. }
  3550. posAfter(view) {
  3551. return this.posBefore(view) + view.length;
  3552. }
  3553. // Will return a rectangle directly before (when side < 0), after
  3554. // (side > 0) or directly on (when the browser supports it) the
  3555. // given position.
  3556. coordsAt(_pos, _side) { return null; }
  3557. sync(track) {
  3558. if (this.dirty & 2 /* Node */) {
  3559. let parent = this.dom, pos = null;
  3560. for (let child of this.children) {
  3561. if (child.dirty) {
  3562. let next = pos ? pos.nextSibling : parent.firstChild;
  3563. if (next && !child.dom && !ContentView.get(next))
  3564. child.reuseDOM(next);
  3565. child.sync(track);
  3566. child.dirty = 0 /* Not */;
  3567. }
  3568. if (track && track.node == parent && pos != child.dom)
  3569. track.written = true;
  3570. syncNodeInto(parent, pos, child.dom);
  3571. pos = child.dom;
  3572. }
  3573. let next = pos ? pos.nextSibling : parent.firstChild;
  3574. if (next && track && track.node == parent)
  3575. track.written = true;
  3576. while (next)
  3577. next = rm(next);
  3578. }
  3579. else if (this.dirty & 1 /* Child */) {
  3580. for (let child of this.children)
  3581. if (child.dirty) {
  3582. child.sync(track);
  3583. child.dirty = 0 /* Not */;
  3584. }
  3585. }
  3586. }
  3587. reuseDOM(_dom) { return false; }
  3588. localPosFromDOM(node, offset) {
  3589. let after;
  3590. if (node == this.dom) {
  3591. after = this.dom.childNodes[offset];
  3592. }
  3593. else {
  3594. let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
  3595. for (;;) {
  3596. let parent = node.parentNode;
  3597. if (parent == this.dom)
  3598. break;
  3599. if (bias == 0 && parent.firstChild != parent.lastChild) {
  3600. if (node == parent.firstChild)
  3601. bias = -1;
  3602. else
  3603. bias = 1;
  3604. }
  3605. node = parent;
  3606. }
  3607. if (bias < 0)
  3608. after = node;
  3609. else
  3610. after = node.nextSibling;
  3611. }
  3612. if (after == this.dom.firstChild)
  3613. return 0;
  3614. while (after && !ContentView.get(after))
  3615. after = after.nextSibling;
  3616. if (!after)
  3617. return this.length;
  3618. for (let i = 0, pos = 0;; i++) {
  3619. let child = this.children[i];
  3620. if (child.dom == after)
  3621. return pos;
  3622. pos += child.length + child.breakAfter;
  3623. }
  3624. }
  3625. domBoundsAround(from, to, offset = 0) {
  3626. let fromI = -1, fromStart = -1, toI = -1, toEnd = -1;
  3627. for (let i = 0, pos = offset; i < this.children.length; i++) {
  3628. let child = this.children[i], end = pos + child.length;
  3629. if (pos < from && end > to)
  3630. return child.domBoundsAround(from, to, pos);
  3631. if (end >= from && fromI == -1) {
  3632. fromI = i;
  3633. fromStart = pos;
  3634. }
  3635. if (end >= to && end != pos && toI == -1) {
  3636. toI = i;
  3637. toEnd = end;
  3638. break;
  3639. }
  3640. pos = end + child.breakAfter;
  3641. }
  3642. return { from: fromStart, to: toEnd < 0 ? offset + this.length : toEnd, startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild, endDOM: toI < this.children.length - 1 && toI >= 0 ? this.children[toI + 1].dom : null };
  3643. }
  3644. markDirty(andParent = false) {
  3645. if (this.dirty & 2 /* Node */)
  3646. return;
  3647. this.dirty |= 2 /* Node */;
  3648. this.markParentsDirty(andParent);
  3649. }
  3650. markParentsDirty(childList) {
  3651. for (let parent = this.parent; parent; parent = parent.parent) {
  3652. if (childList)
  3653. parent.dirty |= 2 /* Node */;
  3654. if (parent.dirty & 1 /* Child */)
  3655. return;
  3656. parent.dirty |= 1 /* Child */;
  3657. childList = false;
  3658. }
  3659. }
  3660. setParent(parent) {
  3661. if (this.parent != parent) {
  3662. this.parent = parent;
  3663. if (this.dirty)
  3664. this.markParentsDirty(true);
  3665. }
  3666. }
  3667. setDOM(dom) {
  3668. this.dom = dom;
  3669. dom.cmView = this;
  3670. }
  3671. get rootView() {
  3672. for (let v = this;;) {
  3673. let parent = v.parent;
  3674. if (!parent)
  3675. return v;
  3676. v = parent;
  3677. }
  3678. }
  3679. replaceChildren(from, to, children = none$1) {
  3680. this.markDirty();
  3681. for (let i = from; i < to; i++)
  3682. this.children[i].parent = null;
  3683. this.children.splice(from, to - from, ...children);
  3684. for (let i = 0; i < children.length; i++)
  3685. children[i].setParent(this);
  3686. }
  3687. ignoreMutation(_rec) { return false; }
  3688. ignoreEvent(_event) { return false; }
  3689. childCursor(pos = this.length) {
  3690. return new ChildCursor(this.children, pos, this.children.length);
  3691. }
  3692. childPos(pos, bias = 1) {
  3693. return this.childCursor().findPos(pos, bias);
  3694. }
  3695. toString() {
  3696. let name = this.constructor.name.replace("View", "");
  3697. return name + (this.children.length ? "(" + this.children.join() + ")" :
  3698. this.length ? "[" + (name == "Text" ? this.text : this.length) + "]" : "") +
  3699. (this.breakAfter ? "#" : "");
  3700. }
  3701. static get(node) { return node.cmView; }
  3702. }
  3703. ContentView.prototype.breakAfter = 0;
  3704. // Remove a DOM node and return its next sibling.
  3705. function rm(dom) {
  3706. let next = dom.nextSibling;
  3707. dom.parentNode.removeChild(dom);
  3708. return next;
  3709. }
  3710. function syncNodeInto(parent, after, dom) {
  3711. let next = after ? after.nextSibling : parent.firstChild;
  3712. if (dom.parentNode == parent)
  3713. while (next != dom)
  3714. next = rm(next);
  3715. else
  3716. parent.insertBefore(dom, next);
  3717. }
  3718. class ChildCursor {
  3719. constructor(children, pos, i) {
  3720. this.children = children;
  3721. this.pos = pos;
  3722. this.i = i;
  3723. this.off = 0;
  3724. }
  3725. findPos(pos, bias = 1) {
  3726. for (;;) {
  3727. if (pos > this.pos || pos == this.pos &&
  3728. (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
  3729. this.off = pos - this.pos;
  3730. return this;
  3731. }
  3732. let next = this.children[--this.i];
  3733. this.pos -= next.length + next.breakAfter;
  3734. }
  3735. }
  3736. }
  3737. const none$1$1 = [];
  3738. class InlineView extends ContentView {
  3739. /// Return true when this view is equivalent to `other` and can take
  3740. /// on its role.
  3741. become(_other) { return false; }
  3742. // When this is a zero-length view with a side, this should return a
  3743. // negative number to indicate it is before its position, or a
  3744. // positive number when after its position.
  3745. getSide() { return 0; }
  3746. }
  3747. InlineView.prototype.children = none$1$1;
  3748. const MaxJoinLen = 256;
  3749. class TextView extends InlineView {
  3750. constructor(text) {
  3751. super();
  3752. this.text = text;
  3753. }
  3754. get length() { return this.text.length; }
  3755. createDOM(textDOM) {
  3756. this.setDOM(textDOM || document.createTextNode(this.text));
  3757. }
  3758. sync(track) {
  3759. if (!this.dom)
  3760. this.createDOM();
  3761. if (this.dom.nodeValue != this.text) {
  3762. if (track && track.node == this.dom)
  3763. track.written = true;
  3764. this.dom.nodeValue = this.text;
  3765. }
  3766. }
  3767. reuseDOM(dom) {
  3768. if (dom.nodeType != 3)
  3769. return false;
  3770. this.createDOM(dom);
  3771. return true;
  3772. }
  3773. merge(from, to, source) {
  3774. if (source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen))
  3775. return false;
  3776. this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
  3777. this.markDirty();
  3778. return true;
  3779. }
  3780. slice(from) {
  3781. return new TextView(this.text.slice(from));
  3782. }
  3783. localPosFromDOM(node, offset) {
  3784. return node == this.dom ? offset : offset ? this.text.length : 0;
  3785. }
  3786. domAtPos(pos) { return new DOMPos(this.dom, pos); }
  3787. domBoundsAround(_from, _to, offset) {
  3788. return { from: offset, to: offset + this.length, startDOM: this.dom, endDOM: this.dom.nextSibling };
  3789. }
  3790. coordsAt(pos, side) {
  3791. return textCoords(this.dom, pos, side);
  3792. }
  3793. }
  3794. class MarkView extends InlineView {
  3795. constructor(mark, children = [], length = 0) {
  3796. super();
  3797. this.mark = mark;
  3798. this.children = children;
  3799. this.length = length;
  3800. for (let ch of children)
  3801. ch.setParent(this);
  3802. }
  3803. createDOM() {
  3804. let dom = document.createElement(this.mark.tagName);
  3805. if (this.mark.class)
  3806. dom.className = this.mark.class;
  3807. if (this.mark.attrs)
  3808. for (let name in this.mark.attrs)
  3809. dom.setAttribute(name, this.mark.attrs[name]);
  3810. this.setDOM(dom);
  3811. }
  3812. sync(track) {
  3813. if (!this.dom)
  3814. this.createDOM();
  3815. super.sync(track);
  3816. }
  3817. merge(from, to, source, openStart, openEnd) {
  3818. if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) ||
  3819. (from && openStart <= 0) || (to < this.length && openEnd <= 0)))
  3820. return false;
  3821. mergeInlineChildren(this, from, to, source ? source.children : none$1$1, openStart - 1, openEnd - 1);
  3822. this.markDirty();
  3823. return true;
  3824. }
  3825. slice(from) {
  3826. return new MarkView(this.mark, sliceInlineChildren(this.children, from), this.length - from);
  3827. }
  3828. domAtPos(pos) {
  3829. return inlineDOMAtPos(this.dom, this.children, pos);
  3830. }
  3831. coordsAt(pos, side) {
  3832. return coordsInChildren(this, pos, side);
  3833. }
  3834. }
  3835. function textCoords(text, pos, side) {
  3836. let length = text.nodeValue.length;
  3837. if (pos > length)
  3838. pos = length;
  3839. let from = pos, to = pos, flatten = 0;
  3840. if (pos == 0 && side < 0 || pos == length && side >= 0) {
  3841. if (!(browser.chrome || browser.gecko)) { // These browsers reliably return valid rectangles for empty ranges
  3842. if (pos) {
  3843. from--;
  3844. flatten = 1;
  3845. } // FIXME this is wrong in RTL text
  3846. else {
  3847. to++;
  3848. flatten = -1;
  3849. }
  3850. }
  3851. }
  3852. else {
  3853. if (side < 0)
  3854. from--;
  3855. else
  3856. to++;
  3857. }
  3858. let range = tempRange();
  3859. range.setEnd(text, to);
  3860. range.setStart(text, from);
  3861. let rects = range.getClientRects(), rect = rects[(flatten ? flatten < 0 : side >= 0) ? 0 : rects.length - 1];
  3862. if (browser.safari && !flatten && rect.width == 0)
  3863. rect = Array.prototype.find.call(rects, r => r.width) || rect;
  3864. return flatten ? flattenRect(rect, flatten < 0) : rect;
  3865. }
  3866. // Also used for collapsed ranges that don't have a placeholder widget!
  3867. class WidgetView extends InlineView {
  3868. constructor(widget, length, side) {
  3869. super();
  3870. this.widget = widget;
  3871. this.length = length;
  3872. this.side = side;
  3873. }
  3874. static create(widget, length, side) {
  3875. return new (widget.customView || WidgetView)(widget, length, side);
  3876. }
  3877. slice(from) { return WidgetView.create(this.widget, this.length - from, this.side); }
  3878. sync() {
  3879. if (!this.dom || !this.widget.updateDOM(this.dom)) {
  3880. this.setDOM(this.widget.toDOM(this.editorView));
  3881. this.dom.contentEditable = "false";
  3882. }
  3883. }
  3884. getSide() { return this.side; }
  3885. merge(from, to, source, openStart, openEnd) {
  3886. if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) ||
  3887. from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
  3888. return false;
  3889. this.length = from + (source ? source.length : 0) + (this.length - to);
  3890. return true;
  3891. }
  3892. become(other) {
  3893. if (other.length == this.length && other instanceof WidgetView && other.side == this.side) {
  3894. if (this.widget.constructor == other.widget.constructor) {
  3895. if (!this.widget.eq(other.widget))
  3896. this.markDirty(true);
  3897. this.widget = other.widget;
  3898. return true;
  3899. }
  3900. }
  3901. return false;
  3902. }
  3903. ignoreMutation() { return true; }
  3904. ignoreEvent(event) { return this.widget.ignoreEvent(event); }
  3905. get overrideDOMText() {
  3906. if (this.length == 0)
  3907. return Text.empty;
  3908. let top = this;
  3909. while (top.parent)
  3910. top = top.parent;
  3911. let view = top.editorView, text = view && view.state.doc, start = this.posAtStart;
  3912. return text ? text.slice(start, start + this.length) : Text.empty;
  3913. }
  3914. domAtPos(pos) {
  3915. return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  3916. }
  3917. domBoundsAround() { return null; }
  3918. coordsAt(pos, side) {
  3919. let rects = this.dom.getClientRects(), rect = null;
  3920. for (let i = pos > 0 ? rects.length - 1 : 0;; i += (pos > 0 ? -1 : 1)) {
  3921. rect = rects[i];
  3922. if (pos > 0 ? i == 0 : i == rects.length - 1 || rect.top < rect.bottom)
  3923. break;
  3924. }
  3925. return (pos == 0 && side > 0 || pos == this.length && side <= 0) ? rect : flattenRect(rect, pos == 0);
  3926. }
  3927. }
  3928. class CompositionView extends WidgetView {
  3929. domAtPos(pos) { return new DOMPos(this.widget.text, pos); }
  3930. sync() { if (!this.dom)
  3931. this.setDOM(this.widget.toDOM()); }
  3932. localPosFromDOM(node, offset) {
  3933. return !offset ? 0 : node.nodeType == 3 ? Math.min(offset, this.length) : this.length;
  3934. }
  3935. ignoreMutation() { return false; }
  3936. get overrideDOMText() { return null; }
  3937. coordsAt(pos, side) { return textCoords(this.widget.text, pos, side); }
  3938. }
  3939. function mergeInlineChildren(parent, from, to, elts, openStart, openEnd) {
  3940. let cur = parent.childCursor();
  3941. let { i: toI, off: toOff } = cur.findPos(to, 1);
  3942. let { i: fromI, off: fromOff } = cur.findPos(from, -1);
  3943. let dLen = from - to;
  3944. for (let view of elts)
  3945. dLen += view.length;
  3946. parent.length += dLen;
  3947. let { children } = parent;
  3948. // Both from and to point into the same text view
  3949. if (fromI == toI && fromOff) {
  3950. let start = children[fromI];
  3951. // Maybe just update that view and be done
  3952. if (elts.length == 1 && start.merge(fromOff, toOff, elts[0], openStart, openEnd))
  3953. return;
  3954. if (elts.length == 0) {
  3955. start.merge(fromOff, toOff, null, openStart, openEnd);
  3956. return;
  3957. }
  3958. // Otherwise split it, so that we don't have to worry about aliasing front/end afterwards
  3959. let after = start.slice(toOff);
  3960. if (after.merge(0, 0, elts[elts.length - 1], 0, openEnd))
  3961. elts[elts.length - 1] = after;
  3962. else
  3963. elts.push(after);
  3964. toI++;
  3965. openEnd = toOff = 0;
  3966. }
  3967. // Make sure start and end positions fall on node boundaries
  3968. // (fromOff/toOff are no longer used after this), and that if the
  3969. // start or end of the elts can be merged with adjacent nodes,
  3970. // this is done
  3971. if (toOff) {
  3972. let end = children[toI];
  3973. if (elts.length && end.merge(0, toOff, elts[elts.length - 1], 0, openEnd)) {
  3974. elts.pop();
  3975. openEnd = 0;
  3976. }
  3977. else {
  3978. end.merge(0, toOff, null, 0, 0);
  3979. }
  3980. }
  3981. else if (toI < children.length && elts.length &&
  3982. children[toI].merge(0, 0, elts[elts.length - 1], 0, openEnd)) {
  3983. elts.pop();
  3984. openEnd = 0;
  3985. }
  3986. if (fromOff) {
  3987. let start = children[fromI];
  3988. if (elts.length && start.merge(fromOff, start.length, elts[0], openStart, 0)) {
  3989. elts.shift();
  3990. openStart = 0;
  3991. }
  3992. else {
  3993. start.merge(fromOff, start.length, null, 0, 0);
  3994. }
  3995. fromI++;
  3996. }
  3997. else if (fromI && elts.length) {
  3998. let end = children[fromI - 1];
  3999. if (end.merge(end.length, end.length, elts[0], openStart, 0)) {
  4000. elts.shift();
  4001. openStart = 0;
  4002. }
  4003. }
  4004. // Then try to merge any mergeable nodes at the start and end of
  4005. // the changed range
  4006. while (fromI < toI && elts.length && children[toI - 1].become(elts[elts.length - 1])) {
  4007. elts.pop();
  4008. toI--;
  4009. openEnd = 0;
  4010. }
  4011. while (fromI < toI && elts.length && children[fromI].become(elts[0])) {
  4012. elts.shift();
  4013. fromI++;
  4014. openStart = 0;
  4015. }
  4016. if (!elts.length && fromI && toI < children.length && openStart && openEnd &&
  4017. children[toI].merge(0, 0, children[fromI - 1], openStart, openEnd))
  4018. fromI--;
  4019. // And if anything remains, splice the child array to insert the new elts
  4020. if (elts.length || fromI != toI)
  4021. parent.replaceChildren(fromI, toI, elts);
  4022. }
  4023. function sliceInlineChildren(children, from) {
  4024. let result = [], off = 0;
  4025. for (let elt of children) {
  4026. let end = off + elt.length;
  4027. if (end > from)
  4028. result.push(off < from ? elt.slice(from - off) : elt);
  4029. off = end;
  4030. }
  4031. return result;
  4032. }
  4033. function inlineDOMAtPos(dom, children, pos) {
  4034. let i = 0;
  4035. for (let off = 0; i < children.length; i++) {
  4036. let child = children[i], end = off + child.length;
  4037. if (end == off && child.getSide() <= 0)
  4038. continue;
  4039. if (pos > off && pos < end && child.dom.parentNode == dom)
  4040. return child.domAtPos(pos - off);
  4041. if (pos <= off)
  4042. break;
  4043. off = end;
  4044. }
  4045. for (; i > 0; i--) {
  4046. let before = children[i - 1].dom;
  4047. if (before.parentNode == dom)
  4048. return DOMPos.after(before);
  4049. }
  4050. return new DOMPos(dom, 0);
  4051. }
  4052. // Assumes `view`, if a mark view, has precisely 1 child.
  4053. function joinInlineInto(parent, view, open) {
  4054. let last, { children } = parent;
  4055. if (open > 0 && view instanceof MarkView && children.length &&
  4056. (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) {
  4057. joinInlineInto(last, view.children[0], open - 1);
  4058. }
  4059. else {
  4060. children.push(view);
  4061. view.setParent(parent);
  4062. }
  4063. parent.length += view.length;
  4064. }
  4065. function coordsInChildren(view, pos, side) {
  4066. for (let off = 0, i = 0; i < view.children.length; i++) {
  4067. let child = view.children[i], end = off + child.length;
  4068. if (end == off && child.getSide() <= 0)
  4069. continue;
  4070. if (side <= 0 || end == view.length ? end >= pos : end > pos)
  4071. return child.coordsAt(pos - off, side);
  4072. off = end;
  4073. }
  4074. return (view.dom.lastChild || view.dom).getBoundingClientRect();
  4075. }
  4076. function combineAttrs(source, target) {
  4077. for (let name in source) {
  4078. if (name == "class" && target.class)
  4079. target.class += " " + source.class;
  4080. else if (name == "style" && target.style)
  4081. target.style += ";" + source.style;
  4082. else
  4083. target[name] = source[name];
  4084. }
  4085. return target;
  4086. }
  4087. function attrsEq(a, b) {
  4088. if (a == b)
  4089. return true;
  4090. if (!a || !b)
  4091. return false;
  4092. let keysA = Object.keys(a), keysB = Object.keys(b);
  4093. if (keysA.length != keysB.length)
  4094. return false;
  4095. for (let key of keysA) {
  4096. if (keysB.indexOf(key) == -1 || a[key] !== b[key])
  4097. return false;
  4098. }
  4099. return true;
  4100. }
  4101. function updateAttrs(dom, prev, attrs) {
  4102. if (prev)
  4103. for (let name in prev)
  4104. if (!(attrs && name in attrs))
  4105. dom.removeAttribute(name);
  4106. if (attrs)
  4107. for (let name in attrs)
  4108. if (!(prev && prev[name] == attrs[name]))
  4109. dom.setAttribute(name, attrs[name]);
  4110. }
  4111. /// Widgets added to the content are described by subclasses of this
  4112. /// class. Using a description object like that makes it possible to
  4113. /// delay creating of the DOM structure for a widget until it is
  4114. /// needed, and to avoid redrawing widgets even when the decorations
  4115. /// that define them are recreated.
  4116. class WidgetType {
  4117. /// Compare this instance to another instance of the same type.
  4118. /// (TypeScript can't express this, but only instances of the same
  4119. /// specific class will be passed to this method.) This is used to
  4120. /// avoid redrawing widgets when they are replaced by a new
  4121. /// decoration of the same type. The default implementation just
  4122. /// returns `false`, which will cause new instances of the widget to
  4123. /// always be redrawn.
  4124. eq(_widget) { return false; }
  4125. /// Update a DOM element created by a widget of the same type (but
  4126. /// different, non-`eq` content) to reflect this widget. May return
  4127. /// true to indicate that it could update, false to indicate it
  4128. /// couldn't (in which case the widget will be redrawn). The default
  4129. /// implementation just returns false.
  4130. updateDOM(_dom) { return false; }
  4131. /// @internal
  4132. compare(other) {
  4133. return this == other || this.constructor == other.constructor && this.eq(other);
  4134. }
  4135. /// The estimated height this widget will have, to be used when
  4136. /// estimating the height of content that hasn't been drawn. May
  4137. /// return -1 to indicate you don't know. The default implementation
  4138. /// returns -1.
  4139. get estimatedHeight() { return -1; }
  4140. /// Can be used to configure which kinds of events inside the widget
  4141. /// should be ignored by the editor. The default is to ignore all
  4142. /// events.
  4143. ignoreEvent(_event) { return true; }
  4144. //// @internal
  4145. get customView() { return null; }
  4146. }
  4147. /// The different types of blocks that can occur in an editor view.
  4148. var BlockType;
  4149. (function (BlockType) {
  4150. /// A line of text.
  4151. BlockType[BlockType["Text"] = 0] = "Text";
  4152. /// A block widget associated with the position after it.
  4153. BlockType[BlockType["WidgetBefore"] = 1] = "WidgetBefore";
  4154. /// A block widget associated with the position before it.
  4155. BlockType[BlockType["WidgetAfter"] = 2] = "WidgetAfter";
  4156. /// A block widget [replacing](#view.Decoration^replace) a range of content.
  4157. BlockType[BlockType["WidgetRange"] = 3] = "WidgetRange";
  4158. })(BlockType || (BlockType = {}));
  4159. /// A decoration provides information on how to draw or style a piece
  4160. /// of content. You'll usually use it wrapped in a
  4161. /// [`Range`](#rangeset.Range), which adds a start and end position.
  4162. class Decoration extends RangeValue {
  4163. /// @internal
  4164. constructor(
  4165. /// @internal
  4166. startSide,
  4167. /// @internal
  4168. endSide,
  4169. /// @internal
  4170. widget,
  4171. /// The config object used to create this decoration. You can
  4172. /// include additional properties in there to store metadata about
  4173. /// your decoration.
  4174. spec) {
  4175. super();
  4176. this.startSide = startSide;
  4177. this.endSide = endSide;
  4178. this.widget = widget;
  4179. this.spec = spec;
  4180. }
  4181. /// @internal
  4182. get heightRelevant() { return false; }
  4183. /// Create a mark decoration, which influences the styling of the
  4184. /// content in its range. Nested mark decorations will cause nested
  4185. /// DOM elements to be created. Nesting order is determined by
  4186. /// precedence of the [facet](#view.EditorView^decorations) or
  4187. /// (below the facet-provided decorations) [view
  4188. /// plugin](#view.PluginSpec.decorations). Such elements are split
  4189. /// on line boundaries and on the boundaries of higher-precedence
  4190. /// decorations.
  4191. static mark(spec) {
  4192. return new MarkDecoration(spec);
  4193. }
  4194. /// Create a widget decoration, which adds an element at the given
  4195. /// position.
  4196. static widget(spec) {
  4197. let side = spec.side || 0;
  4198. if (spec.block)
  4199. side += (200000000 /* BigBlock */ + 1) * (side > 0 ? 1 : -1);
  4200. return new PointDecoration(spec, side, side, !!spec.block, spec.widget || null, false);
  4201. }
  4202. /// Create a replace decoration which replaces the given range with
  4203. /// a widget, or simply hides it.
  4204. static replace(spec) {
  4205. let block = !!spec.block;
  4206. let { start, end } = getInclusive(spec);
  4207. let startSide = block ? -200000000 /* BigBlock */ * (start ? 2 : 1) : 100000000 /* BigInline */ * (start ? -1 : 1);
  4208. let endSide = block ? 200000000 /* BigBlock */ * (end ? 2 : 1) : 100000000 /* BigInline */ * (end ? 1 : -1);
  4209. return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
  4210. }
  4211. /// Create a line decoration, which can add DOM attributes to the
  4212. /// line starting at the given position.
  4213. static line(spec) {
  4214. return new LineDecoration(spec);
  4215. }
  4216. /// Build a [`DecorationSet`](#view.DecorationSet) from the given
  4217. /// decorated range or ranges. If the ranges aren't already sorted,
  4218. /// pass `true` for `sort` to make the library sort them for you.
  4219. static set(of, sort = false) {
  4220. return RangeSet.of(of, sort);
  4221. }
  4222. /// @internal
  4223. hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : false; }
  4224. }
  4225. /// The empty set of decorations.
  4226. Decoration.none = RangeSet.empty;
  4227. class MarkDecoration extends Decoration {
  4228. constructor(spec) {
  4229. let { start, end } = getInclusive(spec);
  4230. super(100000000 /* BigInline */ * (start ? -1 : 1), 100000000 /* BigInline */ * (end ? 1 : -1), null, spec);
  4231. this.tagName = spec.tagName || "span";
  4232. this.class = spec.class || "";
  4233. this.attrs = spec.attributes || null;
  4234. }
  4235. eq(other) {
  4236. return this == other ||
  4237. other instanceof MarkDecoration &&
  4238. this.tagName == other.tagName &&
  4239. this.class == other.class &&
  4240. attrsEq(this.attrs, other.attrs);
  4241. }
  4242. range(from, to = from) {
  4243. if (from >= to)
  4244. throw new RangeError("Mark decorations may not be empty");
  4245. return super.range(from, to);
  4246. }
  4247. }
  4248. MarkDecoration.prototype.point = false;
  4249. class LineDecoration extends Decoration {
  4250. constructor(spec) {
  4251. super(-100000000 /* BigInline */, -100000000 /* BigInline */, null, spec);
  4252. }
  4253. eq(other) {
  4254. return other instanceof LineDecoration && attrsEq(this.spec.attributes, other.spec.attributes);
  4255. }
  4256. range(from, to = from) {
  4257. if (to != from)
  4258. throw new RangeError("Line decoration ranges must be zero-length");
  4259. return super.range(from, to);
  4260. }
  4261. }
  4262. LineDecoration.prototype.mapMode = MapMode.TrackBefore;
  4263. LineDecoration.prototype.point = true;
  4264. class PointDecoration extends Decoration {
  4265. constructor(spec, startSide, endSide, block, widget, isReplace) {
  4266. super(startSide, endSide, widget, spec);
  4267. this.block = block;
  4268. this.isReplace = isReplace;
  4269. this.mapMode = !block ? MapMode.TrackDel : startSide < 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
  4270. }
  4271. // Only relevant when this.block == true
  4272. get type() {
  4273. return this.startSide < this.endSide ? BlockType.WidgetRange
  4274. : this.startSide < 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
  4275. }
  4276. get heightRelevant() { return this.block || !!this.widget && this.widget.estimatedHeight >= 5; }
  4277. eq(other) {
  4278. return other instanceof PointDecoration &&
  4279. widgetsEq(this.widget, other.widget) &&
  4280. this.block == other.block &&
  4281. this.startSide == other.startSide && this.endSide == other.endSide;
  4282. }
  4283. range(from, to = from) {
  4284. if (this.isReplace && (from > to || (from == to && this.startSide > 0 && this.endSide < 0)))
  4285. throw new RangeError("Invalid range for replacement decoration");
  4286. if (!this.isReplace && to != from)
  4287. throw new RangeError("Widget decorations can only have zero-length ranges");
  4288. return super.range(from, to);
  4289. }
  4290. }
  4291. PointDecoration.prototype.point = true;
  4292. function getInclusive(spec) {
  4293. let { inclusiveStart: start, inclusiveEnd: end } = spec;
  4294. if (start == null)
  4295. start = spec.inclusive;
  4296. if (end == null)
  4297. end = spec.inclusive;
  4298. return { start: start || false, end: end || false };
  4299. }
  4300. function widgetsEq(a, b) {
  4301. return a == b || !!(a && b && a.compare(b));
  4302. }
  4303. function addRange(from, to, ranges, margin = 0) {
  4304. let last = ranges.length - 1;
  4305. if (last >= 0 && ranges[last] + margin > from)
  4306. ranges[last] = Math.max(ranges[last], to);
  4307. else
  4308. ranges.push(from, to);
  4309. }
  4310. const theme = Facet.define({ combine: strs => strs.join(" ") });
  4311. const darkTheme = Facet.define({ combine: values => values.indexOf(true) > -1 });
  4312. const baseThemeID = StyleModule.newName();
  4313. function expandThemeClasses(sel) {
  4314. return sel.replace(/\$\w[\w\.]*/g, cls => {
  4315. let parts = cls.slice(1).split("."), result = "";
  4316. for (let i = 1; i <= parts.length; i++)
  4317. result += ".cm-" + parts.slice(0, i).join("-");
  4318. return result;
  4319. });
  4320. }
  4321. function buildTheme(main, spec) {
  4322. return new StyleModule(spec, {
  4323. process(sel) {
  4324. sel = expandThemeClasses(sel);
  4325. return /\$/.test(sel) ? sel.replace(/\$/, main) : main + " " + sel;
  4326. },
  4327. extend(template, sel) {
  4328. template = expandThemeClasses(template);
  4329. return sel.slice(0, main.length + 1) == main + " "
  4330. ? main + " " + template.replace(/&/, sel.slice(main.length + 1))
  4331. : template.replace(/&/, sel);
  4332. }
  4333. });
  4334. }
  4335. /// Create a set of CSS class names for the given theme class, which
  4336. /// can be added to a DOM element within an editor to make themes able
  4337. /// to style it. Theme classes can be single words or words separated
  4338. /// by dot characters. In the latter case, the returned classes
  4339. /// combine those that match the full name and those that match some
  4340. /// prefix—for example `"panel.search"` will match both the theme
  4341. /// styles specified as `"panel.search"` and those with just
  4342. /// `"panel"`. More specific theme classes (with more dots) take
  4343. /// precedence over less specific ones.
  4344. function themeClass(selector) {
  4345. if (selector.indexOf(".") < 0)
  4346. return "cm-" + selector;
  4347. let parts = selector.split("."), result = "";
  4348. for (let i = 1; i <= parts.length; i++)
  4349. result += (result ? " " : "") + "cm-" + parts.slice(0, i).join("-");
  4350. return result;
  4351. }
  4352. const baseTheme = buildTheme("." + baseThemeID, {
  4353. $: {
  4354. position: "relative !important",
  4355. boxSizing: "border-box",
  4356. "&$focused": {
  4357. // FIXME it would be great if we could directly use the browser's
  4358. // default focus outline, but it appears we can't, so this tries to
  4359. // approximate that
  4360. outline_fallback: "1px dotted #212121",
  4361. outline: "5px auto -webkit-focus-ring-color"
  4362. },
  4363. display: "flex !important",
  4364. flexDirection: "column"
  4365. },
  4366. $scroller: {
  4367. display: "flex !important",
  4368. alignItems: "flex-start !important",
  4369. fontFamily: "monospace",
  4370. lineHeight: 1.4,
  4371. height: "100%",
  4372. overflowX: "auto",
  4373. position: "relative",
  4374. zIndex: 0
  4375. },
  4376. $content: {
  4377. margin: 0,
  4378. flexGrow: 2,
  4379. minHeight: "100%",
  4380. display: "block",
  4381. whiteSpace: "pre",
  4382. boxSizing: "border-box",
  4383. padding: "4px 0",
  4384. outline: "none"
  4385. },
  4386. "$$light $content": { caretColor: "black" },
  4387. "$$dark $content": { caretColor: "white" },
  4388. $line: {
  4389. display: "block",
  4390. padding: "0 2px 0 4px"
  4391. },
  4392. $selectionLayer: {
  4393. zIndex: -1,
  4394. contain: "size style"
  4395. },
  4396. $selectionBackground: {
  4397. position: "absolute",
  4398. },
  4399. "$$light $selectionBackground": {
  4400. background: "#d9d9d9"
  4401. },
  4402. "$$dark $selectionBackground": {
  4403. background: "#222"
  4404. },
  4405. "$$focused$light $selectionBackground": {
  4406. background: "#d7d4f0"
  4407. },
  4408. "$$focused$dark $selectionBackground": {
  4409. background: "#233"
  4410. },
  4411. $cursorLayer: {
  4412. zIndex: 100,
  4413. contain: "size style",
  4414. pointerEvents: "none"
  4415. },
  4416. "$$focused $cursorLayer": {
  4417. animation: "steps(1) cm-blink 1.2s infinite"
  4418. },
  4419. // Two animations defined so that we can switch between them to
  4420. // restart the animation without forcing another style
  4421. // recomputation.
  4422. "@keyframes cm-blink": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} },
  4423. "@keyframes cm-blink2": { "0%": {}, "50%": { visibility: "hidden" }, "100%": {} },
  4424. $cursor: {
  4425. position: "absolute",
  4426. borderLeft: "1.2px solid black",
  4427. marginLeft: "-0.6px",
  4428. pointerEvents: "none",
  4429. display: "none"
  4430. },
  4431. "$$dark $cursor": {
  4432. borderLeftColor: "#444"
  4433. },
  4434. "$$focused $cursor": {
  4435. display: "block"
  4436. },
  4437. "$$light $activeLine": { backgroundColor: "#f3f9ff" },
  4438. "$$dark $activeLine": { backgroundColor: "#223039" },
  4439. "$$light $specialChar": { color: "red" },
  4440. "$$dark $specialChar": { color: "#f78" },
  4441. "$tab": {
  4442. display: "inline-block",
  4443. overflow: "hidden",
  4444. verticalAlign: "bottom"
  4445. },
  4446. $placeholder: {
  4447. color: "#888",
  4448. display: "inline-block"
  4449. },
  4450. $button: {
  4451. verticalAlign: "middle",
  4452. color: "inherit",
  4453. fontSize: "70%",
  4454. padding: ".2em 1em",
  4455. borderRadius: "3px"
  4456. },
  4457. "$$light $button": {
  4458. backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
  4459. border: "1px solid #888",
  4460. "&:active": {
  4461. backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
  4462. }
  4463. },
  4464. "$$dark $button": {
  4465. backgroundImage: "linear-gradient(#555, #111)",
  4466. border: "1px solid #888",
  4467. "&:active": {
  4468. backgroundImage: "linear-gradient(#111, #333)"
  4469. }
  4470. },
  4471. $textfield: {
  4472. verticalAlign: "middle",
  4473. color: "inherit",
  4474. fontSize: "70%",
  4475. border: "1px solid silver",
  4476. padding: ".2em .5em"
  4477. },
  4478. "$$light $textfield": {
  4479. backgroundColor: "white"
  4480. },
  4481. "$$dark $textfield": {
  4482. border: "1px solid #555",
  4483. backgroundColor: "inherit"
  4484. }
  4485. });
  4486. const LineClass = themeClass("line");
  4487. class LineView extends ContentView {
  4488. constructor() {
  4489. super(...arguments);
  4490. this.children = [];
  4491. this.length = 0;
  4492. this.prevAttrs = undefined;
  4493. this.attrs = null;
  4494. this.breakAfter = 0;
  4495. }
  4496. // Consumes source
  4497. merge(from, to, source, takeDeco, openStart, openEnd) {
  4498. if (source) {
  4499. if (!(source instanceof LineView))
  4500. return false;
  4501. if (!this.dom)
  4502. source.transferDOM(this); // Reuse source.dom when appropriate
  4503. }
  4504. if (takeDeco)
  4505. this.setDeco(source ? source.attrs : null);
  4506. mergeInlineChildren(this, from, to, source ? source.children : none$2, openStart, openEnd);
  4507. return true;
  4508. }
  4509. split(at) {
  4510. let end = new LineView;
  4511. end.breakAfter = this.breakAfter;
  4512. if (this.length == 0)
  4513. return end;
  4514. let { i, off } = this.childPos(at);
  4515. if (off) {
  4516. end.append(this.children[i].slice(off), 0);
  4517. this.children[i].merge(off, this.children[i].length, null, 0, 0);
  4518. i++;
  4519. }
  4520. for (let j = i; j < this.children.length; j++)
  4521. end.append(this.children[j], 0);
  4522. while (i > 0 && this.children[i - 1].length == 0) {
  4523. this.children[i - 1].parent = null;
  4524. i--;
  4525. }
  4526. this.children.length = i;
  4527. this.markDirty();
  4528. this.length = at;
  4529. return end;
  4530. }
  4531. transferDOM(other) {
  4532. if (!this.dom)
  4533. return;
  4534. other.setDOM(this.dom);
  4535. other.prevAttrs = this.prevAttrs === undefined ? this.attrs : this.prevAttrs;
  4536. this.prevAttrs = undefined;
  4537. this.dom = null;
  4538. }
  4539. setDeco(attrs) {
  4540. if (!attrsEq(this.attrs, attrs)) {
  4541. if (this.dom) {
  4542. this.prevAttrs = this.attrs;
  4543. this.markDirty();
  4544. }
  4545. this.attrs = attrs;
  4546. }
  4547. }
  4548. // Only called when building a line view in ContentBuilder
  4549. append(child, openStart) {
  4550. joinInlineInto(this, child, openStart);
  4551. }
  4552. // Only called when building a line view in ContentBuilder
  4553. addLineDeco(deco) {
  4554. let attrs = deco.spec.attributes;
  4555. if (attrs)
  4556. this.attrs = combineAttrs(attrs, this.attrs || {});
  4557. }
  4558. domAtPos(pos) {
  4559. return inlineDOMAtPos(this.dom, this.children, pos);
  4560. }
  4561. sync(track) {
  4562. if (!this.dom) {
  4563. this.setDOM(document.createElement("div"));
  4564. this.dom.className = LineClass;
  4565. this.prevAttrs = this.attrs ? null : undefined;
  4566. }
  4567. if (this.prevAttrs !== undefined) {
  4568. updateAttrs(this.dom, this.prevAttrs, this.attrs);
  4569. this.dom.classList.add(LineClass);
  4570. this.prevAttrs = undefined;
  4571. }
  4572. super.sync(track);
  4573. let last = this.dom.lastChild;
  4574. if (!last || (last.nodeName != "BR" && (ContentView.get(last) instanceof WidgetView))) {
  4575. let hack = document.createElement("BR");
  4576. hack.cmIgnore = true;
  4577. this.dom.appendChild(hack);
  4578. }
  4579. }
  4580. measureTextSize() {
  4581. if (this.children.length == 0 || this.length > 20)
  4582. return null;
  4583. let totalWidth = 0;
  4584. for (let child of this.children) {
  4585. if (!(child instanceof TextView))
  4586. return null;
  4587. let rects = clientRectsFor(child.dom);
  4588. if (rects.length != 1)
  4589. return null;
  4590. totalWidth += rects[0].width;
  4591. }
  4592. return { lineHeight: this.dom.getBoundingClientRect().height, charWidth: totalWidth / this.length };
  4593. }
  4594. coordsAt(pos, side) {
  4595. return coordsInChildren(this, pos, side);
  4596. }
  4597. match(_other) { return false; }
  4598. get type() { return BlockType.Text; }
  4599. static find(docView, pos) {
  4600. for (let i = 0, off = 0;; i++) {
  4601. let block = docView.children[i], end = off + block.length;
  4602. if (end >= pos) {
  4603. if (block instanceof LineView)
  4604. return block;
  4605. if (block.length)
  4606. return null;
  4607. }
  4608. off = end + block.breakAfter;
  4609. }
  4610. }
  4611. }
  4612. const none$2 = [];
  4613. class BlockWidgetView extends ContentView {
  4614. constructor(widget, length, type) {
  4615. super();
  4616. this.widget = widget;
  4617. this.length = length;
  4618. this.type = type;
  4619. this.breakAfter = 0;
  4620. }
  4621. merge(from, to, source, _takeDeco, openStart, openEnd) {
  4622. if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) ||
  4623. from > 0 && openStart <= 0 || to < this.length && openEnd <= 0))
  4624. return false;
  4625. this.length = from + (source ? source.length : 0) + (this.length - to);
  4626. return true;
  4627. }
  4628. domAtPos(pos) {
  4629. return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
  4630. }
  4631. split(at) {
  4632. let len = this.length - at;
  4633. this.length = at;
  4634. return new BlockWidgetView(this.widget, len, this.type);
  4635. }
  4636. get children() { return none$2; }
  4637. sync() {
  4638. if (!this.dom || !this.widget.updateDOM(this.dom)) {
  4639. this.setDOM(this.widget.toDOM(this.editorView));
  4640. this.dom.contentEditable = "false";
  4641. }
  4642. }
  4643. get overrideDOMText() {
  4644. return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
  4645. }
  4646. domBoundsAround() { return null; }
  4647. match(other) {
  4648. if (other instanceof BlockWidgetView && other.type == this.type &&
  4649. other.widget.constructor == this.widget.constructor) {
  4650. if (!other.widget.eq(this.widget))
  4651. this.markDirty(true);
  4652. this.widget = other.widget;
  4653. this.length = other.length;
  4654. this.breakAfter = other.breakAfter;
  4655. return true;
  4656. }
  4657. return false;
  4658. }
  4659. ignoreMutation() { return true; }
  4660. ignoreEvent(event) { return this.widget.ignoreEvent(event); }
  4661. }
  4662. class ContentBuilder {
  4663. constructor(doc, pos, end) {
  4664. this.doc = doc;
  4665. this.pos = pos;
  4666. this.end = end;
  4667. this.content = [];
  4668. this.curLine = null;
  4669. this.breakAtStart = 0;
  4670. this.openStart = -1;
  4671. this.openEnd = -1;
  4672. this.text = "";
  4673. this.textOff = 0;
  4674. this.cursor = doc.iter();
  4675. this.skip = pos;
  4676. }
  4677. posCovered() {
  4678. if (this.content.length == 0)
  4679. return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
  4680. let last = this.content[this.content.length - 1];
  4681. return !last.breakAfter && !(last instanceof BlockWidgetView && last.type == BlockType.WidgetBefore);
  4682. }
  4683. getLine() {
  4684. if (!this.curLine)
  4685. this.content.push(this.curLine = new LineView);
  4686. return this.curLine;
  4687. }
  4688. addWidget(view) {
  4689. this.curLine = null;
  4690. this.content.push(view);
  4691. }
  4692. finish() {
  4693. if (!this.posCovered())
  4694. this.getLine();
  4695. }
  4696. wrapMarks(view, active) {
  4697. for (let i = active.length - 1; i >= 0; i--)
  4698. view = new MarkView(active[i], [view], view.length);
  4699. return view;
  4700. }
  4701. buildText(length, active, openStart) {
  4702. while (length > 0) {
  4703. if (this.textOff == this.text.length) {
  4704. let { value, lineBreak, done } = this.cursor.next(this.skip);
  4705. this.skip = 0;
  4706. if (done)
  4707. throw new Error("Ran out of text content when drawing inline views");
  4708. if (lineBreak) {
  4709. if (!this.posCovered())
  4710. this.getLine();
  4711. if (this.content.length)
  4712. this.content[this.content.length - 1].breakAfter = 1;
  4713. else
  4714. this.breakAtStart = 1;
  4715. this.curLine = null;
  4716. length--;
  4717. continue;
  4718. }
  4719. else {
  4720. this.text = value;
  4721. this.textOff = 0;
  4722. }
  4723. }
  4724. let take = Math.min(this.text.length - this.textOff, length, 512 /* Chunk */);
  4725. this.getLine().append(this.wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
  4726. this.textOff += take;
  4727. length -= take;
  4728. openStart = 0;
  4729. }
  4730. }
  4731. span(from, to, active, openStart) {
  4732. this.buildText(to - from, active, openStart);
  4733. this.pos = to;
  4734. if (this.openStart < 0)
  4735. this.openStart = openStart;
  4736. }
  4737. point(from, to, deco, active, openStart) {
  4738. let len = to - from;
  4739. if (deco instanceof PointDecoration) {
  4740. if (deco.block) {
  4741. let { type } = deco;
  4742. if (type == BlockType.WidgetAfter && !this.posCovered())
  4743. this.getLine();
  4744. this.addWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, type));
  4745. }
  4746. else {
  4747. let widget = this.wrapMarks(WidgetView.create(deco.widget || new NullWidget("span"), len, deco.startSide), active);
  4748. this.getLine().append(widget, openStart);
  4749. }
  4750. }
  4751. else if (this.doc.lineAt(this.pos).from == this.pos) { // Line decoration
  4752. this.getLine().addLineDeco(deco);
  4753. }
  4754. if (len) {
  4755. // Advance the iterator past the replaced content
  4756. if (this.textOff + len <= this.text.length) {
  4757. this.textOff += len;
  4758. }
  4759. else {
  4760. this.skip += len - (this.text.length - this.textOff);
  4761. this.text = "";
  4762. this.textOff = 0;
  4763. }
  4764. this.pos = to;
  4765. }
  4766. if (this.openStart < 0)
  4767. this.openStart = openStart;
  4768. }
  4769. static build(text, from, to, decorations) {
  4770. let builder = new ContentBuilder(text, from, to);
  4771. builder.openEnd = RangeSet.spans(decorations, from, to, builder);
  4772. if (builder.openStart < 0)
  4773. builder.openStart = builder.openEnd;
  4774. builder.finish();
  4775. return builder;
  4776. }
  4777. }
  4778. class NullWidget extends WidgetType {
  4779. constructor(tag) {
  4780. super();
  4781. this.tag = tag;
  4782. }
  4783. eq(other) { return other.tag == this.tag; }
  4784. toDOM() { return document.createElement(this.tag); }
  4785. updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag; }
  4786. }
  4787. /// Used to indicate [text direction](#view.EditorView.textDirection).
  4788. var Direction;
  4789. (function (Direction) {
  4790. // (These are chosen to match the base levels, in bidi algorithm
  4791. // terms, of spans in that direction.)
  4792. /// Left-to-right.
  4793. Direction[Direction["LTR"] = 0] = "LTR";
  4794. /// Right-to-left.
  4795. Direction[Direction["RTL"] = 1] = "RTL";
  4796. })(Direction || (Direction = {}));
  4797. const LTR = Direction.LTR, RTL = Direction.RTL;
  4798. // Decode a string with each type encoded as log2(type)
  4799. function dec(str) {
  4800. let result = [];
  4801. for (let i = 0; i < str.length; i++)
  4802. result.push(1 << +str[i]);
  4803. return result;
  4804. }
  4805. // Character types for codepoints 0 to 0xf8
  4806. const LowTypes = dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
  4807. // Character types for codepoints 0x600 to 0x6f9
  4808. const ArabicTypes = dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
  4809. function charType(ch) {
  4810. return ch <= 0xf7 ? LowTypes[ch] :
  4811. 0x590 <= ch && ch <= 0x5f4 ? 2 /* R */ :
  4812. 0x600 <= ch && ch <= 0x6f9 ? ArabicTypes[ch - 0x600] :
  4813. 0x6ee <= ch && ch <= 0x8ac ? 4 /* AL */ :
  4814. 0x2000 <= ch && ch <= 0x200b ? 256 /* NI */ :
  4815. ch == 0x200c ? 256 /* NI */ : 1 /* L */;
  4816. }
  4817. const BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  4818. /// Represents a contiguous range of text that has a single direction
  4819. /// (as in left-to-right or right-to-left).
  4820. class BidiSpan {
  4821. /// @internal
  4822. constructor(
  4823. /// The start of the span (relative to the start of the line).
  4824. from,
  4825. /// The end of the span.
  4826. to,
  4827. /// The ["bidi
  4828. /// level"](https://unicode.org/reports/tr9/#Basic_Display_Algorithm)
  4829. /// of the span (in this context, 0 means
  4830. /// left-to-right, 1 means right-to-left, 2 means left-to-right
  4831. /// number inside right-to-left text).
  4832. level) {
  4833. this.from = from;
  4834. this.to = to;
  4835. this.level = level;
  4836. }
  4837. /// The direction of this span.
  4838. get dir() { return this.level % 2 ? RTL : LTR; }
  4839. /// @internal
  4840. side(end, dir) { return (this.dir == dir) == end ? this.to : this.from; }
  4841. /// @internal
  4842. static find(order, index, level, assoc) {
  4843. let maybe = -1;
  4844. for (let i = 0; i < order.length; i++) {
  4845. let span = order[i];
  4846. if (span.from <= index && span.to >= index) {
  4847. if (span.level == level)
  4848. return i;
  4849. // When multiple spans match, if assoc != 0, take the one that
  4850. // covers that side, otherwise take the one with the minimum
  4851. // level.
  4852. if (maybe < 0 || (assoc != 0 ? (assoc < 0 ? span.from < index : span.to > index) : order[maybe].level > span.level))
  4853. maybe = i;
  4854. }
  4855. }
  4856. if (maybe < 0)
  4857. throw new RangeError("Index out of range");
  4858. return maybe;
  4859. }
  4860. }
  4861. // Reused array of character types
  4862. const types = [];
  4863. function computeOrder(line, direction) {
  4864. let len = line.length, outerType = direction == LTR ? 1 /* L */ : 2 /* R */;
  4865. if (!line || outerType == 1 /* L */ && !BidiRE.test(line))
  4866. return trivialOrder(len);
  4867. // W1. Examine each non-spacing mark (NSM) in the level run, and
  4868. // change the type of the NSM to the type of the previous
  4869. // character. If the NSM is at the start of the level run, it will
  4870. // get the type of sor.
  4871. // W2. Search backwards from each instance of a European number
  4872. // until the first strong type (R, L, AL, or sor) is found. If an
  4873. // AL is found, change the type of the European number to Arabic
  4874. // number.
  4875. // W3. Change all ALs to R.
  4876. // (Left after this: L, R, EN, AN, ET, CS, NI)
  4877. for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) {
  4878. let type = charType(line.charCodeAt(i));
  4879. if (type == 512 /* NSM */)
  4880. type = prev;
  4881. else if (type == 8 /* EN */ && prevStrong == 4 /* AL */)
  4882. type = 16 /* AN */;
  4883. types[i] = type == 4 /* AL */ ? 2 /* R */ : type;
  4884. if (type & 7 /* Strong */)
  4885. prevStrong = type;
  4886. prev = type;
  4887. }
  4888. // W5. A sequence of European terminators adjacent to European
  4889. // numbers changes to all European numbers.
  4890. // W6. Otherwise, separators and terminators change to Other
  4891. // Neutral.
  4892. // W7. Search backwards from each instance of a European number
  4893. // until the first strong type (R, L, or sor) is found. If an L is
  4894. // found, then change the type of the European number to L.
  4895. // (Left after this: L, R, EN+AN, NI)
  4896. for (let i = 0, prev = outerType, prevStrong = outerType; i < len; i++) {
  4897. let type = types[i];
  4898. if (type == 128 /* CS */) {
  4899. if (i < len - 1 && prev == types[i + 1] && (prev & 24 /* Num */))
  4900. type = types[i] = prev;
  4901. else
  4902. types[i] = 256 /* NI */;
  4903. }
  4904. else if (type == 64 /* ET */) {
  4905. let end = i + 1;
  4906. while (end < len && types[end] == 64 /* ET */)
  4907. end++;
  4908. let replace = (i && prev == 8 /* EN */) || (end < len && types[end] == 8 /* EN */) ? (prevStrong == 1 /* L */ ? 1 /* L */ : 8 /* EN */) : 256 /* NI */;
  4909. for (let j = i; j < end; j++)
  4910. types[j] = replace;
  4911. i = end - 1;
  4912. }
  4913. else if (type == 8 /* EN */ && prevStrong == 1 /* L */) {
  4914. types[i] = 1 /* L */;
  4915. }
  4916. prev = type;
  4917. if (type & 7 /* Strong */)
  4918. prevStrong = type;
  4919. }
  4920. // N1. A sequence of neutrals takes the direction of the
  4921. // surrounding strong text if the text on both sides has the same
  4922. // direction. European and Arabic numbers act as if they were R in
  4923. // terms of their influence on neutrals. Start-of-level-run (sor)
  4924. // and end-of-level-run (eor) are used at level run boundaries.
  4925. // N2. Any remaining neutrals take the embedding direction.
  4926. // (Left after this: L, R, EN+AN)
  4927. for (let i = 0; i < len; i++) {
  4928. if (types[i] == 256 /* NI */) {
  4929. let end = i + 1;
  4930. while (end < len && types[end] == 256 /* NI */)
  4931. end++;
  4932. let beforeL = (i ? types[i - 1] : outerType) == 1 /* L */;
  4933. let afterL = (end < len ? types[end] : outerType) == 1 /* L */;
  4934. let replace = beforeL == afterL ? (beforeL ? 1 /* L */ : 2 /* R */) : outerType;
  4935. for (let j = i; j < end; j++)
  4936. types[j] = replace;
  4937. i = end - 1;
  4938. }
  4939. }
  4940. // Here we depart from the documented algorithm, in order to avoid
  4941. // building up an actual levels array. Since there are only three
  4942. // levels (0, 1, 2) in an implementation that doesn't take
  4943. // explicit embedding into account, we can build up the order on
  4944. // the fly, without following the level-based algorithm.
  4945. let order = [];
  4946. if (outerType == 1 /* L */) {
  4947. for (let i = 0; i < len;) {
  4948. let start = i, rtl = types[i++] != 1 /* L */;
  4949. while (i < len && rtl == (types[i] != 1 /* L */))
  4950. i++;
  4951. if (rtl) {
  4952. for (let j = i; j > start;) {
  4953. let end = j, l = types[--j] != 2 /* R */;
  4954. while (j > start && l == (types[j - 1] != 2 /* R */))
  4955. j--;
  4956. order.push(new BidiSpan(j, end, l ? 2 : 1));
  4957. }
  4958. }
  4959. else {
  4960. order.push(new BidiSpan(start, i, 0));
  4961. }
  4962. }
  4963. }
  4964. else {
  4965. for (let i = 0; i < len;) {
  4966. let start = i, rtl = types[i++] == 2 /* R */;
  4967. while (i < len && rtl == (types[i] == 2 /* R */))
  4968. i++;
  4969. order.push(new BidiSpan(start, i, rtl ? 1 : 2));
  4970. }
  4971. }
  4972. return order;
  4973. }
  4974. function trivialOrder(length) {
  4975. return [new BidiSpan(0, length, 0)];
  4976. }
  4977. let movedOver = "";
  4978. function moveVisually(line, order, dir, start, forward) {
  4979. var _a;
  4980. let startIndex = start.head - line.from, spanI = -1;
  4981. if (startIndex == 0) {
  4982. if (!forward || !line.length)
  4983. return null;
  4984. if (order[0].level != dir) {
  4985. startIndex = order[0].side(false, dir);
  4986. spanI = 0;
  4987. }
  4988. }
  4989. else if (startIndex == line.length) {
  4990. if (forward)
  4991. return null;
  4992. let last = order[order.length - 1];
  4993. if (last.level != dir) {
  4994. startIndex = last.side(true, dir);
  4995. spanI = order.length - 1;
  4996. }
  4997. }
  4998. if (spanI < 0)
  4999. spanI = BidiSpan.find(order, startIndex, (_a = start.bidiLevel) !== null && _a !== void 0 ? _a : -1, start.assoc);
  5000. let span = order[spanI];
  5001. // End of span. (But not end of line--that was checked for above.)
  5002. if (startIndex == span.side(forward, dir)) {
  5003. span = order[spanI += forward ? 1 : -1];
  5004. startIndex = span.side(!forward, dir);
  5005. }
  5006. let indexForward = forward == (span.dir == dir);
  5007. let nextIndex = findClusterBreak(line.text, startIndex, indexForward);
  5008. movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
  5009. if (nextIndex != span.side(forward, dir))
  5010. return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level);
  5011. let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
  5012. if (!nextSpan && span.level != dir)
  5013. return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir);
  5014. if (nextSpan && nextSpan.level < span.level)
  5015. return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, 0, nextSpan.level);
  5016. return EditorSelection.cursor(nextIndex + line.from, 0, span.level);
  5017. }
  5018. const wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line"];
  5019. class HeightOracle {
  5020. constructor() {
  5021. this.doc = Text.empty;
  5022. this.lineWrapping = false;
  5023. this.direction = Direction.LTR;
  5024. this.heightSamples = {};
  5025. this.lineHeight = 14;
  5026. this.charWidth = 7;
  5027. this.lineLength = 30;
  5028. // Used to track, during updateHeight, if any actual heights changed
  5029. this.heightChanged = false;
  5030. }
  5031. heightForGap(from, to) {
  5032. let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
  5033. if (this.lineWrapping)
  5034. lines += Math.ceil(((to - from) - (lines * this.lineLength * 0.5)) / this.lineLength);
  5035. return this.lineHeight * lines;
  5036. }
  5037. heightForLine(length) {
  5038. if (!this.lineWrapping)
  5039. return this.lineHeight;
  5040. let lines = 1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)));
  5041. return lines * this.lineHeight;
  5042. }
  5043. setDoc(doc) { this.doc = doc; return this; }
  5044. mustRefresh(lineHeights, whiteSpace, direction) {
  5045. let newHeight = false;
  5046. for (let i = 0; i < lineHeights.length; i++) {
  5047. let h = lineHeights[i];
  5048. if (h < 0) {
  5049. i++;
  5050. }
  5051. else if (!this.heightSamples[Math.floor(h * 10)]) { // Round to .1 pixels
  5052. newHeight = true;
  5053. this.heightSamples[Math.floor(h * 10)] = true;
  5054. }
  5055. }
  5056. return newHeight || (wrappingWhiteSpace.indexOf(whiteSpace) > -1) != this.lineWrapping || this.direction != direction;
  5057. }
  5058. refresh(whiteSpace, direction, lineHeight, charWidth, lineLength, knownHeights) {
  5059. let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
  5060. let changed = Math.round(lineHeight) != Math.round(this.lineHeight) ||
  5061. this.lineWrapping != lineWrapping ||
  5062. this.direction != direction;
  5063. this.lineWrapping = lineWrapping;
  5064. this.direction = direction;
  5065. this.lineHeight = lineHeight;
  5066. this.charWidth = charWidth;
  5067. this.lineLength = lineLength;
  5068. if (changed) {
  5069. this.heightSamples = {};
  5070. for (let i = 0; i < knownHeights.length; i++) {
  5071. let h = knownHeights[i];
  5072. if (h < 0)
  5073. i++;
  5074. else
  5075. this.heightSamples[Math.floor(h * 10)] = true;
  5076. }
  5077. }
  5078. return changed;
  5079. }
  5080. }
  5081. // This object is used by `updateHeight` to make DOM measurements
  5082. // arrive at the right nides. The `heights` array is a sequence of
  5083. // block heights, starting from position `from`.
  5084. class MeasuredHeights {
  5085. constructor(from, heights) {
  5086. this.from = from;
  5087. this.heights = heights;
  5088. this.index = 0;
  5089. }
  5090. get more() { return this.index < this.heights.length; }
  5091. }
  5092. /// Record used to represent information about a block-level element
  5093. /// in the editor view.
  5094. class BlockInfo {
  5095. /// @internal
  5096. constructor(
  5097. /// The start of the element in the document.
  5098. from,
  5099. /// The length of the element.
  5100. length,
  5101. /// The top position of the element.
  5102. top,
  5103. /// Its height.
  5104. height,
  5105. /// The type of element this is. When querying lines, this may be
  5106. /// an array of all the blocks that make up the line.
  5107. type) {
  5108. this.from = from;
  5109. this.length = length;
  5110. this.top = top;
  5111. this.height = height;
  5112. this.type = type;
  5113. }
  5114. /// The end of the element as a document position.
  5115. get to() { return this.from + this.length; }
  5116. /// The bottom position of the element.
  5117. get bottom() { return this.top + this.height; }
  5118. /// @internal
  5119. join(other) {
  5120. let detail = (Array.isArray(this.type) ? this.type : [this])
  5121. .concat(Array.isArray(other.type) ? other.type : [other]);
  5122. return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, detail);
  5123. }
  5124. }
  5125. var QueryType;
  5126. (function (QueryType) {
  5127. QueryType[QueryType["ByPos"] = 0] = "ByPos";
  5128. QueryType[QueryType["ByHeight"] = 1] = "ByHeight";
  5129. QueryType[QueryType["ByPosNoHeight"] = 2] = "ByPosNoHeight";
  5130. })(QueryType || (QueryType = {}));
  5131. const Epsilon = 1e-4;
  5132. class HeightMap {
  5133. constructor(length, // The number of characters covered
  5134. height, // Height of this part of the document
  5135. flags = 2 /* Outdated */) {
  5136. this.length = length;
  5137. this.height = height;
  5138. this.flags = flags;
  5139. }
  5140. get outdated() { return (this.flags & 2 /* Outdated */) > 0; }
  5141. set outdated(value) { this.flags = (value ? 2 /* Outdated */ : 0) | (this.flags & ~2 /* Outdated */); }
  5142. setHeight(oracle, height) {
  5143. if (this.height != height) {
  5144. if (Math.abs(this.height - height) > Epsilon)
  5145. oracle.heightChanged = true;
  5146. this.height = height;
  5147. }
  5148. }
  5149. // Base case is to replace a leaf node, which simply builds a tree
  5150. // from the new nodes and returns that (HeightMapBranch and
  5151. // HeightMapGap override this to actually use from/to)
  5152. replace(_from, _to, nodes) {
  5153. return HeightMap.of(nodes);
  5154. }
  5155. // Again, these are base cases, and are overridden for branch and gap nodes.
  5156. decomposeLeft(_to, result) { result.push(this); }
  5157. decomposeRight(_from, result) { result.push(this); }
  5158. applyChanges(decorations, oldDoc, oracle, changes) {
  5159. let me = this;
  5160. for (let i = changes.length - 1; i >= 0; i--) {
  5161. let { fromA, toA, fromB, toB } = changes[i];
  5162. let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
  5163. let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
  5164. toB += end.to - toA;
  5165. toA = end.to;
  5166. while (i > 0 && start.from <= changes[i - 1].toA) {
  5167. fromA = changes[i - 1].fromA;
  5168. fromB = changes[i - 1].fromB;
  5169. i--;
  5170. if (fromA < start.from)
  5171. start = me.lineAt(fromA, QueryType.ByPosNoHeight, oldDoc, 0, 0);
  5172. }
  5173. fromB += start.from - fromA;
  5174. fromA = start.from;
  5175. let nodes = NodeBuilder.build(oracle, decorations, fromB, toB);
  5176. me = me.replace(fromA, toA, nodes);
  5177. }
  5178. return me.updateHeight(oracle, 0);
  5179. }
  5180. static empty() { return new HeightMapText(0, 0); }
  5181. // nodes uses null values to indicate the position of line breaks.
  5182. // There are never line breaks at the start or end of the array, or
  5183. // two line breaks next to each other, and the array isn't allowed
  5184. // to be empty (same restrictions as return value from the builder).
  5185. static of(nodes) {
  5186. if (nodes.length == 1)
  5187. return nodes[0];
  5188. let i = 0, j = nodes.length, before = 0, after = 0;
  5189. for (;;) {
  5190. if (i == j) {
  5191. if (before > after * 2) {
  5192. let split = nodes[i - 1];
  5193. if (split.break)
  5194. nodes.splice(--i, 1, split.left, null, split.right);
  5195. else
  5196. nodes.splice(--i, 1, split.left, split.right);
  5197. j += 1 + split.break;
  5198. before -= split.size;
  5199. }
  5200. else if (after > before * 2) {
  5201. let split = nodes[j];
  5202. if (split.break)
  5203. nodes.splice(j, 1, split.left, null, split.right);
  5204. else
  5205. nodes.splice(j, 1, split.left, split.right);
  5206. j += 2 + split.break;
  5207. after -= split.size;
  5208. }
  5209. else {
  5210. break;
  5211. }
  5212. }
  5213. else if (before < after) {
  5214. let next = nodes[i++];
  5215. if (next)
  5216. before += next.size;
  5217. }
  5218. else {
  5219. let next = nodes[--j];
  5220. if (next)
  5221. after += next.size;
  5222. }
  5223. }
  5224. let brk = 0;
  5225. if (nodes[i - 1] == null) {
  5226. brk = 1;
  5227. i--;
  5228. }
  5229. else if (nodes[i] == null) {
  5230. brk = 1;
  5231. j++;
  5232. }
  5233. return new HeightMapBranch(HeightMap.of(nodes.slice(0, i)), brk, HeightMap.of(nodes.slice(j)));
  5234. }
  5235. }
  5236. HeightMap.prototype.size = 1;
  5237. class HeightMapBlock extends HeightMap {
  5238. constructor(length, height, type) {
  5239. super(length, height);
  5240. this.type = type;
  5241. }
  5242. blockAt(_height, _doc, top, offset) {
  5243. return new BlockInfo(offset, this.length, top, this.height, this.type);
  5244. }
  5245. lineAt(_value, _type, doc, top, offset) {
  5246. return this.blockAt(0, doc, top, offset);
  5247. }
  5248. forEachLine(_from, _to, doc, top, offset, f) {
  5249. f(this.blockAt(0, doc, top, offset));
  5250. }
  5251. updateHeight(oracle, offset = 0, _force = false, measured) {
  5252. if (measured && measured.from <= offset && measured.more)
  5253. this.setHeight(oracle, measured.heights[measured.index++]);
  5254. this.outdated = false;
  5255. return this;
  5256. }
  5257. toString() { return `block(${this.length})`; }
  5258. }
  5259. class HeightMapText extends HeightMapBlock {
  5260. constructor(length, height) {
  5261. super(length, height, BlockType.Text);
  5262. this.collapsed = 0; // Amount of collapsed content in the line
  5263. this.widgetHeight = 0; // Maximum inline widget height
  5264. }
  5265. replace(_from, _to, nodes) {
  5266. let node = nodes[0];
  5267. if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && (node.flags & 4 /* SingleLine */)) &&
  5268. Math.abs(this.length - node.length) < 10) {
  5269. if (node instanceof HeightMapGap)
  5270. node = new HeightMapText(node.length, this.height);
  5271. else
  5272. node.height = this.height;
  5273. if (!this.outdated)
  5274. node.outdated = false;
  5275. return node;
  5276. }
  5277. else {
  5278. return HeightMap.of(nodes);
  5279. }
  5280. }
  5281. updateHeight(oracle, offset = 0, force = false, measured) {
  5282. if (measured && measured.from <= offset && measured.more)
  5283. this.setHeight(oracle, measured.heights[measured.index++]);
  5284. else if (force || this.outdated)
  5285. this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)));
  5286. this.outdated = false;
  5287. return this;
  5288. }
  5289. toString() {
  5290. return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
  5291. }
  5292. }
  5293. class HeightMapGap extends HeightMap {
  5294. constructor(length) { super(length, 0); }
  5295. lines(doc, offset) {
  5296. let firstLine = doc.lineAt(offset).number, lastLine = doc.lineAt(offset + this.length).number;
  5297. return { firstLine, lastLine, lineHeight: this.height / (lastLine - firstLine + 1) };
  5298. }
  5299. blockAt(height, doc, top, offset) {
  5300. let { firstLine, lastLine, lineHeight } = this.lines(doc, offset);
  5301. let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top) / lineHeight)));
  5302. let { from, length } = doc.line(firstLine + line);
  5303. return new BlockInfo(from, length, top + lineHeight * line, lineHeight, BlockType.Text);
  5304. }
  5305. lineAt(value, type, doc, top, offset) {
  5306. if (type == QueryType.ByHeight)
  5307. return this.blockAt(value, doc, top, offset);
  5308. if (type == QueryType.ByPosNoHeight) {
  5309. let { from, to } = doc.lineAt(value);
  5310. return new BlockInfo(from, to - from, 0, 0, BlockType.Text);
  5311. }
  5312. let { firstLine, lineHeight } = this.lines(doc, offset);
  5313. let { from, length, number } = doc.lineAt(value);
  5314. return new BlockInfo(from, length, top + lineHeight * (number - firstLine), lineHeight, BlockType.Text);
  5315. }
  5316. forEachLine(from, to, doc, top, offset, f) {
  5317. let { firstLine, lineHeight } = this.lines(doc, offset);
  5318. for (let pos = Math.max(from, offset), end = Math.min(offset + this.length, to); pos <= end;) {
  5319. let line = doc.lineAt(pos);
  5320. if (pos == from)
  5321. top += lineHeight * (line.number - firstLine);
  5322. f(new BlockInfo(line.from, line.length, top, top += lineHeight, BlockType.Text));
  5323. pos = line.to + 1;
  5324. }
  5325. }
  5326. replace(from, to, nodes) {
  5327. let after = this.length - to;
  5328. if (after > 0) {
  5329. let last = nodes[nodes.length - 1];
  5330. if (last instanceof HeightMapGap)
  5331. nodes[nodes.length - 1] = new HeightMapGap(last.length + after);
  5332. else
  5333. nodes.push(null, new HeightMapGap(after - 1));
  5334. }
  5335. if (from > 0) {
  5336. let first = nodes[0];
  5337. if (first instanceof HeightMapGap)
  5338. nodes[0] = new HeightMapGap(from + first.length);
  5339. else
  5340. nodes.unshift(new HeightMapGap(from - 1), null);
  5341. }
  5342. return HeightMap.of(nodes);
  5343. }
  5344. decomposeLeft(to, result) {
  5345. result.push(new HeightMapGap(to - 1), null);
  5346. }
  5347. decomposeRight(from, result) {
  5348. result.push(null, new HeightMapGap(this.length - from - 1));
  5349. }
  5350. updateHeight(oracle, offset = 0, force = false, measured) {
  5351. let end = offset + this.length;
  5352. if (measured && measured.from <= offset + this.length && measured.more) {
  5353. // Fill in part of this gap with measured lines. We know there
  5354. // can't be widgets or collapsed ranges in those lines, because
  5355. // they would already have been added to the heightmap (gaps
  5356. // only contain plain text).
  5357. let nodes = [], pos = Math.max(offset, measured.from);
  5358. if (measured.from > offset)
  5359. nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
  5360. while (pos <= end && measured.more) {
  5361. let len = oracle.doc.lineAt(pos).length;
  5362. if (nodes.length)
  5363. nodes.push(null);
  5364. let line = new HeightMapText(len, measured.heights[measured.index++]);
  5365. line.outdated = false;
  5366. nodes.push(line);
  5367. pos += len + 1;
  5368. }
  5369. if (pos <= end)
  5370. nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
  5371. oracle.heightChanged = true;
  5372. return HeightMap.of(nodes);
  5373. }
  5374. else if (force || this.outdated) {
  5375. this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
  5376. this.outdated = false;
  5377. }
  5378. return this;
  5379. }
  5380. toString() { return `gap(${this.length})`; }
  5381. }
  5382. class HeightMapBranch extends HeightMap {
  5383. constructor(left, brk, right) {
  5384. super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 /* Outdated */ : 0));
  5385. this.left = left;
  5386. this.right = right;
  5387. this.size = left.size + right.size;
  5388. }
  5389. get break() { return this.flags & 1 /* Break */; }
  5390. blockAt(height, doc, top, offset) {
  5391. let mid = top + this.left.height;
  5392. return height < mid || this.right.height == 0 ? this.left.blockAt(height, doc, top, offset)
  5393. : this.right.blockAt(height, doc, mid, offset + this.left.length + this.break);
  5394. }
  5395. lineAt(value, type, doc, top, offset) {
  5396. let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
  5397. let left = type == QueryType.ByHeight ? value < rightTop || this.right.height == 0 : value < rightOffset;
  5398. let base = left ? this.left.lineAt(value, type, doc, top, offset)
  5399. : this.right.lineAt(value, type, doc, rightTop, rightOffset);
  5400. if (this.break || (left ? base.to < rightOffset : base.from > rightOffset))
  5401. return base;
  5402. let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
  5403. if (left)
  5404. return base.join(this.right.lineAt(rightOffset, subQuery, doc, rightTop, rightOffset));
  5405. else
  5406. return this.left.lineAt(rightOffset, subQuery, doc, top, offset).join(base);
  5407. }
  5408. forEachLine(from, to, doc, top, offset, f) {
  5409. let rightTop = top + this.left.height, rightOffset = offset + this.left.length + this.break;
  5410. if (this.break) {
  5411. if (from < rightOffset)
  5412. this.left.forEachLine(from, to, doc, top, offset, f);
  5413. if (to >= rightOffset)
  5414. this.right.forEachLine(from, to, doc, rightTop, rightOffset, f);
  5415. }
  5416. else {
  5417. let mid = this.lineAt(rightOffset, QueryType.ByPos, doc, top, offset);
  5418. if (from < mid.from)
  5419. this.left.forEachLine(from, mid.from - 1, doc, top, offset, f);
  5420. if (mid.to >= from && mid.from <= to)
  5421. f(mid);
  5422. if (to > mid.to)
  5423. this.right.forEachLine(mid.to + 1, to, doc, rightTop, rightOffset, f);
  5424. }
  5425. }
  5426. replace(from, to, nodes) {
  5427. let rightStart = this.left.length + this.break;
  5428. if (to < rightStart)
  5429. return this.balanced(this.left.replace(from, to, nodes), this.right);
  5430. if (from > this.left.length)
  5431. return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
  5432. let result = [];
  5433. if (from > 0)
  5434. this.decomposeLeft(from, result);
  5435. let left = result.length;
  5436. for (let node of nodes)
  5437. result.push(node);
  5438. if (from > 0)
  5439. mergeGaps(result, left - 1);
  5440. if (to < this.length) {
  5441. let right = result.length;
  5442. this.decomposeRight(to, result);
  5443. mergeGaps(result, right);
  5444. }
  5445. return HeightMap.of(result);
  5446. }
  5447. decomposeLeft(to, result) {
  5448. let left = this.left.length;
  5449. if (to <= left)
  5450. return this.left.decomposeLeft(to, result);
  5451. result.push(this.left);
  5452. if (this.break) {
  5453. left++;
  5454. if (to >= left)
  5455. result.push(null);
  5456. }
  5457. if (to > left)
  5458. this.right.decomposeLeft(to - left, result);
  5459. }
  5460. decomposeRight(from, result) {
  5461. let left = this.left.length, right = left + this.break;
  5462. if (from >= right)
  5463. return this.right.decomposeRight(from - right, result);
  5464. if (from < left)
  5465. this.left.decomposeRight(from, result);
  5466. if (this.break && from < right)
  5467. result.push(null);
  5468. result.push(this.right);
  5469. }
  5470. balanced(left, right) {
  5471. if (left.size > 2 * right.size || right.size > 2 * left.size)
  5472. return HeightMap.of(this.break ? [left, null, right] : [left, right]);
  5473. this.left = left;
  5474. this.right = right;
  5475. this.height = left.height + right.height;
  5476. this.outdated = left.outdated || right.outdated;
  5477. this.size = left.size + right.size;
  5478. this.length = left.length + this.break + right.length;
  5479. return this;
  5480. }
  5481. updateHeight(oracle, offset = 0, force = false, measured) {
  5482. let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null;
  5483. if (measured && measured.from <= offset + left.length && measured.more)
  5484. rebalance = left = left.updateHeight(oracle, offset, force, measured);
  5485. else
  5486. left.updateHeight(oracle, offset, force);
  5487. if (measured && measured.from <= rightStart + right.length && measured.more)
  5488. rebalance = right = right.updateHeight(oracle, rightStart, force, measured);
  5489. else
  5490. right.updateHeight(oracle, rightStart, force);
  5491. if (rebalance)
  5492. return this.balanced(left, right);
  5493. this.height = this.left.height + this.right.height;
  5494. this.outdated = false;
  5495. return this;
  5496. }
  5497. toString() { return this.left + (this.break ? " " : "-") + this.right; }
  5498. }
  5499. function mergeGaps(nodes, around) {
  5500. let before, after;
  5501. if (nodes[around] == null &&
  5502. (before = nodes[around - 1]) instanceof HeightMapGap &&
  5503. (after = nodes[around + 1]) instanceof HeightMapGap)
  5504. nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
  5505. }
  5506. const relevantWidgetHeight = 5;
  5507. class NodeBuilder {
  5508. constructor(pos, oracle) {
  5509. this.pos = pos;
  5510. this.oracle = oracle;
  5511. this.nodes = [];
  5512. this.lineStart = -1;
  5513. this.lineEnd = -1;
  5514. this.covering = null;
  5515. this.writtenTo = pos;
  5516. }
  5517. get isCovered() {
  5518. return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
  5519. }
  5520. span(_from, to) {
  5521. if (this.lineStart > -1) {
  5522. let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1];
  5523. if (last instanceof HeightMapText)
  5524. last.length += end - this.pos;
  5525. else if (end > this.pos || !this.isCovered)
  5526. this.nodes.push(new HeightMapText(end - this.pos, -1));
  5527. this.writtenTo = end;
  5528. if (to > end) {
  5529. this.nodes.push(null);
  5530. this.writtenTo++;
  5531. this.lineStart = -1;
  5532. }
  5533. }
  5534. this.pos = to;
  5535. }
  5536. point(from, to, deco) {
  5537. if (from < to || deco.heightRelevant) {
  5538. let height = deco.widget ? Math.max(0, deco.widget.estimatedHeight) : 0;
  5539. let len = to - from;
  5540. if (deco.block) {
  5541. this.addBlock(new HeightMapBlock(len, height, deco.type));
  5542. }
  5543. else if (len || height >= relevantWidgetHeight) {
  5544. this.addLineDeco(height, len);
  5545. }
  5546. }
  5547. else if (to > from) {
  5548. this.span(from, to);
  5549. }
  5550. if (this.lineEnd > -1 && this.lineEnd < this.pos)
  5551. this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
  5552. }
  5553. enterLine() {
  5554. if (this.lineStart > -1)
  5555. return;
  5556. let { from, to } = this.oracle.doc.lineAt(this.pos);
  5557. this.lineStart = from;
  5558. this.lineEnd = to;
  5559. if (this.writtenTo < from) {
  5560. if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null)
  5561. this.nodes.push(this.blankContent(this.writtenTo, from - 1));
  5562. this.nodes.push(null);
  5563. }
  5564. if (this.pos > from)
  5565. this.nodes.push(new HeightMapText(this.pos - from, -1));
  5566. this.writtenTo = this.pos;
  5567. }
  5568. blankContent(from, to) {
  5569. let gap = new HeightMapGap(to - from);
  5570. if (this.oracle.doc.lineAt(from).to == to)
  5571. gap.flags |= 4 /* SingleLine */;
  5572. return gap;
  5573. }
  5574. ensureLine() {
  5575. this.enterLine();
  5576. let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
  5577. if (last instanceof HeightMapText)
  5578. return last;
  5579. let line = new HeightMapText(0, -1);
  5580. this.nodes.push(line);
  5581. return line;
  5582. }
  5583. addBlock(block) {
  5584. this.enterLine();
  5585. if (block.type == BlockType.WidgetAfter && !this.isCovered)
  5586. this.ensureLine();
  5587. this.nodes.push(block);
  5588. this.writtenTo = this.pos = this.pos + block.length;
  5589. if (block.type != BlockType.WidgetBefore)
  5590. this.covering = block;
  5591. }
  5592. addLineDeco(height, length) {
  5593. let line = this.ensureLine();
  5594. line.length += length;
  5595. line.collapsed += length;
  5596. line.widgetHeight = Math.max(line.widgetHeight, height);
  5597. this.writtenTo = this.pos = this.pos + length;
  5598. }
  5599. finish(from) {
  5600. let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
  5601. if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered)
  5602. this.nodes.push(new HeightMapText(0, -1));
  5603. else if (this.writtenTo < this.pos || last == null)
  5604. this.nodes.push(this.blankContent(this.writtenTo, this.pos));
  5605. let pos = from;
  5606. for (let node of this.nodes) {
  5607. if (node instanceof HeightMapText)
  5608. node.updateHeight(this.oracle, pos);
  5609. pos += node ? node.length : 1;
  5610. }
  5611. return this.nodes;
  5612. }
  5613. // Always called with a region that on both sides either stretches
  5614. // to a line break or the end of the document.
  5615. // The returned array uses null to indicate line breaks, but never
  5616. // starts or ends in a line break, or has multiple line breaks next
  5617. // to each other.
  5618. static build(oracle, decorations, from, to) {
  5619. let builder = new NodeBuilder(from, oracle);
  5620. RangeSet.spans(decorations, from, to, builder, 0);
  5621. return builder.finish(from);
  5622. }
  5623. }
  5624. function heightRelevantDecoChanges(a, b, diff) {
  5625. let comp = new DecorationComparator;
  5626. RangeSet.compare(a, b, diff, comp, 0);
  5627. return comp.changes;
  5628. }
  5629. class DecorationComparator {
  5630. constructor() {
  5631. this.changes = [];
  5632. }
  5633. compareRange() { }
  5634. comparePoint(from, to, a, b) {
  5635. if (from < to || a && a.heightRelevant || b && b.heightRelevant)
  5636. addRange(from, to, this.changes, 5);
  5637. }
  5638. }
  5639. const none$3 = [];
  5640. const clickAddsSelectionRange = Facet.define();
  5641. const dragMovesSelection = Facet.define();
  5642. const mouseSelectionStyle = Facet.define();
  5643. const exceptionSink = Facet.define();
  5644. const updateListener = Facet.define();
  5645. const inputHandler = Facet.define();
  5646. /// Log or report an unhandled exception in client code. Should
  5647. /// probably only be used by extension code that allows client code to
  5648. /// provide functions, and calls those functions in a context where an
  5649. /// exception can't be propagated to calling code in a reasonable way
  5650. /// (for example when in an event handler).
  5651. ///
  5652. /// Either calls a handler registered with
  5653. /// [`EditorView.exceptionSink`](#view.EditorView^exceptionSink),
  5654. /// `window.onerror`, if defined, or `console.error` (in which case
  5655. /// it'll pass `context`, when given, as first argument).
  5656. function logException(state, exception, context) {
  5657. let handler = state.facet(exceptionSink);
  5658. if (handler.length)
  5659. handler[0](exception);
  5660. else if (window.onerror)
  5661. window.onerror(String(exception), context, undefined, undefined, exception);
  5662. else if (context)
  5663. console.error(context + ":", exception);
  5664. else
  5665. console.error(exception);
  5666. }
  5667. const editable = Facet.define({ combine: values => values.length ? values[0] : true });
  5668. /// Used to [declare](#view.PluginSpec.provide) which
  5669. /// [fields](#view.PluginValue) a [view plugin](#view.ViewPlugin)
  5670. /// provides.
  5671. class PluginFieldProvider {
  5672. /// @internal
  5673. constructor(
  5674. /// @internal
  5675. field,
  5676. /// @internal
  5677. get) {
  5678. this.field = field;
  5679. this.get = get;
  5680. }
  5681. }
  5682. /// Plugin fields are a mechanism for allowing plugins to provide
  5683. /// values that can be retrieved through the
  5684. /// [`pluginField`](#view.EditorView.pluginField) view method.
  5685. class PluginField {
  5686. /// Create a [provider](#view.PluginFieldProvider) for this field,
  5687. /// to use with a plugin's [provide](#view.PluginSpec.provide)
  5688. /// option.
  5689. from(get) {
  5690. return new PluginFieldProvider(this, get);
  5691. }
  5692. /// Define a new plugin field.
  5693. static define() { return new PluginField(); }
  5694. }
  5695. /// This field can be used by plugins to provide
  5696. /// [decorations](#view.Decoration).
  5697. ///
  5698. /// **Note**: For reasons of data flow (plugins are only updated
  5699. /// after the viewport is computed), decorations produced by plugins
  5700. /// are _not_ taken into account when predicting the vertical
  5701. /// layout structure of the editor. Thus, things like large widgets
  5702. /// or big replacements (i.e. code folding) should be provided
  5703. /// through the state-level [`decorations`
  5704. /// facet](#view.EditorView^decorations), not this plugin field.
  5705. PluginField.decorations = PluginField.define();
  5706. /// Plugins can provide additional scroll margins (space around the
  5707. /// sides of the scrolling element that should be considered
  5708. /// invisible) through this field. This can be useful when the
  5709. /// plugin introduces elements that cover part of that element (for
  5710. /// example a horizontally fixed gutter).
  5711. PluginField.scrollMargins = PluginField.define();
  5712. let nextPluginID = 0;
  5713. const viewPlugin = Facet.define();
  5714. /// View plugins associate stateful values with a view. They can
  5715. /// influence the way the content is drawn, and are notified of things
  5716. /// that happen in the view.
  5717. class ViewPlugin {
  5718. constructor(
  5719. /// @internal
  5720. id,
  5721. /// @internal
  5722. create,
  5723. /// @internal
  5724. fields) {
  5725. this.id = id;
  5726. this.create = create;
  5727. this.fields = fields;
  5728. this.extension = viewPlugin.of(this);
  5729. }
  5730. /// Define a plugin from a constructor function that creates the
  5731. /// plugin's value, given an editor view.
  5732. static define(create, spec) {
  5733. let { eventHandlers, provide, decorations } = spec || {};
  5734. let fields = [];
  5735. if (provide)
  5736. for (let provider of Array.isArray(provide) ? provide : [provide])
  5737. fields.push(provider);
  5738. if (eventHandlers)
  5739. fields.push(domEventHandlers.from((value) => ({ plugin: value, handlers: eventHandlers })));
  5740. if (decorations)
  5741. fields.push(PluginField.decorations.from(decorations));
  5742. return new ViewPlugin(nextPluginID++, create, fields);
  5743. }
  5744. /// Create a plugin for a class whose constructor takes a single
  5745. /// editor view as argument.
  5746. static fromClass(cls, spec) {
  5747. return ViewPlugin.define(view => new cls(view), spec);
  5748. }
  5749. }
  5750. const domEventHandlers = PluginField.define();
  5751. class PluginInstance {
  5752. constructor(spec) {
  5753. this.spec = spec;
  5754. // When starting an update, all plugins have this field set to the
  5755. // update object, indicating they need to be updated. When finished
  5756. // updating, it is set to `false`. Retrieving a plugin that needs to
  5757. // be updated with `view.plugin` forces an eager update.
  5758. this.mustUpdate = null;
  5759. // This is null when the plugin is initially created, but
  5760. // initialized on the first update.
  5761. this.value = null;
  5762. }
  5763. takeField(type, target) {
  5764. for (let { field, get } of this.spec.fields)
  5765. if (field == type)
  5766. target.push(get(this.value));
  5767. }
  5768. update(view) {
  5769. if (!this.value) {
  5770. try {
  5771. this.value = this.spec.create(view);
  5772. }
  5773. catch (e) {
  5774. logException(view.state, e, "CodeMirror plugin crashed");
  5775. return PluginInstance.dummy;
  5776. }
  5777. }
  5778. else if (this.mustUpdate) {
  5779. let update = this.mustUpdate;
  5780. this.mustUpdate = null;
  5781. if (!this.value.update)
  5782. return this;
  5783. try {
  5784. this.value.update(update);
  5785. }
  5786. catch (e) {
  5787. logException(update.state, e, "CodeMirror plugin crashed");
  5788. if (this.value.destroy)
  5789. try {
  5790. this.value.destroy();
  5791. }
  5792. catch (_) { }
  5793. return PluginInstance.dummy;
  5794. }
  5795. }
  5796. return this;
  5797. }
  5798. destroy(view) {
  5799. var _a;
  5800. if ((_a = this.value) === null || _a === void 0 ? void 0 : _a.destroy) {
  5801. try {
  5802. this.value.destroy();
  5803. }
  5804. catch (e) {
  5805. logException(view.state, e, "CodeMirror plugin crashed");
  5806. }
  5807. }
  5808. }
  5809. }
  5810. PluginInstance.dummy = new PluginInstance(ViewPlugin.define(() => ({})));
  5811. const editorAttributes = Facet.define({
  5812. combine: values => values.reduce((a, b) => combineAttrs(b, a), {})
  5813. });
  5814. const contentAttributes = Facet.define({
  5815. combine: values => values.reduce((a, b) => combineAttrs(b, a), {})
  5816. });
  5817. // Provide decorations
  5818. const decorations = Facet.define();
  5819. const styleModule = Facet.define();
  5820. class ChangedRange {
  5821. constructor(fromA, toA, fromB, toB) {
  5822. this.fromA = fromA;
  5823. this.toA = toA;
  5824. this.fromB = fromB;
  5825. this.toB = toB;
  5826. }
  5827. join(other) {
  5828. 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));
  5829. }
  5830. addToSet(set) {
  5831. let i = set.length, me = this;
  5832. for (; i > 0; i--) {
  5833. let range = set[i - 1];
  5834. if (range.fromA > me.toA)
  5835. continue;
  5836. if (range.toA < me.fromA)
  5837. break;
  5838. me = me.join(range);
  5839. set.splice(i - 1, 1);
  5840. }
  5841. set.splice(i, 0, me);
  5842. return set;
  5843. }
  5844. static extendWithRanges(diff, ranges) {
  5845. if (ranges.length == 0)
  5846. return diff;
  5847. let result = [];
  5848. for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
  5849. let next = dI == diff.length ? null : diff[dI], off = posA - posB;
  5850. let end = next ? next.fromB : 1e9;
  5851. while (rI < ranges.length && ranges[rI] < end) {
  5852. let from = ranges[rI], to = ranges[rI + 1];
  5853. let fromB = Math.max(posB, from), toB = Math.min(end, to);
  5854. if (fromB <= toB)
  5855. new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
  5856. if (to > end)
  5857. break;
  5858. else
  5859. rI += 2;
  5860. }
  5861. if (!next)
  5862. return result;
  5863. new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
  5864. posA = next.toA;
  5865. posB = next.toB;
  5866. }
  5867. }
  5868. }
  5869. /// View [plugins](#view.ViewPlugin) are given instances of this
  5870. /// class, which describe what happened, whenever the view is updated.
  5871. class ViewUpdate {
  5872. /// @internal
  5873. constructor(
  5874. /// The editor view that the update is associated with.
  5875. view,
  5876. /// The new editor state.
  5877. state,
  5878. /// The transactions involved in the update. May be empty.
  5879. transactions = none$3) {
  5880. this.view = view;
  5881. this.state = state;
  5882. this.transactions = transactions;
  5883. /// @internal
  5884. this.flags = 0;
  5885. this.startState = view.state;
  5886. this.changes = ChangeSet.empty(this.startState.doc.length);
  5887. for (let tr of transactions)
  5888. this.changes = this.changes.compose(tr.changes);
  5889. let changedRanges = [];
  5890. this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
  5891. this.changedRanges = changedRanges;
  5892. let focus = view.hasFocus;
  5893. if (focus != view.inputState.notifiedFocused) {
  5894. view.inputState.notifiedFocused = focus;
  5895. this.flags |= 1 /* Focus */;
  5896. }
  5897. if (this.docChanged)
  5898. this.flags |= 2 /* Height */;
  5899. }
  5900. /// Tells you whether the viewport changed in this update.
  5901. get viewportChanged() {
  5902. return (this.flags & 4 /* Viewport */) > 0;
  5903. }
  5904. /// Indicates whether the line height in the editor changed in this update.
  5905. get heightChanged() {
  5906. return (this.flags & 2 /* Height */) > 0;
  5907. }
  5908. /// Returns true when the document changed or the size of the editor
  5909. /// or the lines or characters within it has changed.
  5910. get geometryChanged() {
  5911. return this.docChanged || (this.flags & (16 /* Geometry */ | 2 /* Height */)) > 0;
  5912. }
  5913. /// True when this update indicates a focus change.
  5914. get focusChanged() {
  5915. return (this.flags & 1 /* Focus */) > 0;
  5916. }
  5917. /// Whether the document changed in this update.
  5918. get docChanged() {
  5919. return this.transactions.some(tr => tr.docChanged);
  5920. }
  5921. /// Whether the selection was explicitly set in this update.
  5922. get selectionSet() {
  5923. return this.transactions.some(tr => tr.selection);
  5924. }
  5925. /// @internal
  5926. get empty() { return this.flags == 0 && this.transactions.length == 0; }
  5927. }
  5928. function visiblePixelRange(dom, paddingTop) {
  5929. let rect = dom.getBoundingClientRect();
  5930. let left = Math.max(0, rect.left), right = Math.min(innerWidth, rect.right);
  5931. let top = Math.max(0, rect.top), bottom = Math.min(innerHeight, rect.bottom);
  5932. for (let parent = dom.parentNode; parent;) { // (Cast to any because TypeScript is useless with Node types)
  5933. if (parent.nodeType == 1) {
  5934. if ((parent.scrollHeight > parent.clientHeight || parent.scrollWidth > parent.clientWidth) &&
  5935. window.getComputedStyle(parent).overflow != "visible") {
  5936. let parentRect = parent.getBoundingClientRect();
  5937. left = Math.max(left, parentRect.left);
  5938. right = Math.min(right, parentRect.right);
  5939. top = Math.max(top, parentRect.top);
  5940. bottom = Math.min(bottom, parentRect.bottom);
  5941. }
  5942. parent = parent.parentNode;
  5943. }
  5944. else if (parent.nodeType == 11) { // Shadow root
  5945. parent = parent.host;
  5946. }
  5947. else {
  5948. break;
  5949. }
  5950. }
  5951. return { left: left - rect.left, right: right - rect.left,
  5952. top: top - (rect.top + paddingTop), bottom: bottom - (rect.top + paddingTop) };
  5953. }
  5954. // Line gaps are placeholder widgets used to hide pieces of overlong
  5955. // lines within the viewport, as a kludge to keep the editor
  5956. // responsive when a ridiculously long line is loaded into it.
  5957. class LineGap {
  5958. constructor(from, to, size) {
  5959. this.from = from;
  5960. this.to = to;
  5961. this.size = size;
  5962. }
  5963. static same(a, b) {
  5964. if (a.length != b.length)
  5965. return false;
  5966. for (let i = 0; i < a.length; i++) {
  5967. let gA = a[i], gB = b[i];
  5968. if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size)
  5969. return false;
  5970. }
  5971. return true;
  5972. }
  5973. draw(wrapping) {
  5974. return Decoration.replace({ widget: new LineGapWidget(this.size, wrapping) }).range(this.from, this.to);
  5975. }
  5976. }
  5977. class LineGapWidget extends WidgetType {
  5978. constructor(size, vertical) {
  5979. super();
  5980. this.size = size;
  5981. this.vertical = vertical;
  5982. }
  5983. eq(other) { return other.size == this.size && other.vertical == this.vertical; }
  5984. toDOM() {
  5985. let elt = document.createElement("div");
  5986. if (this.vertical) {
  5987. elt.style.height = this.size + "px";
  5988. }
  5989. else {
  5990. elt.style.width = this.size + "px";
  5991. elt.style.height = "2px";
  5992. elt.style.display = "inline-block";
  5993. }
  5994. return elt;
  5995. }
  5996. get estimatedHeight() { return this.vertical ? this.size : -1; }
  5997. }
  5998. class ViewState {
  5999. constructor(state) {
  6000. this.state = state;
  6001. // These are contentDOM-local coordinates
  6002. this.pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 };
  6003. this.inView = true;
  6004. this.paddingTop = 0;
  6005. this.paddingBottom = 0;
  6006. this.contentWidth = 0;
  6007. this.heightOracle = new HeightOracle;
  6008. this.heightMap = HeightMap.empty();
  6009. this.scrollTo = null;
  6010. // Briefly set to true when printing, to disable viewport limiting
  6011. this.printing = false;
  6012. this.visibleRanges = [];
  6013. // Cursor 'assoc' is only significant when the cursor is on a line
  6014. // wrap point, where it must stick to the character that it is
  6015. // associated with. Since browsers don't provide a reasonable
  6016. // interface to set or query this, when a selection is set that
  6017. // might cause this to be signficant, this flag is set. The next
  6018. // measure phase will check whether the cursor is on a line-wrapping
  6019. // boundary and, if so, reset it to make sure it is positioned in
  6020. // the right place.
  6021. this.mustEnforceCursorAssoc = false;
  6022. this.heightMap = this.heightMap.applyChanges(state.facet(decorations), Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
  6023. this.viewport = this.getViewport(0, null);
  6024. this.lineGaps = this.ensureLineGaps([]);
  6025. this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(false)));
  6026. this.computeVisibleRanges();
  6027. }
  6028. update(update, scrollTo = null) {
  6029. let prev = this.state;
  6030. this.state = update.state;
  6031. let newDeco = this.state.facet(decorations);
  6032. let contentChanges = update.changedRanges;
  6033. let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(update.startState.facet(decorations), newDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
  6034. let prevHeight = this.heightMap.height;
  6035. this.heightMap = this.heightMap.applyChanges(newDeco, prev.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
  6036. if (this.heightMap.height != prevHeight)
  6037. update.flags |= 2 /* Height */;
  6038. let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
  6039. if (scrollTo && (scrollTo.head < viewport.from || scrollTo.head > viewport.to) || !this.viewportIsAppropriate(viewport))
  6040. viewport = this.getViewport(0, scrollTo);
  6041. if (!viewport.eq(this.viewport)) {
  6042. this.viewport = viewport;
  6043. update.flags |= 4 /* Viewport */;
  6044. }
  6045. if (this.lineGaps.length || this.viewport.to - this.viewport.from > 15000 /* MinViewPort */)
  6046. update.flags |= this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
  6047. this.computeVisibleRanges();
  6048. if (scrollTo)
  6049. this.scrollTo = scrollTo;
  6050. if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping &&
  6051. update.state.selection.main.empty && update.state.selection.main.assoc)
  6052. this.mustEnforceCursorAssoc = true;
  6053. }
  6054. measure(docView, repeated) {
  6055. let dom = docView.dom, whiteSpace = "", direction = Direction.LTR;
  6056. if (!repeated) {
  6057. // Vertical padding
  6058. let style = window.getComputedStyle(dom);
  6059. whiteSpace = style.whiteSpace, direction = (style.direction == "rtl" ? Direction.RTL : Direction.LTR);
  6060. this.paddingTop = parseInt(style.paddingTop) || 0;
  6061. this.paddingBottom = parseInt(style.paddingBottom) || 0;
  6062. }
  6063. // Pixel viewport
  6064. let pixelViewport = this.printing ? { top: -1e8, bottom: 1e8, left: -1e8, right: 1e8 } : visiblePixelRange(dom, this.paddingTop);
  6065. let dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
  6066. this.pixelViewport = pixelViewport;
  6067. this.inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
  6068. if (!this.inView)
  6069. return 0;
  6070. let lineHeights = docView.measureVisibleLineHeights();
  6071. let refresh = false, bias = 0, result = 0, oracle = this.heightOracle;
  6072. if (!repeated) {
  6073. let contentWidth = docView.dom.clientWidth;
  6074. if (oracle.mustRefresh(lineHeights, whiteSpace, direction) ||
  6075. oracle.lineWrapping && Math.abs(contentWidth - this.contentWidth) > oracle.charWidth) {
  6076. let { lineHeight, charWidth } = docView.measureTextSize();
  6077. refresh = oracle.refresh(whiteSpace, direction, lineHeight, charWidth, contentWidth / charWidth, lineHeights);
  6078. if (refresh) {
  6079. docView.minWidth = 0;
  6080. result |= 16 /* Geometry */;
  6081. }
  6082. }
  6083. if (this.contentWidth != contentWidth) {
  6084. this.contentWidth = contentWidth;
  6085. result |= 16 /* Geometry */;
  6086. }
  6087. if (dTop > 0 && dBottom > 0)
  6088. bias = Math.max(dTop, dBottom);
  6089. else if (dTop < 0 && dBottom < 0)
  6090. bias = Math.min(dTop, dBottom);
  6091. }
  6092. oracle.heightChanged = false;
  6093. this.heightMap = this.heightMap.updateHeight(oracle, 0, refresh, new MeasuredHeights(this.viewport.from, lineHeights));
  6094. if (oracle.heightChanged)
  6095. result |= 2 /* Height */;
  6096. if (!this.viewportIsAppropriate(this.viewport, bias) ||
  6097. this.scrollTo && (this.scrollTo.head < this.viewport.from || this.scrollTo.head > this.viewport.to)) {
  6098. let newVP = this.getViewport(bias, this.scrollTo);
  6099. if (newVP.from != this.viewport.from || newVP.to != this.viewport.to) {
  6100. this.viewport = newVP;
  6101. result |= 4 /* Viewport */;
  6102. }
  6103. }
  6104. if (this.lineGaps.length || this.viewport.to - this.viewport.from > 15000 /* MinViewPort */)
  6105. result |= this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps));
  6106. this.computeVisibleRanges();
  6107. if (this.mustEnforceCursorAssoc) {
  6108. this.mustEnforceCursorAssoc = false;
  6109. // This is done in the read stage, because moving the selection
  6110. // to a line end is going to trigger a layout anyway, so it
  6111. // can't be a pure write. It should be rare that it does any
  6112. // writing.
  6113. docView.enforceCursorAssoc();
  6114. }
  6115. return result;
  6116. }
  6117. getViewport(bias, scrollTo) {
  6118. // This will divide VP.Margin between the top and the
  6119. // bottom, depending on the bias (the change in viewport position
  6120. // since the last update). It'll hold a number between 0 and 1
  6121. let marginTop = 0.5 - Math.max(-0.5, Math.min(0.5, bias / 1000 /* Margin */ / 2));
  6122. let map = this.heightMap, doc = this.state.doc, { top, bottom } = this.pixelViewport;
  6123. let viewport = new Viewport(map.lineAt(top - marginTop * 1000 /* Margin */, QueryType.ByHeight, doc, 0, 0).from, map.lineAt(bottom + (1 - marginTop) * 1000 /* Margin */, QueryType.ByHeight, doc, 0, 0).to);
  6124. // If scrollTo is given, make sure the viewport includes that position
  6125. if (scrollTo) {
  6126. if (scrollTo.head < viewport.from) {
  6127. let { top: newTop } = map.lineAt(scrollTo.head, QueryType.ByPos, doc, 0, 0);
  6128. viewport = new Viewport(map.lineAt(newTop - 1000 /* Margin */ / 2, QueryType.ByHeight, doc, 0, 0).from, map.lineAt(newTop + (bottom - top) + 1000 /* Margin */ / 2, QueryType.ByHeight, doc, 0, 0).to);
  6129. }
  6130. else if (scrollTo.head > viewport.to) {
  6131. let { bottom: newBottom } = map.lineAt(scrollTo.head, QueryType.ByPos, doc, 0, 0);
  6132. viewport = new Viewport(map.lineAt(newBottom - (bottom - top) - 1000 /* Margin */ / 2, QueryType.ByHeight, doc, 0, 0).from, map.lineAt(newBottom + 1000 /* Margin */ / 2, QueryType.ByHeight, doc, 0, 0).to);
  6133. }
  6134. }
  6135. return viewport;
  6136. }
  6137. mapViewport(viewport, changes) {
  6138. let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1);
  6139. return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.state.doc, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.state.doc, 0, 0).to);
  6140. }
  6141. // Checks if a given viewport covers the visible part of the
  6142. // document and not too much beyond that.
  6143. viewportIsAppropriate({ from, to }, bias = 0) {
  6144. let { top } = this.heightMap.lineAt(from, QueryType.ByPos, this.state.doc, 0, 0);
  6145. let { bottom } = this.heightMap.lineAt(to, QueryType.ByPos, this.state.doc, 0, 0);
  6146. return (from == 0 || top <= this.pixelViewport.top - Math.max(10 /* MinCoverMargin */, Math.min(-bias, 250 /* MaxCoverMargin */))) &&
  6147. (to == this.state.doc.length ||
  6148. bottom >= this.pixelViewport.bottom + Math.max(10 /* MinCoverMargin */, Math.min(bias, 250 /* MaxCoverMargin */))) &&
  6149. (top > this.pixelViewport.top - 2 * 1000 /* Margin */ && bottom < this.pixelViewport.bottom + 2 * 1000 /* Margin */);
  6150. }
  6151. mapLineGaps(gaps, changes) {
  6152. if (!gaps.length || changes.empty)
  6153. return gaps;
  6154. let mapped = [];
  6155. for (let gap of gaps)
  6156. if (!changes.touchesRange(gap.from, gap.to))
  6157. mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
  6158. return mapped;
  6159. }
  6160. // Computes positions in the viewport where the start or end of a
  6161. // line should be hidden, trying to reuse existing line gaps when
  6162. // appropriate to avoid unneccesary redraws.
  6163. // Uses crude character-counting for the positioning and sizing,
  6164. // since actual DOM coordinates aren't always available and
  6165. // predictable. Relies on generous margins (see LG.Margin) to hide
  6166. // the artifacts this might produce from the user.
  6167. ensureLineGaps(current) {
  6168. let gaps = [];
  6169. // This won't work at all in predominantly right-to-left text.
  6170. if (this.heightOracle.direction != Direction.LTR)
  6171. return gaps;
  6172. this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, line => {
  6173. if (line.length < 10000 /* Margin */)
  6174. return;
  6175. let structure = lineStructure(line.from, line.to, this.state);
  6176. if (structure.total < 10000 /* Margin */)
  6177. return;
  6178. let viewFrom, viewTo;
  6179. if (this.heightOracle.lineWrapping) {
  6180. if (line.from != this.viewport.from)
  6181. viewFrom = line.from;
  6182. else
  6183. viewFrom = findPosition(structure, (this.pixelViewport.top - line.top) / line.height);
  6184. if (line.to != this.viewport.to)
  6185. viewTo = line.to;
  6186. else
  6187. viewTo = findPosition(structure, (this.pixelViewport.bottom - line.top) / line.height);
  6188. }
  6189. else {
  6190. let totalWidth = structure.total * this.heightOracle.charWidth;
  6191. viewFrom = findPosition(structure, this.pixelViewport.left / totalWidth);
  6192. viewTo = findPosition(structure, this.pixelViewport.right / totalWidth);
  6193. }
  6194. let sel = this.state.selection.main;
  6195. // Make sure the gap doesn't cover a selection end
  6196. if (sel.from <= viewFrom && sel.to >= line.from)
  6197. viewFrom = sel.from;
  6198. if (sel.from <= line.to && sel.to >= viewTo)
  6199. viewTo = sel.to;
  6200. let gapTo = viewFrom - 10000 /* Margin */, gapFrom = viewTo + 10000 /* Margin */;
  6201. if (gapTo > line.from + 5000 /* HalfMargin */)
  6202. gaps.push(find(current, gap => gap.from == line.from && gap.to > gapTo - 5000 /* HalfMargin */ && gap.to < gapTo + 5000 /* HalfMargin */) ||
  6203. new LineGap(line.from, gapTo, this.gapSize(line, gapTo, true, structure)));
  6204. if (gapFrom < line.to - 5000 /* HalfMargin */)
  6205. gaps.push(find(current, gap => gap.to == line.to && gap.from > gapFrom - 5000 /* HalfMargin */ &&
  6206. gap.from < gapFrom + 5000 /* HalfMargin */) ||
  6207. new LineGap(gapFrom, line.to, this.gapSize(line, gapFrom, false, structure)));
  6208. });
  6209. return gaps;
  6210. }
  6211. gapSize(line, pos, start, structure) {
  6212. if (this.heightOracle.lineWrapping) {
  6213. let height = line.height * findFraction(structure, pos);
  6214. return start ? height : line.height - height;
  6215. }
  6216. else {
  6217. let ratio = findFraction(structure, pos);
  6218. return structure.total * this.heightOracle.charWidth * (start ? ratio : 1 - ratio);
  6219. }
  6220. }
  6221. updateLineGaps(gaps) {
  6222. if (!LineGap.same(gaps, this.lineGaps)) {
  6223. this.lineGaps = gaps;
  6224. this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this.heightOracle.lineWrapping)));
  6225. return 8 /* LineGaps */;
  6226. }
  6227. return 0;
  6228. }
  6229. computeVisibleRanges() {
  6230. let deco = this.state.facet(decorations);
  6231. if (this.lineGaps.length)
  6232. deco = deco.concat(this.lineGapDeco);
  6233. let ranges = [];
  6234. RangeSet.spans(deco, this.viewport.from, this.viewport.to, {
  6235. span(from, to) { ranges.push({ from, to }); },
  6236. point() { }
  6237. }, 20);
  6238. this.visibleRanges = ranges;
  6239. }
  6240. lineAt(pos, editorTop) {
  6241. return this.heightMap.lineAt(pos, QueryType.ByPos, this.state.doc, editorTop + this.paddingTop, 0);
  6242. }
  6243. lineAtHeight(height, editorTop) {
  6244. return this.heightMap.lineAt(height, QueryType.ByHeight, this.state.doc, editorTop + this.paddingTop, 0);
  6245. }
  6246. blockAtHeight(height, editorTop) {
  6247. return this.heightMap.blockAt(height, this.state.doc, editorTop + this.paddingTop, 0);
  6248. }
  6249. forEachLine(from, to, f, editorTop) {
  6250. return this.heightMap.forEachLine(from, to, this.state.doc, editorTop + this.paddingTop, 0, f);
  6251. }
  6252. }
  6253. /// Indicates the range of the document that is in the visible
  6254. /// viewport.
  6255. class Viewport {
  6256. constructor(from, to) {
  6257. this.from = from;
  6258. this.to = to;
  6259. }
  6260. eq(b) { return this.from == b.from && this.to == b.to; }
  6261. }
  6262. function lineStructure(from, to, state) {
  6263. let ranges = [], pos = from, total = 0;
  6264. RangeSet.spans(state.facet(decorations), from, to, {
  6265. span() { },
  6266. point(from, to) {
  6267. if (from > pos) {
  6268. ranges.push({ from: pos, to: from });
  6269. total += from - pos;
  6270. }
  6271. pos = to;
  6272. }
  6273. }, 20); // We're only interested in collapsed ranges of a significant size
  6274. if (pos < to) {
  6275. ranges.push({ from: pos, to });
  6276. total += to - pos;
  6277. }
  6278. return { total, ranges };
  6279. }
  6280. function findPosition({ total, ranges }, ratio) {
  6281. if (ratio <= 0)
  6282. return ranges[0].from;
  6283. if (ratio >= 1)
  6284. return ranges[ranges.length - 1].to;
  6285. let dist = Math.floor(total * ratio);
  6286. for (let i = 0;; i++) {
  6287. let { from, to } = ranges[i], size = to - from;
  6288. if (dist <= size)
  6289. return from + dist;
  6290. dist -= size;
  6291. }
  6292. }
  6293. function findFraction(structure, pos) {
  6294. let counted = 0;
  6295. for (let { from, to } of structure.ranges) {
  6296. if (pos <= to) {
  6297. counted += pos - from;
  6298. break;
  6299. }
  6300. counted += to - from;
  6301. }
  6302. return counted / structure.total;
  6303. }
  6304. function find(array, f) {
  6305. for (let val of array)
  6306. if (f(val))
  6307. return val;
  6308. return undefined;
  6309. }
  6310. const none$4 = [];
  6311. class DocView extends ContentView {
  6312. constructor(view) {
  6313. super();
  6314. this.view = view;
  6315. this.viewports = none$4;
  6316. this.compositionDeco = Decoration.none;
  6317. this.decorations = [];
  6318. // Track a minimum width for the editor. When measuring sizes in
  6319. // checkLayout, this is updated to point at the width of a given
  6320. // element and its extent in the document. When a change happens in
  6321. // that range, these are reset. That way, once we've seen a
  6322. // line/element of a given length, we keep the editor wide enough to
  6323. // fit at least that element, until it is changed, at which point we
  6324. // forget it again.
  6325. this.minWidth = 0;
  6326. this.minWidthFrom = 0;
  6327. this.minWidthTo = 0;
  6328. // Track whether the DOM selection was set in a lossy way, so that
  6329. // we don't mess it up when reading it back it
  6330. this.impreciseAnchor = null;
  6331. this.impreciseHead = null;
  6332. this.setDOM(view.contentDOM);
  6333. this.children = [new LineView];
  6334. this.children[0].setParent(this);
  6335. this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], this.updateDeco(), 0);
  6336. }
  6337. get root() { return this.view.root; }
  6338. get editorView() { return this.view; }
  6339. get length() { return this.view.state.doc.length; }
  6340. // Update the document view to a given state. scrollIntoView can be
  6341. // used as a hint to compute a new viewport that includes that
  6342. // position, if we know the editor is going to scroll that position
  6343. // into view.
  6344. update(update) {
  6345. let changedRanges = update.changedRanges;
  6346. if (this.minWidth > 0 && changedRanges.length) {
  6347. if (!changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo)) {
  6348. this.minWidth = 0;
  6349. }
  6350. else {
  6351. this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
  6352. this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
  6353. }
  6354. }
  6355. if (this.view.inputState.composing < 0)
  6356. this.compositionDeco = Decoration.none;
  6357. else if (update.transactions.length)
  6358. this.compositionDeco = computeCompositionDeco(this.view, update.changes);
  6359. // When the DOM nodes around the selection are moved to another
  6360. // parent, Chrome sometimes reports a different selection through
  6361. // getSelection than the one that it actually shows to the user.
  6362. // This forces a selection update when lines are joined to work
  6363. // around that. Issue #54
  6364. let forceSelection = (browser.ie || browser.chrome) && !this.compositionDeco.size && update &&
  6365. update.state.doc.lines != update.startState.doc.lines;
  6366. let prevDeco = this.decorations, deco = this.updateDeco();
  6367. let decoDiff = findChangedDeco(prevDeco, deco, update.changes);
  6368. changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
  6369. let pointerSel = update.transactions.some(tr => tr.annotation(Transaction.userEvent) == "pointerselection");
  6370. if (this.dirty == 0 /* Not */ && changedRanges.length == 0 &&
  6371. !(update.flags & (4 /* Viewport */ | 8 /* LineGaps */)) &&
  6372. update.state.selection.main.from >= this.view.viewport.from &&
  6373. update.state.selection.main.to <= this.view.viewport.to) {
  6374. this.updateSelection(forceSelection, pointerSel);
  6375. return false;
  6376. }
  6377. else {
  6378. this.updateInner(changedRanges, deco, update.startState.doc.length, forceSelection, pointerSel);
  6379. return true;
  6380. }
  6381. }
  6382. // Used both by update and checkLayout do perform the actual DOM
  6383. // update
  6384. updateInner(changes, deco, oldLength, forceSelection = false, pointerSel = false) {
  6385. this.updateChildren(changes, deco, oldLength);
  6386. this.view.observer.ignore(() => {
  6387. // Lock the height during redrawing, since Chrome sometimes
  6388. // messes with the scroll position during DOM mutation (though
  6389. // no relayout is triggered and I cannot imagine how it can
  6390. // recompute the scroll position without a layout)
  6391. this.dom.style.height = this.view.viewState.heightMap.height + "px";
  6392. this.dom.style.minWidth = this.minWidth ? this.minWidth + "px" : "";
  6393. // Chrome will sometimes, when DOM mutations occur directly
  6394. // around the selection, get confused and report a different
  6395. // selection from the one it displays (issue #218). This tries
  6396. // to detect that situation.
  6397. let track = browser.chrome ? { node: getSelection(this.view.root).focusNode, written: false } : undefined;
  6398. this.sync(track);
  6399. this.dirty = 0 /* Not */;
  6400. if (track === null || track === void 0 ? void 0 : track.written)
  6401. forceSelection = true;
  6402. this.updateSelection(forceSelection, pointerSel);
  6403. this.dom.style.height = "";
  6404. });
  6405. }
  6406. updateChildren(changes, deco, oldLength) {
  6407. let cursor = this.childCursor(oldLength);
  6408. for (let i = changes.length - 1;; i--) {
  6409. let next = i >= 0 ? changes[i] : null;
  6410. if (!next)
  6411. break;
  6412. let { fromA, toA, fromB, toB } = next;
  6413. let { content, breakAtStart, openStart, openEnd } = ContentBuilder.build(this.view.state.doc, fromB, toB, deco);
  6414. let { i: toI, off: toOff } = cursor.findPos(toA, 1);
  6415. let { i: fromI, off: fromOff } = cursor.findPos(fromA, -1);
  6416. this.replaceRange(fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd);
  6417. }
  6418. }
  6419. replaceRange(fromI, fromOff, toI, toOff, content, breakAtStart, openStart, openEnd) {
  6420. let before = this.children[fromI], last = content.length ? content[content.length - 1] : null;
  6421. let breakAtEnd = last ? last.breakAfter : breakAtStart;
  6422. // Change within a single line
  6423. if (fromI == toI && !breakAtStart && !breakAtEnd && content.length < 2 &&
  6424. before.merge(fromOff, toOff, content.length ? last : null, fromOff == 0, openStart, openEnd))
  6425. return;
  6426. let after = this.children[toI];
  6427. // Make sure the end of the line after the update is preserved in `after`
  6428. if (toOff < after.length || after.children.length && after.children[after.children.length - 1].length == 0) {
  6429. // If we're splitting a line, separate part of the start line to
  6430. // avoid that being mangled when updating the start line.
  6431. if (fromI == toI) {
  6432. after = after.split(toOff);
  6433. toOff = 0;
  6434. }
  6435. // If the element after the replacement should be merged with
  6436. // the last replacing element, update `content`
  6437. if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) {
  6438. content[content.length - 1] = after;
  6439. }
  6440. else {
  6441. // Remove the start of the after element, if necessary, and
  6442. // add it to `content`.
  6443. if (toOff || after.children.length && after.children[0].length == 0)
  6444. after.merge(0, toOff, null, false, 0, openEnd);
  6445. content.push(after);
  6446. }
  6447. }
  6448. else if (after.breakAfter) {
  6449. // The element at `toI` is entirely covered by this range.
  6450. // Preserve its line break, if any.
  6451. if (last)
  6452. last.breakAfter = 1;
  6453. else
  6454. breakAtStart = 1;
  6455. }
  6456. // Since we've handled the next element from the current elements
  6457. // now, make sure `toI` points after that.
  6458. toI++;
  6459. before.breakAfter = breakAtStart;
  6460. if (fromOff > 0) {
  6461. if (!breakAtStart && content.length && before.merge(fromOff, before.length, content[0], false, openStart, 0)) {
  6462. before.breakAfter = content.shift().breakAfter;
  6463. }
  6464. else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) {
  6465. before.merge(fromOff, before.length, null, false, openStart, 0);
  6466. }
  6467. fromI++;
  6468. }
  6469. // Try to merge widgets on the boundaries of the replacement
  6470. while (fromI < toI && content.length) {
  6471. if (this.children[toI - 1].match(content[content.length - 1]))
  6472. toI--, content.pop();
  6473. else if (this.children[fromI].match(content[0]))
  6474. fromI++, content.shift();
  6475. else
  6476. break;
  6477. }
  6478. if (fromI < toI || content.length)
  6479. this.replaceChildren(fromI, toI, content);
  6480. }
  6481. // Sync the DOM selection to this.state.selection
  6482. updateSelection(force = false, fromPointer = false) {
  6483. if (!(fromPointer || this.mayControlSelection()))
  6484. return;
  6485. let main = this.view.state.selection.main;
  6486. // FIXME need to handle the case where the selection falls inside a block range
  6487. let anchor = this.domAtPos(main.anchor);
  6488. let head = this.domAtPos(main.head);
  6489. let domSel = getSelection(this.root);
  6490. // If the selection is already here, or in an equivalent position, don't touch it
  6491. if (force || !domSel.focusNode ||
  6492. (browser.gecko && main.empty && nextToUneditable(domSel.focusNode, domSel.focusOffset)) ||
  6493. !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) ||
  6494. !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {
  6495. this.view.observer.ignore(() => {
  6496. if (main.empty) {
  6497. // Work around https://bugzilla.mozilla.org/show_bug.cgi?id=1612076
  6498. if (browser.gecko) {
  6499. let nextTo = nextToUneditable(anchor.node, anchor.offset);
  6500. if (nextTo && nextTo != (1 /* Before */ | 2 /* After */)) {
  6501. let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 /* Before */ ? 1 : -1);
  6502. if (text)
  6503. anchor = new DOMPos(text, nextTo == 1 /* Before */ ? 0 : text.nodeValue.length);
  6504. }
  6505. }
  6506. domSel.collapse(anchor.node, anchor.offset);
  6507. if (main.bidiLevel != null && domSel.cursorBidiLevel != null)
  6508. domSel.cursorBidiLevel = main.bidiLevel;
  6509. }
  6510. else if (domSel.extend) {
  6511. // Selection.extend can be used to create an 'inverted' selection
  6512. // (one where the focus is before the anchor), but not all
  6513. // browsers support it yet.
  6514. domSel.collapse(anchor.node, anchor.offset);
  6515. domSel.extend(head.node, head.offset);
  6516. }
  6517. else {
  6518. // Primitive (IE) way
  6519. let range = document.createRange();
  6520. if (main.anchor > main.head)
  6521. [anchor, head] = [head, anchor];
  6522. range.setEnd(head.node, head.offset);
  6523. range.setStart(anchor.node, anchor.offset);
  6524. domSel.removeAllRanges();
  6525. domSel.addRange(range);
  6526. }
  6527. });
  6528. }
  6529. this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
  6530. this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
  6531. }
  6532. enforceCursorAssoc() {
  6533. let cursor = this.view.state.selection.main;
  6534. let sel = getSelection(this.root);
  6535. if (!cursor.empty || !cursor.assoc || !sel.modify)
  6536. return;
  6537. let line = LineView.find(this, cursor.head); // FIXME provide view-line-range finding helper
  6538. if (!line)
  6539. return;
  6540. let lineStart = line.posAtStart;
  6541. if (cursor.head == lineStart || cursor.head == lineStart + line.length)
  6542. return;
  6543. let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1);
  6544. if (!before || !after || before.bottom > after.top)
  6545. return;
  6546. let dom = this.domAtPos(cursor.head + cursor.assoc);
  6547. sel.collapse(dom.node, dom.offset);
  6548. sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
  6549. }
  6550. mayControlSelection() {
  6551. return this.view.state.facet(editable) ? this.root.activeElement == this.dom : hasSelection(this.dom, getSelection(this.root));
  6552. }
  6553. nearest(dom) {
  6554. for (let cur = dom; cur;) {
  6555. let domView = ContentView.get(cur);
  6556. if (domView && domView.rootView == this)
  6557. return domView;
  6558. cur = cur.parentNode;
  6559. }
  6560. return null;
  6561. }
  6562. posFromDOM(node, offset) {
  6563. let view = this.nearest(node);
  6564. if (!view)
  6565. throw new RangeError("Trying to find position for a DOM position outside of the document");
  6566. return view.localPosFromDOM(node, offset) + view.posAtStart;
  6567. }
  6568. domAtPos(pos) {
  6569. let { i, off } = this.childCursor().findPos(pos, -1);
  6570. for (; i < this.children.length - 1;) {
  6571. let child = this.children[i];
  6572. if (off < child.length || child instanceof LineView)
  6573. break;
  6574. i++;
  6575. off = 0;
  6576. }
  6577. return this.children[i].domAtPos(off);
  6578. }
  6579. coordsAt(pos, side) {
  6580. for (let off = this.length, i = this.children.length - 1;; i--) {
  6581. let child = this.children[i], start = off - child.breakAfter - child.length;
  6582. if (pos > start || pos == start && (child.type == BlockType.Text || !i || this.children[i - 1].breakAfter))
  6583. return child.coordsAt(pos - start, side);
  6584. off = start;
  6585. }
  6586. }
  6587. measureVisibleLineHeights() {
  6588. let result = [], { from, to } = this.view.viewState.viewport;
  6589. let minWidth = Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
  6590. for (let pos = 0, i = 0; i < this.children.length; i++) {
  6591. let child = this.children[i], end = pos + child.length;
  6592. if (end > to)
  6593. break;
  6594. if (pos >= from) {
  6595. result.push(child.dom.getBoundingClientRect().height);
  6596. let width = child.dom.scrollWidth;
  6597. if (width > minWidth) {
  6598. this.minWidth = minWidth = width;
  6599. this.minWidthFrom = pos;
  6600. this.minWidthTo = end;
  6601. }
  6602. }
  6603. pos = end + child.breakAfter;
  6604. }
  6605. return result;
  6606. }
  6607. measureTextSize() {
  6608. for (let child of this.children) {
  6609. if (child instanceof LineView) {
  6610. let measure = child.measureTextSize();
  6611. if (measure)
  6612. return measure;
  6613. }
  6614. }
  6615. // If no workable line exists, force a layout of a measurable element
  6616. let dummy = document.createElement("div"), lineHeight, charWidth;
  6617. dummy.className = "cm-line";
  6618. dummy.textContent = "abc def ghi jkl mno pqr stu";
  6619. this.view.observer.ignore(() => {
  6620. this.dom.appendChild(dummy);
  6621. let rect = clientRectsFor(dummy.firstChild)[0];
  6622. lineHeight = dummy.getBoundingClientRect().height;
  6623. charWidth = rect ? rect.width / 27 : 7;
  6624. dummy.remove();
  6625. });
  6626. return { lineHeight, charWidth };
  6627. }
  6628. childCursor(pos = this.length) {
  6629. // Move back to start of last element when possible, so that
  6630. // `ChildCursor.findPos` doesn't have to deal with the edge case
  6631. // of being after the last element.
  6632. let i = this.children.length;
  6633. if (i)
  6634. pos -= this.children[--i].length;
  6635. return new ChildCursor(this.children, pos, i);
  6636. }
  6637. computeBlockGapDeco() {
  6638. let visible = this.view.viewState.viewport, viewports = [visible];
  6639. let { head, anchor } = this.view.state.selection.main;
  6640. if (head < visible.from || head > visible.to) {
  6641. let { from, to } = this.view.viewState.lineAt(head, 0);
  6642. viewports.push(new Viewport(from, to));
  6643. }
  6644. if (!viewports.some(({ from, to }) => anchor >= from && anchor <= to)) {
  6645. let { from, to } = this.view.viewState.lineAt(anchor, 0);
  6646. viewports.push(new Viewport(from, to));
  6647. }
  6648. this.viewports = viewports.sort((a, b) => a.from - b.from);
  6649. let deco = [];
  6650. for (let pos = 0, i = 0;; i++) {
  6651. let next = i == viewports.length ? null : viewports[i];
  6652. let end = next ? next.from - 1 : this.length;
  6653. if (end > pos) {
  6654. let height = this.view.viewState.lineAt(end, 0).bottom - this.view.viewState.lineAt(pos, 0).top;
  6655. deco.push(Decoration.replace({ widget: new BlockGapWidget(height), block: true, inclusive: true }).range(pos, end));
  6656. }
  6657. if (!next)
  6658. break;
  6659. pos = next.to + 1;
  6660. }
  6661. return Decoration.set(deco);
  6662. }
  6663. updateDeco() {
  6664. return this.decorations = [
  6665. this.computeBlockGapDeco(),
  6666. this.view.viewState.lineGapDeco,
  6667. this.compositionDeco,
  6668. ...this.view.state.facet(decorations),
  6669. ...this.view.pluginField(PluginField.decorations)
  6670. ];
  6671. }
  6672. scrollPosIntoView(pos, side) {
  6673. let rect = this.coordsAt(pos, side);
  6674. if (!rect)
  6675. return;
  6676. let mLeft = 0, mRight = 0, mTop = 0, mBottom = 0;
  6677. for (let margins of this.view.pluginField(PluginField.scrollMargins))
  6678. if (margins) {
  6679. let { left, right, top, bottom } = margins;
  6680. if (left != null)
  6681. mLeft = Math.max(mLeft, left);
  6682. if (right != null)
  6683. mRight = Math.max(mRight, right);
  6684. if (top != null)
  6685. mTop = Math.max(mTop, top);
  6686. if (bottom != null)
  6687. mBottom = Math.max(mBottom, bottom);
  6688. }
  6689. scrollRectIntoView(this.dom, {
  6690. left: rect.left - mLeft, top: rect.top - mTop,
  6691. right: rect.right + mRight, bottom: rect.bottom + mBottom
  6692. });
  6693. }
  6694. }
  6695. // Browsers appear to reserve a fixed amount of bits for height
  6696. // styles, and ignore or clip heights above that. For Chrome and
  6697. // Firefox, this is in the 20 million range, so we try to stay below
  6698. // that.
  6699. const MaxNodeHeight = 1e7;
  6700. class BlockGapWidget extends WidgetType {
  6701. constructor(height) {
  6702. super();
  6703. this.height = height;
  6704. }
  6705. toDOM() {
  6706. let elt = document.createElement("div");
  6707. this.updateDOM(elt);
  6708. return elt;
  6709. }
  6710. eq(other) { return other.height == this.height; }
  6711. updateDOM(elt) {
  6712. while (elt.lastChild)
  6713. elt.lastChild.remove();
  6714. if (this.height < MaxNodeHeight) {
  6715. elt.style.height = this.height + "px";
  6716. }
  6717. else {
  6718. elt.style.height = "";
  6719. for (let remaining = this.height; remaining > 0; remaining -= MaxNodeHeight) {
  6720. let fill = elt.appendChild(document.createElement("div"));
  6721. fill.style.height = Math.min(remaining, MaxNodeHeight) + "px";
  6722. }
  6723. }
  6724. return true;
  6725. }
  6726. get estimatedHeight() { return this.height; }
  6727. }
  6728. function computeCompositionDeco(view, changes) {
  6729. let sel = getSelection(view.root);
  6730. let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);
  6731. if (!textNode)
  6732. return Decoration.none;
  6733. let cView = view.docView.nearest(textNode);
  6734. let from, to, topNode = textNode;
  6735. if (cView instanceof InlineView) {
  6736. while (cView.parent instanceof InlineView)
  6737. cView = cView.parent;
  6738. from = cView.posAtStart;
  6739. to = from + cView.length;
  6740. topNode = cView.dom;
  6741. }
  6742. else if (cView instanceof LineView) {
  6743. while (topNode.parentNode != cView.dom)
  6744. topNode = topNode.parentNode;
  6745. let prev = topNode.previousSibling;
  6746. while (prev && !ContentView.get(prev))
  6747. prev = prev.previousSibling;
  6748. from = to = prev ? ContentView.get(prev).posAtEnd : cView.posAtStart;
  6749. }
  6750. else {
  6751. return Decoration.none;
  6752. }
  6753. let newFrom = changes.mapPos(from, 1), newTo = Math.max(newFrom, changes.mapPos(to, -1));
  6754. let text = textNode.nodeValue, { state } = view;
  6755. if (newTo - newFrom < text.length) {
  6756. if (state.sliceDoc(newFrom, Math.min(state.doc.length, newFrom + text.length)) == text)
  6757. newTo = newFrom + text.length;
  6758. else if (state.sliceDoc(Math.max(0, newTo - text.length), newTo) == text)
  6759. newFrom = newTo - text.length;
  6760. else
  6761. return Decoration.none;
  6762. }
  6763. else if (state.sliceDoc(newFrom, newTo) != text) {
  6764. return Decoration.none;
  6765. }
  6766. return Decoration.set(Decoration.replace({ widget: new CompositionWidget(topNode, textNode) }).range(newFrom, newTo));
  6767. }
  6768. class CompositionWidget extends WidgetType {
  6769. constructor(top, text) {
  6770. super();
  6771. this.top = top;
  6772. this.text = text;
  6773. }
  6774. eq(other) { return this.top == other.top && this.text == other.text; }
  6775. toDOM() { return this.top; }
  6776. ignoreEvent() { return false; }
  6777. get customView() { return CompositionView; }
  6778. }
  6779. function nearbyTextNode(node, offset, side) {
  6780. for (;;) {
  6781. if (node.nodeType == 3)
  6782. return node;
  6783. if (node.nodeType == 1 && offset > 0 && side <= 0) {
  6784. node = node.childNodes[offset - 1];
  6785. offset = maxOffset(node);
  6786. }
  6787. else if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {
  6788. node = node.childNodes[offset];
  6789. offset = 0;
  6790. }
  6791. else {
  6792. return null;
  6793. }
  6794. }
  6795. }
  6796. function nextToUneditable(node, offset) {
  6797. if (node.nodeType != 1)
  6798. return 0;
  6799. return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 /* Before */ : 0) |
  6800. (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 /* After */ : 0);
  6801. }
  6802. class DecorationComparator$1 {
  6803. constructor() {
  6804. this.changes = [];
  6805. }
  6806. compareRange(from, to) { addRange(from, to, this.changes); }
  6807. comparePoint(from, to) { addRange(from, to, this.changes); }
  6808. }
  6809. function findChangedDeco(a, b, diff) {
  6810. let comp = new DecorationComparator$1;
  6811. RangeSet.compare(a, b, diff, comp);
  6812. return comp.changes;
  6813. }
  6814. function groupAt(state, pos, bias = 1) {
  6815. let categorize = state.charCategorizer(pos);
  6816. let line = state.doc.lineAt(pos), linePos = pos - line.from;
  6817. if (line.length == 0)
  6818. return EditorSelection.cursor(pos);
  6819. if (linePos == 0)
  6820. bias = 1;
  6821. else if (linePos == line.length)
  6822. bias = -1;
  6823. let from = linePos, to = linePos;
  6824. if (bias < 0)
  6825. from = findClusterBreak(line.text, linePos, false);
  6826. else
  6827. to = findClusterBreak(line.text, linePos);
  6828. let cat = categorize(line.text.slice(from, to));
  6829. while (from > 0) {
  6830. let prev = findClusterBreak(line.text, from, false);
  6831. if (categorize(line.text.slice(prev, from)) != cat)
  6832. break;
  6833. from = prev;
  6834. }
  6835. while (to < line.length) {
  6836. let next = findClusterBreak(line.text, to);
  6837. if (categorize(line.text.slice(to, next)) != cat)
  6838. break;
  6839. to = next;
  6840. }
  6841. return EditorSelection.range(from + line.from, to + line.from);
  6842. }
  6843. // Search the DOM for the {node, offset} position closest to the given
  6844. // coordinates. Very inefficient and crude, but can usually be avoided
  6845. // by calling caret(Position|Range)FromPoint instead.
  6846. // FIXME holding arrow-up/down at the end of the viewport is a rather
  6847. // common use case that will repeatedly trigger this code. Maybe
  6848. // introduce some element of binary search after all?
  6849. function getdx(x, rect) {
  6850. return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
  6851. }
  6852. function getdy(y, rect) {
  6853. return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
  6854. }
  6855. function yOverlap(a, b) {
  6856. return a.top < b.bottom - 1 && a.bottom > b.top + 1;
  6857. }
  6858. function upTop(rect, top) {
  6859. return top < rect.top ? { top, left: rect.left, right: rect.right, bottom: rect.bottom } : rect;
  6860. }
  6861. function upBot(rect, bottom) {
  6862. return bottom > rect.bottom ? { top: rect.top, left: rect.left, right: rect.right, bottom } : rect;
  6863. }
  6864. function domPosAtCoords(parent, x, y) {
  6865. let closest, closestRect, closestX, closestY;
  6866. let above, below, aboveRect, belowRect;
  6867. for (let child = parent.firstChild; child; child = child.nextSibling) {
  6868. let rects = clientRectsFor(child);
  6869. for (let i = 0; i < rects.length; i++) {
  6870. let rect = rects[i];
  6871. if (closestRect && yOverlap(closestRect, rect))
  6872. rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
  6873. let dx = getdx(x, rect), dy = getdy(y, rect);
  6874. if (dx == 0 && dy == 0)
  6875. return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);
  6876. if (!closest || closestY > dy || closestY == dy && closestX > dx) {
  6877. closest = child;
  6878. closestRect = rect;
  6879. closestX = dx;
  6880. closestY = dy;
  6881. }
  6882. if (dx == 0) {
  6883. if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
  6884. above = child;
  6885. aboveRect = rect;
  6886. }
  6887. else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
  6888. below = child;
  6889. belowRect = rect;
  6890. }
  6891. }
  6892. else if (aboveRect && yOverlap(aboveRect, rect)) {
  6893. aboveRect = upBot(aboveRect, rect.bottom);
  6894. }
  6895. else if (belowRect && yOverlap(belowRect, rect)) {
  6896. belowRect = upTop(belowRect, rect.top);
  6897. }
  6898. }
  6899. }
  6900. if (aboveRect && aboveRect.bottom >= y) {
  6901. closest = above;
  6902. closestRect = aboveRect;
  6903. }
  6904. else if (belowRect && belowRect.top <= y) {
  6905. closest = below;
  6906. closestRect = belowRect;
  6907. }
  6908. if (!closest)
  6909. return { node: parent, offset: 0 };
  6910. let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
  6911. if (closest.nodeType == 3)
  6912. return domPosInText(closest, clipX, y);
  6913. if (!closestX && closest.contentEditable == "true")
  6914. return domPosAtCoords(closest, clipX, y);
  6915. let offset = Array.prototype.indexOf.call(parent.childNodes, closest) +
  6916. (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0);
  6917. return { node: parent, offset };
  6918. }
  6919. function domPosInText(node, x, y) {
  6920. let len = node.nodeValue.length, range = tempRange();
  6921. for (let i = 0; i < len; i++) {
  6922. range.setEnd(node, i + 1);
  6923. range.setStart(node, i);
  6924. let rects = range.getClientRects();
  6925. for (let j = 0; j < rects.length; j++) {
  6926. let rect = rects[j];
  6927. if (rect.top == rect.bottom)
  6928. continue;
  6929. if (rect.left - 1 <= x && rect.right + 1 >= x &&
  6930. rect.top - 1 <= y && rect.bottom + 1 >= y) {
  6931. let right = x >= (rect.left + rect.right) / 2, after = right;
  6932. if (browser.chrome || browser.gecko) {
  6933. // Check for RTL on browsers that support getting client
  6934. // rects for empty ranges.
  6935. range.setEnd(node, i);
  6936. let rectBefore = range.getBoundingClientRect();
  6937. if (rectBefore.left == rect.right)
  6938. after = !right;
  6939. }
  6940. return { node, offset: i + (after ? 1 : 0) };
  6941. }
  6942. }
  6943. }
  6944. return { node, offset: 0 };
  6945. }
  6946. function posAtCoords(view, { x, y }, bias = -1) {
  6947. let content = view.contentDOM.getBoundingClientRect(), block;
  6948. let halfLine = view.defaultLineHeight / 2;
  6949. for (let bounced = false;;) {
  6950. block = view.blockAtHeight(y, content.top);
  6951. if (block.top > y || block.bottom < y) {
  6952. bias = block.top > y ? -1 : 1;
  6953. y = Math.min(block.bottom - halfLine, Math.max(block.top + halfLine, y));
  6954. if (bounced)
  6955. return -1;
  6956. else
  6957. bounced = true;
  6958. }
  6959. if (block.type == BlockType.Text)
  6960. break;
  6961. y = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
  6962. }
  6963. let lineStart = block.from;
  6964. // If this is outside of the rendered viewport, we can't determine a position
  6965. if (lineStart < view.viewport.from)
  6966. return view.viewport.from == 0 ? 0 : null;
  6967. if (lineStart > view.viewport.to)
  6968. return view.viewport.to == view.state.doc.length ? view.state.doc.length : null;
  6969. // Clip x to the viewport sides
  6970. x = Math.max(content.left + 1, Math.min(content.right - 1, x));
  6971. let root = view.root, element = root.elementFromPoint(x, y);
  6972. // There's visible editor content under the point, so we can try
  6973. // using caret(Position|Range)FromPoint as a shortcut
  6974. let node, offset = -1;
  6975. if (element && view.contentDOM.contains(element) && !(view.docView.nearest(element) instanceof WidgetView)) {
  6976. if (root.caretPositionFromPoint) {
  6977. let pos = root.caretPositionFromPoint(x, y);
  6978. if (pos)
  6979. ({ offsetNode: node, offset } = pos);
  6980. }
  6981. else if (root.caretRangeFromPoint) {
  6982. let range = root.caretRangeFromPoint(x, y);
  6983. if (range)
  6984. ({ startContainer: node, startOffset: offset } = range);
  6985. }
  6986. }
  6987. // No luck, do our own (potentially expensive) search
  6988. if (!node || !view.docView.dom.contains(node)) {
  6989. let line = LineView.find(view.docView, lineStart);
  6990. ({ node, offset } = domPosAtCoords(line.dom, x, y));
  6991. }
  6992. return view.docView.posFromDOM(node, offset);
  6993. }
  6994. function moveToLineBoundary(view, start, forward, includeWrap) {
  6995. let line = view.state.doc.lineAt(start.head);
  6996. let coords = !includeWrap || !view.lineWrapping ? null
  6997. : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
  6998. if (coords) {
  6999. let editorRect = view.dom.getBoundingClientRect();
  7000. let pos = view.posAtCoords({ x: forward == (view.textDirection == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
  7001. y: (coords.top + coords.bottom) / 2 });
  7002. if (pos != null)
  7003. return EditorSelection.cursor(pos, forward ? -1 : 1);
  7004. }
  7005. let lineView = LineView.find(view.docView, start.head);
  7006. let end = lineView ? (forward ? lineView.posAtEnd : lineView.posAtStart) : (forward ? line.to : line.from);
  7007. return EditorSelection.cursor(end, forward ? -1 : 1);
  7008. }
  7009. function moveByChar(view, start, forward, by) {
  7010. let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line);
  7011. for (let cur = start, check = null;;) {
  7012. let next = moveVisually(line, spans, view.textDirection, cur, forward), char = movedOver;
  7013. if (!next) {
  7014. if (line.number == (forward ? view.state.doc.lines : 1))
  7015. return cur;
  7016. char = "\n";
  7017. line = view.state.doc.line(line.number + (forward ? 1 : -1));
  7018. spans = view.bidiSpans(line);
  7019. next = EditorSelection.cursor(forward ? line.from : line.to);
  7020. }
  7021. if (!check) {
  7022. if (!by)
  7023. return next;
  7024. check = by(char);
  7025. }
  7026. else if (!check(char)) {
  7027. return cur;
  7028. }
  7029. cur = next;
  7030. }
  7031. }
  7032. function byGroup(view, pos, start) {
  7033. let categorize = view.state.charCategorizer(pos);
  7034. let cat = categorize(start);
  7035. return (next) => {
  7036. let nextCat = categorize(next);
  7037. if (cat == CharCategory.Space)
  7038. cat = nextCat;
  7039. return cat == nextCat;
  7040. };
  7041. }
  7042. function moveVertically(view, start, forward, distance) {
  7043. var _a;
  7044. let startPos = start.head, dir = forward ? 1 : -1;
  7045. if (startPos == (forward ? view.state.doc.length : 0))
  7046. return EditorSelection.cursor(startPos);
  7047. let startCoords = view.coordsAtPos(startPos);
  7048. if (startCoords) {
  7049. let rect = view.dom.getBoundingClientRect();
  7050. let goal = (_a = start.goalColumn) !== null && _a !== void 0 ? _a : startCoords.left - rect.left;
  7051. let resolvedGoal = rect.left + goal;
  7052. let dist = distance !== null && distance !== void 0 ? distance : 5;
  7053. for (let startY = dir < 0 ? startCoords.top : startCoords.bottom, extra = 0; extra < 50; extra += 10) {
  7054. let pos = posAtCoords(view, { x: resolvedGoal, y: startY + (dist + extra) * dir }, dir);
  7055. if (pos == null)
  7056. break;
  7057. if (pos != startPos)
  7058. return EditorSelection.cursor(pos, undefined, undefined, goal);
  7059. }
  7060. }
  7061. // Outside of the drawn viewport, use a crude column-based approach
  7062. let { doc } = view.state, line = doc.lineAt(startPos), tabSize = view.state.tabSize;
  7063. let goal = start.goalColumn, goalCol = 0;
  7064. if (goal == null) {
  7065. for (const iter = doc.iterRange(line.from, startPos); !iter.next().done;)
  7066. goalCol = countColumn(iter.value, goalCol, tabSize);
  7067. goal = goalCol * view.defaultCharacterWidth;
  7068. }
  7069. else {
  7070. goalCol = Math.round(goal / view.defaultCharacterWidth);
  7071. }
  7072. if (dir < 0 && line.from == 0)
  7073. return EditorSelection.cursor(0);
  7074. else if (dir > 0 && line.to == doc.length)
  7075. return EditorSelection.cursor(line.to);
  7076. let otherLine = doc.line(line.number + dir);
  7077. let result = otherLine.from;
  7078. let seen = 0;
  7079. for (const iter = doc.iterRange(otherLine.from, otherLine.to); seen >= goalCol && !iter.next().done;) {
  7080. const { offset, leftOver } = findColumn(iter.value, seen, goalCol, tabSize);
  7081. seen = goalCol - leftOver;
  7082. result += offset;
  7083. }
  7084. return EditorSelection.cursor(result, undefined, undefined, goal);
  7085. }
  7086. // This will also be where dragging info and such goes
  7087. class InputState {
  7088. constructor(view) {
  7089. this.lastKeyCode = 0;
  7090. this.lastKeyTime = 0;
  7091. this.lastSelectionOrigin = null;
  7092. this.lastSelectionTime = 0;
  7093. this.lastEscPress = 0;
  7094. this.scrollHandlers = [];
  7095. this.registeredEvents = [];
  7096. this.customHandlers = [];
  7097. // -1 means not in a composition. Otherwise, this counts the number
  7098. // of changes made during the composition. The count is used to
  7099. // avoid treating the start state of the composition, before any
  7100. // changes have been made, as part of the composition.
  7101. this.composing = -1;
  7102. this.compositionEndedAt = 0;
  7103. this.mouseSelection = null;
  7104. for (let type in handlers) {
  7105. let handler = handlers[type];
  7106. view.contentDOM.addEventListener(type, (event) => {
  7107. if (!eventBelongsToEditor(view, event) || this.ignoreDuringComposition(event) ||
  7108. type == "keydown" && this.screenKeyEvent(view, event))
  7109. return;
  7110. if (this.mustFlushObserver(event))
  7111. view.observer.forceFlush();
  7112. if (this.runCustomHandlers(type, view, event))
  7113. event.preventDefault();
  7114. else
  7115. handler(view, event);
  7116. });
  7117. this.registeredEvents.push(type);
  7118. }
  7119. // Must always run, even if a custom handler handled the event
  7120. view.contentDOM.addEventListener("keydown", (event) => {
  7121. view.inputState.lastKeyCode = event.keyCode;
  7122. view.inputState.lastKeyTime = Date.now();
  7123. });
  7124. this.notifiedFocused = view.hasFocus;
  7125. this.ensureHandlers(view);
  7126. }
  7127. setSelectionOrigin(origin) {
  7128. this.lastSelectionOrigin = origin;
  7129. this.lastSelectionTime = Date.now();
  7130. }
  7131. ensureHandlers(view) {
  7132. let handlers = this.customHandlers = view.pluginField(domEventHandlers);
  7133. for (let set of handlers) {
  7134. for (let type in set.handlers)
  7135. if (this.registeredEvents.indexOf(type) < 0 && type != "scroll") {
  7136. this.registeredEvents.push(type);
  7137. view.contentDOM.addEventListener(type, (event) => {
  7138. if (!eventBelongsToEditor(view, event))
  7139. return;
  7140. if (this.runCustomHandlers(type, view, event))
  7141. event.preventDefault();
  7142. });
  7143. }
  7144. }
  7145. }
  7146. runCustomHandlers(type, view, event) {
  7147. for (let set of this.customHandlers) {
  7148. let handler = set.handlers[type], handled = false;
  7149. if (handler) {
  7150. try {
  7151. handled = handler.call(set.plugin, event, view);
  7152. }
  7153. catch (e) {
  7154. logException(view.state, e);
  7155. }
  7156. if (handled || event.defaultPrevented) {
  7157. // Chrome for Android often applies a bunch of nonsensical
  7158. // DOM changes after an enter press, even when
  7159. // preventDefault-ed. This tries to ignore those.
  7160. if (browser.android && type == "keydown" && event.keyCode == 13)
  7161. view.observer.flushSoon();
  7162. return true;
  7163. }
  7164. }
  7165. }
  7166. return false;
  7167. }
  7168. runScrollHandlers(view, event) {
  7169. for (let set of this.customHandlers) {
  7170. let handler = set.handlers.scroll;
  7171. if (handler) {
  7172. try {
  7173. handler.call(set.plugin, event, view);
  7174. }
  7175. catch (e) {
  7176. logException(view.state, e);
  7177. }
  7178. }
  7179. }
  7180. }
  7181. ignoreDuringComposition(event) {
  7182. if (!/^key/.test(event.type))
  7183. return false;
  7184. if (this.composing > 0)
  7185. return true;
  7186. // See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
  7187. // On some input method editors (IMEs), the Enter key is used to
  7188. // confirm character selection. On Safari, when Enter is pressed,
  7189. // compositionend and keydown events are sometimes emitted in the
  7190. // wrong order. The key event should still be ignored, even when
  7191. // it happens after the compositionend event.
  7192. if (browser.safari && event.timeStamp - this.compositionEndedAt < 500) {
  7193. this.compositionEndedAt = 0;
  7194. return true;
  7195. }
  7196. return false;
  7197. }
  7198. screenKeyEvent(view, event) {
  7199. let protectedTab = event.keyCode == 9 && Date.now() < this.lastEscPress + 2000;
  7200. if (event.keyCode == 27)
  7201. this.lastEscPress = Date.now();
  7202. else if (modifierCodes.indexOf(event.keyCode) < 0)
  7203. this.lastEscPress = 0;
  7204. return protectedTab;
  7205. }
  7206. mustFlushObserver(event) {
  7207. return (event.type == "keydown" && event.keyCode != 229) || event.type == "compositionend";
  7208. }
  7209. startMouseSelection(view, event, style) {
  7210. if (this.mouseSelection)
  7211. this.mouseSelection.destroy();
  7212. this.mouseSelection = new MouseSelection(this, view, event, style);
  7213. }
  7214. update(update) {
  7215. if (this.mouseSelection)
  7216. this.mouseSelection.update(update);
  7217. this.lastKeyCode = this.lastSelectionTime = 0;
  7218. }
  7219. destroy() {
  7220. if (this.mouseSelection)
  7221. this.mouseSelection.destroy();
  7222. }
  7223. }
  7224. // Key codes for modifier keys
  7225. const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
  7226. class MouseSelection {
  7227. constructor(inputState, view, startEvent, style) {
  7228. this.inputState = inputState;
  7229. this.view = view;
  7230. this.startEvent = startEvent;
  7231. this.style = style;
  7232. let doc = view.contentDOM.ownerDocument;
  7233. doc.addEventListener("mousemove", this.move = this.move.bind(this));
  7234. doc.addEventListener("mouseup", this.up = this.up.bind(this));
  7235. this.extend = startEvent.shiftKey;
  7236. this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
  7237. this.dragMove = dragMovesSelection$1(view, startEvent);
  7238. this.dragging = isInPrimarySelection(view, startEvent) ? null : false;
  7239. // When clicking outside of the selection, immediately apply the
  7240. // effect of starting the selection
  7241. if (this.dragging === false) {
  7242. startEvent.preventDefault();
  7243. this.select(startEvent);
  7244. }
  7245. }
  7246. move(event) {
  7247. if (event.buttons == 0)
  7248. return this.destroy();
  7249. if (this.dragging !== false)
  7250. return;
  7251. this.select(event);
  7252. }
  7253. up(event) {
  7254. if (this.dragging == null)
  7255. this.select(this.startEvent);
  7256. if (!this.dragging)
  7257. event.preventDefault();
  7258. this.destroy();
  7259. }
  7260. destroy() {
  7261. let doc = this.view.contentDOM.ownerDocument;
  7262. doc.removeEventListener("mousemove", this.move);
  7263. doc.removeEventListener("mouseup", this.up);
  7264. this.inputState.mouseSelection = null;
  7265. }
  7266. select(event) {
  7267. let selection = this.style.get(event, this.extend, this.multiple);
  7268. if (!selection.eq(this.view.state.selection) || selection.main.assoc != this.view.state.selection.main.assoc)
  7269. this.view.dispatch({
  7270. selection,
  7271. annotations: Transaction.userEvent.of("pointerselection"),
  7272. scrollIntoView: true
  7273. });
  7274. }
  7275. update(update) {
  7276. if (update.docChanged && this.dragging)
  7277. this.dragging = this.dragging.map(update.changes);
  7278. this.style.update(update);
  7279. }
  7280. }
  7281. function addsSelectionRange(view, event) {
  7282. let facet = view.state.facet(clickAddsSelectionRange);
  7283. return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
  7284. }
  7285. function dragMovesSelection$1(view, event) {
  7286. let facet = view.state.facet(dragMovesSelection);
  7287. return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
  7288. }
  7289. function isInPrimarySelection(view, event) {
  7290. let { main } = view.state.selection;
  7291. if (main.empty)
  7292. return false;
  7293. // On boundary clicks, check whether the coordinates are inside the
  7294. // selection's client rectangles
  7295. let sel = getSelection(view.root);
  7296. if (sel.rangeCount == 0)
  7297. return true;
  7298. let rects = sel.getRangeAt(0).getClientRects();
  7299. for (let i = 0; i < rects.length; i++) {
  7300. let rect = rects[i];
  7301. if (rect.left <= event.clientX && rect.right >= event.clientX &&
  7302. rect.top <= event.clientY && rect.bottom >= event.clientY)
  7303. return true;
  7304. }
  7305. return false;
  7306. }
  7307. function eventBelongsToEditor(view, event) {
  7308. if (!event.bubbles)
  7309. return true;
  7310. if (event.defaultPrevented)
  7311. return false;
  7312. for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode)
  7313. if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))
  7314. return false;
  7315. return true;
  7316. }
  7317. const handlers = Object.create(null);
  7318. // This is very crude, but unfortunately both these browsers _pretend_
  7319. // that they have a clipboard API—all the objects and methods are
  7320. // there, they just don't work, and they are hard to test.
  7321. const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
  7322. (browser.ios && browser.webkit_version < 604);
  7323. function capturePaste(view) {
  7324. let parent = view.dom.parentNode;
  7325. if (!parent)
  7326. return;
  7327. let target = parent.appendChild(document.createElement("textarea"));
  7328. target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  7329. target.focus();
  7330. setTimeout(() => {
  7331. view.focus();
  7332. target.remove();
  7333. doPaste(view, target.value);
  7334. }, 50);
  7335. }
  7336. function doPaste(view, input) {
  7337. let { state } = view, changes, i = 1, text = state.toText(input);
  7338. let byLine = text.lines == state.selection.ranges.length;
  7339. let linewise = lastLinewiseCopy && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString();
  7340. if (linewise) {
  7341. changes = {
  7342. changes: state.selection.ranges.map(r => state.doc.lineAt(r.from))
  7343. .filter((l, i, a) => i == 0 || a[i - 1] != l)
  7344. .map(line => ({ from: line.from, insert: (byLine ? text.line(i++).text : input) + state.lineBreak }))
  7345. };
  7346. }
  7347. else if (byLine) {
  7348. changes = state.changeByRange(range => {
  7349. let line = text.line(i++);
  7350. return { changes: { from: range.from, to: range.to, insert: line.text },
  7351. range: EditorSelection.cursor(range.from + line.length) };
  7352. });
  7353. }
  7354. else {
  7355. changes = state.replaceSelection(text);
  7356. }
  7357. view.dispatch(changes, {
  7358. annotations: Transaction.userEvent.of("paste"),
  7359. scrollIntoView: true
  7360. });
  7361. }
  7362. function mustCapture(event) {
  7363. let mods = (event.ctrlKey ? 1 /* Ctrl */ : 0) | (event.metaKey ? 8 /* Meta */ : 0) |
  7364. (event.altKey ? 2 /* Alt */ : 0) | (event.shiftKey ? 4 /* Shift */ : 0);
  7365. let code = event.keyCode, macCtrl = browser.mac && mods == 1 /* Ctrl */;
  7366. return code == 8 || (macCtrl && code == 72) || // Backspace, Ctrl-h on Mac
  7367. code == 46 || (macCtrl && code == 68) || // Delete, Ctrl-d on Mac
  7368. code == 27 || // Esc
  7369. (mods == (browser.mac ? 8 /* Meta */ : 1 /* Ctrl */) && // Ctrl/Cmd-[biyz]
  7370. (code == 66 || code == 73 || code == 89 || code == 90));
  7371. }
  7372. handlers.keydown = (view, event) => {
  7373. if (mustCapture(event))
  7374. event.preventDefault();
  7375. view.inputState.setSelectionOrigin("keyboardselection");
  7376. };
  7377. handlers.touchdown = handlers.touchmove = view => {
  7378. view.inputState.setSelectionOrigin("pointerselection");
  7379. };
  7380. handlers.mousedown = (view, event) => {
  7381. let style = null;
  7382. for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
  7383. style = makeStyle(view, event);
  7384. if (style)
  7385. break;
  7386. }
  7387. if (!style && event.button == 0)
  7388. style = basicMouseSelection(view, event);
  7389. if (style) {
  7390. if (view.root.activeElement != view.contentDOM)
  7391. view.observer.ignore(() => focusPreventScroll(view.contentDOM));
  7392. view.inputState.startMouseSelection(view, event, style);
  7393. }
  7394. };
  7395. function rangeForClick(view, pos, bias, type) {
  7396. if (type == 1) { // Single click
  7397. return EditorSelection.cursor(pos, bias);
  7398. }
  7399. else if (type == 2) { // Double click
  7400. return groupAt(view.state, pos, bias);
  7401. }
  7402. else { // Triple click
  7403. let line = LineView.find(view.docView, pos);
  7404. if (line)
  7405. return EditorSelection.range(line.posAtStart, line.posAtEnd);
  7406. let { from, to } = view.state.doc.lineAt(pos);
  7407. return EditorSelection.range(from, to);
  7408. }
  7409. }
  7410. let insideY = (y, rect) => y >= rect.top && y <= rect.bottom;
  7411. let inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;
  7412. // Try to determine, for the given coordinates, associated with the
  7413. // given position, whether they are related to the element before or
  7414. // the element after the position.
  7415. function findPositionSide(view, pos, x, y) {
  7416. let line = LineView.find(view.docView, pos);
  7417. if (!line)
  7418. return 1;
  7419. let off = pos - line.posAtStart;
  7420. // Line boundaries point into the line
  7421. if (off == 0)
  7422. return 1;
  7423. if (off == line.length)
  7424. return -1;
  7425. // Positions on top of an element point at that element
  7426. let before = line.coordsAt(off, -1);
  7427. if (before && inside(x, y, before))
  7428. return -1;
  7429. let after = line.coordsAt(off, 1);
  7430. if (after && inside(x, y, after))
  7431. return 1;
  7432. // This is probably a line wrap point. Pick before if the point is
  7433. // beside it.
  7434. return before && insideY(y, before) ? -1 : 1;
  7435. }
  7436. function queryPos(view, event) {
  7437. let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
  7438. if (pos == null)
  7439. return null;
  7440. return { pos, bias: findPositionSide(view, pos, event.clientX, event.clientY) };
  7441. }
  7442. const BadMouseDetail = browser.ie && browser.ie_version <= 11;
  7443. let lastMouseDown = null, lastMouseDownCount = 0;
  7444. function getClickType(event) {
  7445. if (!BadMouseDetail)
  7446. return event.detail;
  7447. let last = lastMouseDown;
  7448. lastMouseDown = event;
  7449. return lastMouseDownCount = !last || (last.timeStamp > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
  7450. Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1;
  7451. }
  7452. function basicMouseSelection(view, event) {
  7453. let start = queryPos(view, event), type = getClickType(event);
  7454. let startSel = view.state.selection;
  7455. let last = start, lastEvent = event;
  7456. return {
  7457. update(update) {
  7458. if (update.changes) {
  7459. if (start)
  7460. start.pos = update.changes.mapPos(start.pos);
  7461. startSel = startSel.map(update.changes);
  7462. }
  7463. },
  7464. get(event, extend, multiple) {
  7465. let cur;
  7466. if (event.clientX == lastEvent.clientX && event.clientY == lastEvent.clientY)
  7467. cur = last;
  7468. else {
  7469. cur = last = queryPos(view, event);
  7470. lastEvent = event;
  7471. }
  7472. if (!cur || !start)
  7473. return startSel;
  7474. let range = rangeForClick(view, cur.pos, cur.bias, type);
  7475. if (start.pos != cur.pos && !extend) {
  7476. let startRange = rangeForClick(view, start.pos, start.bias, type);
  7477. let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to);
  7478. range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
  7479. }
  7480. if (extend)
  7481. return startSel.replaceRange(startSel.main.extend(range.from, range.to));
  7482. else if (multiple)
  7483. return startSel.addRange(range);
  7484. else
  7485. return EditorSelection.create([range]);
  7486. }
  7487. };
  7488. }
  7489. handlers.dragstart = (view, event) => {
  7490. let { selection: { main } } = view.state;
  7491. let { mouseSelection } = view.inputState;
  7492. if (mouseSelection)
  7493. mouseSelection.dragging = main;
  7494. if (event.dataTransfer) {
  7495. event.dataTransfer.setData("Text", view.state.sliceDoc(main.from, main.to));
  7496. event.dataTransfer.effectAllowed = "copyMove";
  7497. }
  7498. };
  7499. handlers.drop = (view, event) => {
  7500. if (!event.dataTransfer)
  7501. return;
  7502. let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY });
  7503. let text = event.dataTransfer.getData("Text");
  7504. if (dropPos == null || !text)
  7505. return;
  7506. event.preventDefault();
  7507. let { mouseSelection } = view.inputState;
  7508. let del = mouseSelection && mouseSelection.dragging && mouseSelection.dragMove ?
  7509. { from: mouseSelection.dragging.from, to: mouseSelection.dragging.to } : null;
  7510. let ins = { from: dropPos, insert: text };
  7511. let changes = view.state.changes(del ? [del, ins] : ins);
  7512. view.focus();
  7513. view.dispatch({
  7514. changes,
  7515. selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) },
  7516. annotations: Transaction.userEvent.of("drop")
  7517. });
  7518. };
  7519. handlers.paste = (view, event) => {
  7520. view.observer.flush();
  7521. let data = brokenClipboardAPI ? null : event.clipboardData;
  7522. let text = data && data.getData("text/plain");
  7523. if (text) {
  7524. doPaste(view, text);
  7525. event.preventDefault();
  7526. }
  7527. else {
  7528. capturePaste(view);
  7529. }
  7530. };
  7531. function captureCopy(view, text) {
  7532. // The extra wrapper is somehow necessary on IE/Edge to prevent the
  7533. // content from being mangled when it is put onto the clipboard
  7534. let parent = view.dom.parentNode;
  7535. if (!parent)
  7536. return;
  7537. let target = parent.appendChild(document.createElement("textarea"));
  7538. target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  7539. target.value = text;
  7540. target.focus();
  7541. target.selectionEnd = text.length;
  7542. target.selectionStart = 0;
  7543. setTimeout(() => {
  7544. target.remove();
  7545. view.focus();
  7546. }, 50);
  7547. }
  7548. function copiedRange(state) {
  7549. let content = [], ranges = [], linewise = false;
  7550. for (let range of state.selection.ranges)
  7551. if (!range.empty) {
  7552. content.push(state.sliceDoc(range.from, range.to));
  7553. ranges.push(range);
  7554. }
  7555. if (!content.length) {
  7556. // Nothing selected, do a line-wise copy
  7557. let upto = -1;
  7558. for (let { from } of state.selection.ranges) {
  7559. let line = state.doc.lineAt(from);
  7560. if (line.number > upto) {
  7561. content.push(line.text);
  7562. ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) });
  7563. }
  7564. upto = line.number;
  7565. }
  7566. linewise = true;
  7567. }
  7568. return { text: content.join(state.lineBreak), ranges, linewise };
  7569. }
  7570. let lastLinewiseCopy = null;
  7571. handlers.copy = handlers.cut = (view, event) => {
  7572. let { text, ranges, linewise } = copiedRange(view.state);
  7573. if (!text)
  7574. return;
  7575. lastLinewiseCopy = linewise ? text : null;
  7576. let data = brokenClipboardAPI ? null : event.clipboardData;
  7577. if (data) {
  7578. event.preventDefault();
  7579. data.clearData();
  7580. data.setData("text/plain", text);
  7581. }
  7582. else {
  7583. captureCopy(view, text);
  7584. }
  7585. if (event.type == "cut")
  7586. view.dispatch({
  7587. changes: ranges,
  7588. scrollIntoView: true,
  7589. annotations: Transaction.userEvent.of("cut")
  7590. });
  7591. };
  7592. handlers.focus = handlers.blur = view => {
  7593. setTimeout(() => {
  7594. if (view.hasFocus != view.inputState.notifiedFocused)
  7595. view.update([]);
  7596. }, 10);
  7597. };
  7598. handlers.beforeprint = view => {
  7599. view.viewState.printing = true;
  7600. view.requestMeasure();
  7601. setTimeout(() => {
  7602. view.viewState.printing = false;
  7603. view.requestMeasure();
  7604. }, 2000);
  7605. };
  7606. function forceClearComposition(view) {
  7607. if (view.docView.compositionDeco.size)
  7608. view.update([]);
  7609. }
  7610. handlers.compositionstart = handlers.compositionupdate = view => {
  7611. if (view.inputState.composing < 0) {
  7612. if (view.docView.compositionDeco.size) {
  7613. view.observer.flush();
  7614. forceClearComposition(view);
  7615. }
  7616. // FIXME possibly set a timeout to clear it again on Android
  7617. view.inputState.composing = 0;
  7618. }
  7619. };
  7620. handlers.compositionend = view => {
  7621. view.inputState.composing = -1;
  7622. view.inputState.compositionEndedAt = Date.now();
  7623. setTimeout(() => {
  7624. if (view.inputState.composing < 0)
  7625. forceClearComposition(view);
  7626. }, 50);
  7627. };
  7628. const observeOptions = {
  7629. childList: true,
  7630. characterData: true,
  7631. subtree: true,
  7632. characterDataOldValue: true
  7633. };
  7634. // IE11 has very broken mutation observers, so we also listen to
  7635. // DOMCharacterDataModified there
  7636. const useCharData = browser.ie && browser.ie_version <= 11;
  7637. class DOMObserver {
  7638. constructor(view, onChange, onScrollChanged) {
  7639. this.view = view;
  7640. this.onChange = onChange;
  7641. this.onScrollChanged = onScrollChanged;
  7642. this.active = false;
  7643. this.ignoreSelection = new DOMSelection;
  7644. this.delayedFlush = -1;
  7645. this.queue = [];
  7646. this.scrollTargets = [];
  7647. this.intersection = null;
  7648. this.intersecting = false;
  7649. // Timeout for scheduling check of the parents that need scroll handlers
  7650. this.parentCheck = -1;
  7651. this.dom = view.contentDOM;
  7652. this.observer = new MutationObserver(mutations => {
  7653. for (let mut of mutations)
  7654. this.queue.push(mut);
  7655. // IE11 will sometimes (on typing over a selection or
  7656. // backspacing out a single character text node) call the
  7657. // observer callback before actually updating the DOM
  7658. if (browser.ie && browser.ie_version <= 11 &&
  7659. mutations.some(m => m.type == "childList" && m.removedNodes.length ||
  7660. m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length))
  7661. this.flushSoon();
  7662. else
  7663. this.flush();
  7664. });
  7665. if (useCharData)
  7666. this.onCharData = (event) => {
  7667. this.queue.push({ target: event.target,
  7668. type: "characterData",
  7669. oldValue: event.prevValue });
  7670. this.flushSoon();
  7671. };
  7672. this.onSelectionChange = (event) => {
  7673. if (this.view.root.activeElement != this.dom)
  7674. return;
  7675. let sel = getSelection(this.view.root);
  7676. let context = sel.anchorNode && this.view.docView.nearest(sel.anchorNode);
  7677. if (context && context.ignoreEvent(event))
  7678. return;
  7679. // Deletions on IE11 fire their events in the wrong order, giving
  7680. // us a selection change event before the DOM changes are
  7681. // reported.
  7682. // (Selection.isCollapsed isn't reliable on IE)
  7683. if (browser.ie && browser.ie_version <= 11 && !this.view.state.selection.main.empty &&
  7684. sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
  7685. this.flushSoon();
  7686. else
  7687. this.flush();
  7688. };
  7689. this.start();
  7690. this.onScroll = this.onScroll.bind(this);
  7691. window.addEventListener("scroll", this.onScroll);
  7692. if (typeof IntersectionObserver == "function") {
  7693. this.intersection = new IntersectionObserver(entries => {
  7694. if (this.parentCheck < 0)
  7695. this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1000);
  7696. if (entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
  7697. this.intersecting = !this.intersecting;
  7698. this.onScrollChanged(document.createEvent("Event"));
  7699. }
  7700. }, {});
  7701. this.intersection.observe(this.dom);
  7702. }
  7703. this.listenForScroll();
  7704. }
  7705. onScroll(e) {
  7706. if (this.intersecting) {
  7707. this.flush();
  7708. this.onScrollChanged(e);
  7709. }
  7710. }
  7711. listenForScroll() {
  7712. this.parentCheck = -1;
  7713. let i = 0, changed = null;
  7714. for (let dom = this.dom; dom;) {
  7715. if (dom.nodeType == 1) {
  7716. if (!changed && i < this.scrollTargets.length && this.scrollTargets[i] == dom)
  7717. i++;
  7718. else if (!changed)
  7719. changed = this.scrollTargets.slice(0, i);
  7720. if (changed)
  7721. changed.push(dom);
  7722. dom = dom.parentNode;
  7723. }
  7724. else if (dom.nodeType == 11) { // Shadow root
  7725. dom = dom.host;
  7726. }
  7727. else {
  7728. break;
  7729. }
  7730. }
  7731. if (i < this.scrollTargets.length && !changed)
  7732. changed = this.scrollTargets.slice(0, i);
  7733. if (changed) {
  7734. for (let dom of this.scrollTargets)
  7735. dom.removeEventListener("scroll", this.onScroll);
  7736. for (let dom of this.scrollTargets = changed)
  7737. dom.addEventListener("scroll", this.onScroll);
  7738. }
  7739. }
  7740. ignore(f) {
  7741. if (!this.active)
  7742. return f();
  7743. try {
  7744. this.stop();
  7745. return f();
  7746. }
  7747. finally {
  7748. this.start();
  7749. this.clear();
  7750. }
  7751. }
  7752. start() {
  7753. if (this.active)
  7754. return;
  7755. this.observer.observe(this.dom, observeOptions);
  7756. this.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  7757. if (useCharData)
  7758. this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
  7759. this.active = true;
  7760. }
  7761. stop() {
  7762. if (!this.active)
  7763. return;
  7764. this.active = false;
  7765. this.observer.disconnect();
  7766. this.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  7767. if (useCharData)
  7768. this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
  7769. }
  7770. clearSelection() {
  7771. this.ignoreSelection.set(getSelection(this.view.root));
  7772. }
  7773. // Throw away any pending changes
  7774. clear() {
  7775. this.observer.takeRecords();
  7776. this.queue.length = 0;
  7777. this.clearSelection();
  7778. }
  7779. flushSoon() {
  7780. if (this.delayedFlush < 0)
  7781. this.delayedFlush = window.setTimeout(() => { this.delayedFlush = -1; this.flush(); }, 20);
  7782. }
  7783. forceFlush() {
  7784. if (this.delayedFlush >= 0) {
  7785. window.clearTimeout(this.delayedFlush);
  7786. this.delayedFlush = -1;
  7787. this.flush();
  7788. }
  7789. }
  7790. // Apply pending changes, if any
  7791. flush() {
  7792. if (this.delayedFlush >= 0)
  7793. return;
  7794. let records = this.queue;
  7795. for (let mut of this.observer.takeRecords())
  7796. records.push(mut);
  7797. if (records.length)
  7798. this.queue = [];
  7799. let selection = getSelection(this.view.root);
  7800. let newSel = !this.ignoreSelection.eq(selection) && hasSelection(this.dom, selection);
  7801. if (records.length == 0 && !newSel)
  7802. return;
  7803. let from = -1, to = -1, typeOver = false;
  7804. for (let record of records) {
  7805. let range = this.readMutation(record);
  7806. if (!range)
  7807. continue;
  7808. if (range.typeOver)
  7809. typeOver = true;
  7810. if (from == -1) {
  7811. ({ from, to } = range);
  7812. }
  7813. else {
  7814. from = Math.min(range.from, from);
  7815. to = Math.max(range.to, to);
  7816. }
  7817. }
  7818. let startState = this.view.state;
  7819. if (from > -1 || newSel)
  7820. this.onChange(from, to, typeOver);
  7821. if (this.view.state == startState) { // The view wasn't updated
  7822. if (this.view.docView.dirty) {
  7823. this.ignore(() => this.view.docView.sync());
  7824. this.view.docView.dirty = 0 /* Not */;
  7825. }
  7826. this.view.docView.updateSelection();
  7827. }
  7828. this.clearSelection();
  7829. }
  7830. readMutation(rec) {
  7831. let cView = this.view.docView.nearest(rec.target);
  7832. if (!cView || cView.ignoreMutation(rec))
  7833. return null;
  7834. cView.markDirty();
  7835. if (rec.type == "childList") {
  7836. let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
  7837. let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
  7838. return { from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
  7839. to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd, typeOver: false };
  7840. }
  7841. else { // "characterData"
  7842. return { from: cView.posAtStart, to: cView.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue };
  7843. }
  7844. }
  7845. destroy() {
  7846. this.stop();
  7847. if (this.intersection)
  7848. this.intersection.disconnect();
  7849. for (let dom of this.scrollTargets)
  7850. dom.removeEventListener("scroll", this.onScroll);
  7851. window.removeEventListener("scroll", this.onScroll);
  7852. clearTimeout(this.parentCheck);
  7853. }
  7854. }
  7855. function findChild(cView, dom, dir) {
  7856. while (dom) {
  7857. let curView = ContentView.get(dom);
  7858. if (curView && curView.parent == cView)
  7859. return curView;
  7860. let parent = dom.parentNode;
  7861. dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
  7862. }
  7863. return null;
  7864. }
  7865. function applyDOMChange(view, start, end, typeOver) {
  7866. let change, newSel;
  7867. let sel = view.state.selection.main, bounds;
  7868. if (start > -1 && (bounds = view.docView.domBoundsAround(start, end, 0))) {
  7869. let { from, to } = bounds;
  7870. let selPoints = view.docView.impreciseHead || view.docView.impreciseAnchor ? [] : selectionPoints(view.contentDOM, view.root);
  7871. let reader = new DOMReader(selPoints, view);
  7872. reader.readRange(bounds.startDOM, bounds.endDOM);
  7873. newSel = selectionFromPoints(selPoints, from);
  7874. let preferredPos = sel.from, preferredSide = null;
  7875. // Prefer anchoring to end when Backspace is pressed (or, on
  7876. // Android, when something was deleted)
  7877. if (view.inputState.lastKeyCode === 8 && view.inputState.lastKeyTime > Date.now() - 100 ||
  7878. browser.android && reader.text.length < to - from) {
  7879. preferredPos = sel.to;
  7880. preferredSide = "end";
  7881. }
  7882. let diff = findDiff(view.state.sliceDoc(from, to), reader.text, preferredPos - from, preferredSide);
  7883. if (diff)
  7884. change = { from: from + diff.from, to: from + diff.toA,
  7885. insert: view.state.toText(reader.text.slice(diff.from, diff.toB)) };
  7886. }
  7887. else if (view.hasFocus) {
  7888. let domSel = getSelection(view.root);
  7889. let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView;
  7890. let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset ? view.state.selection.main.head
  7891. : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
  7892. let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset
  7893. ? view.state.selection.main.anchor
  7894. : selectionCollapsed(domSel) ? head : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
  7895. if (head != sel.head || anchor != sel.anchor)
  7896. newSel = EditorSelection.single(anchor, head);
  7897. }
  7898. if (!change && !newSel)
  7899. return;
  7900. // Heuristic to notice typing over a selected character
  7901. if (!change && typeOver && !sel.empty && newSel && newSel.main.empty)
  7902. change = { from: sel.from, to: sel.to, insert: view.state.doc.slice(sel.from, sel.to) };
  7903. if (change) {
  7904. let startState = view.state;
  7905. // Android browsers don't fire reasonable key events for enter,
  7906. // backspace, or delete. So this detects changes that look like
  7907. // they're caused by those keys, and reinterprets them as key
  7908. // events.
  7909. if (browser.android &&
  7910. ((change.from == sel.from && change.to == sel.to &&
  7911. change.insert.length == 1 && change.insert.lines == 2 &&
  7912. dispatchKey(view, "Enter", 10)) ||
  7913. (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 &&
  7914. dispatchKey(view, "Backspace", 8)) ||
  7915. (change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 &&
  7916. dispatchKey(view, "Delete", 46))))
  7917. return;
  7918. let text = change.insert.toString();
  7919. if (view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text)))
  7920. return;
  7921. if (view.inputState.composing >= 0)
  7922. view.inputState.composing++;
  7923. let tr;
  7924. if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3) {
  7925. let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
  7926. let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
  7927. tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, undefined, view.state.lineBreak) +
  7928. after));
  7929. }
  7930. else {
  7931. let changes = startState.changes(change);
  7932. tr = {
  7933. changes,
  7934. selection: newSel && !startState.selection.main.eq(newSel.main) && newSel.main.to <= changes.newLength
  7935. ? startState.selection.replaceRange(newSel.main) : undefined
  7936. };
  7937. }
  7938. view.dispatch(tr, { scrollIntoView: true, annotations: Transaction.userEvent.of("input") });
  7939. }
  7940. else if (newSel && !newSel.main.eq(sel)) {
  7941. let scrollIntoView = false, annotations;
  7942. if (view.inputState.lastSelectionTime > Date.now() - 50) {
  7943. if (view.inputState.lastSelectionOrigin == "keyboardselection")
  7944. scrollIntoView = true;
  7945. else
  7946. annotations = Transaction.userEvent.of(view.inputState.lastSelectionOrigin);
  7947. }
  7948. view.dispatch({ selection: newSel, scrollIntoView, annotations });
  7949. }
  7950. }
  7951. function findDiff(a, b, preferredPos, preferredSide) {
  7952. let minLen = Math.min(a.length, b.length);
  7953. let from = 0;
  7954. while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from))
  7955. from++;
  7956. if (from == minLen && a.length == b.length)
  7957. return null;
  7958. let toA = a.length, toB = b.length;
  7959. while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
  7960. toA--;
  7961. toB--;
  7962. }
  7963. if (preferredSide == "end") {
  7964. let adjust = Math.max(0, from - Math.min(toA, toB));
  7965. preferredPos -= toA + adjust - from;
  7966. }
  7967. if (toA < from && a.length < b.length) {
  7968. let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
  7969. from -= move;
  7970. toB = from + (toB - toA);
  7971. toA = from;
  7972. }
  7973. else if (toB < from) {
  7974. let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
  7975. from -= move;
  7976. toA = from + (toA - toB);
  7977. toB = from;
  7978. }
  7979. return { from, toA, toB };
  7980. }
  7981. class DOMReader {
  7982. constructor(points, view) {
  7983. this.points = points;
  7984. this.view = view;
  7985. this.text = "";
  7986. this.lineBreak = view.state.lineBreak;
  7987. }
  7988. readRange(start, end) {
  7989. if (!start)
  7990. return;
  7991. let parent = start.parentNode;
  7992. for (let cur = start;;) {
  7993. this.findPointBefore(parent, cur);
  7994. this.readNode(cur);
  7995. let next = cur.nextSibling;
  7996. if (next == end)
  7997. break;
  7998. let view = ContentView.get(cur), nextView = ContentView.get(next);
  7999. if ((view ? view.breakAfter : isBlockElement(cur)) ||
  8000. ((nextView ? nextView.breakAfter : isBlockElement(next)) && !(cur.nodeName == "BR" && !cur.cmIgnore)))
  8001. this.text += this.lineBreak;
  8002. cur = next;
  8003. }
  8004. this.findPointBefore(parent, end);
  8005. }
  8006. readNode(node) {
  8007. if (node.cmIgnore)
  8008. return;
  8009. let view = ContentView.get(node);
  8010. let fromView = view && view.overrideDOMText;
  8011. let text;
  8012. if (fromView != null)
  8013. text = fromView.sliceString(0, undefined, this.lineBreak);
  8014. else if (node.nodeType == 3)
  8015. text = node.nodeValue;
  8016. else if (node.nodeName == "BR")
  8017. text = node.nextSibling ? this.lineBreak : "";
  8018. else if (node.nodeType == 1)
  8019. this.readRange(node.firstChild, null);
  8020. if (text != null) {
  8021. this.findPointIn(node, text.length);
  8022. this.text += text;
  8023. // Chrome inserts two newlines when pressing shift-enter at the
  8024. // end of a line. This drops one of those.
  8025. if (browser.chrome && this.view.inputState.lastKeyCode == 13 && !node.nextSibling && /\n\n$/.test(this.text))
  8026. this.text = this.text.slice(0, -1);
  8027. }
  8028. }
  8029. findPointBefore(node, next) {
  8030. for (let point of this.points)
  8031. if (point.node == node && node.childNodes[point.offset] == next)
  8032. point.pos = this.text.length;
  8033. }
  8034. findPointIn(node, maxLen) {
  8035. for (let point of this.points)
  8036. if (point.node == node)
  8037. point.pos = this.text.length + Math.min(point.offset, maxLen);
  8038. }
  8039. }
  8040. function isBlockElement(node) {
  8041. return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
  8042. }
  8043. class DOMPoint {
  8044. constructor(node, offset) {
  8045. this.node = node;
  8046. this.offset = offset;
  8047. this.pos = -1;
  8048. }
  8049. }
  8050. function selectionPoints(dom, root) {
  8051. let result = [];
  8052. if (root.activeElement != dom)
  8053. return result;
  8054. let { anchorNode, anchorOffset, focusNode, focusOffset } = getSelection(root);
  8055. if (anchorNode) {
  8056. result.push(new DOMPoint(anchorNode, anchorOffset));
  8057. if (focusNode != anchorNode || focusOffset != anchorOffset)
  8058. result.push(new DOMPoint(focusNode, focusOffset));
  8059. }
  8060. return result;
  8061. }
  8062. function selectionFromPoints(points, base) {
  8063. if (points.length == 0)
  8064. return null;
  8065. let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor;
  8066. return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base, head + base) : null;
  8067. }
  8068. function dispatchKey(view, name, code) {
  8069. let options = { key: name, code: name, keyCode: code, which: code, cancelable: true };
  8070. let down = new KeyboardEvent("keydown", options);
  8071. view.contentDOM.dispatchEvent(down);
  8072. let up = new KeyboardEvent("keyup", options);
  8073. view.contentDOM.dispatchEvent(up);
  8074. return down.defaultPrevented || up.defaultPrevented;
  8075. }
  8076. // The editor's update state machine looks something like this:
  8077. //
  8078. // Idle → Updating ⇆ Idle (unchecked) → Measuring → Idle
  8079. // ↑ ↓
  8080. // Updating (measure)
  8081. //
  8082. // The difference between 'Idle' and 'Idle (unchecked)' lies in
  8083. // whether a layout check has been scheduled. A regular update through
  8084. // the `update` method updates the DOM in a write-only fashion, and
  8085. // relies on a check (scheduled with `requestAnimationFrame`) to make
  8086. // sure everything is where it should be and the viewport covers the
  8087. // visible code. That check continues to measure and then optionally
  8088. // update until it reaches a coherent state.
  8089. /// An editor view represents the editor's user interface. It holds
  8090. /// the editable DOM surface, and possibly other elements such as the
  8091. /// line number gutter. It handles events and dispatches state
  8092. /// transactions for editing actions.
  8093. class EditorView {
  8094. /// Construct a new view. You'll usually want to put `view.dom` into
  8095. /// your document after creating a view, so that the user can see
  8096. /// it.
  8097. constructor(
  8098. /// Initialization options.
  8099. config = {}) {
  8100. this.plugins = [];
  8101. this.editorAttrs = {};
  8102. this.contentAttrs = {};
  8103. this.bidiCache = [];
  8104. /// @internal
  8105. this.updateState = 2 /* Updating */;
  8106. /// @internal
  8107. this.measureScheduled = -1;
  8108. /// @internal
  8109. this.measureRequests = [];
  8110. this.contentDOM = document.createElement("div");
  8111. this.scrollDOM = document.createElement("div");
  8112. this.scrollDOM.className = themeClass("scroller");
  8113. this.scrollDOM.appendChild(this.contentDOM);
  8114. this.dom = document.createElement("div");
  8115. this.dom.appendChild(this.scrollDOM);
  8116. this._dispatch = config.dispatch || ((tr) => this.update([tr]));
  8117. this.dispatch = this.dispatch.bind(this);
  8118. this.root = (config.root || document);
  8119. this.viewState = new ViewState(config.state || EditorState.create());
  8120. this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec).update(this));
  8121. this.observer = new DOMObserver(this, (from, to, typeOver) => {
  8122. applyDOMChange(this, from, to, typeOver);
  8123. }, event => {
  8124. this.inputState.runScrollHandlers(this, event);
  8125. this.measure();
  8126. });
  8127. this.inputState = new InputState(this);
  8128. this.docView = new DocView(this);
  8129. this.mountStyles();
  8130. this.updateAttrs();
  8131. this.updateState = 0 /* Idle */;
  8132. ensureGlobalHandler();
  8133. this.requestMeasure();
  8134. if (config.parent)
  8135. config.parent.appendChild(this.dom);
  8136. }
  8137. /// The current editor state.
  8138. get state() { return this.viewState.state; }
  8139. /// To be able to display large documents without consuming too much
  8140. /// memory or overloading the browser, CodeMirror only draws the
  8141. /// code that is visible (plus a margin around it) to the DOM. This
  8142. /// property tells you the extent of the current drawn viewport, in
  8143. /// document positions.
  8144. get viewport() { return this.viewState.viewport; }
  8145. /// When there are, for example, large collapsed ranges in the
  8146. /// viewport, its size can be a lot bigger than the actual visible
  8147. /// content. Thus, if you are doing something like styling the
  8148. /// content in the viewport, it is preferable to only do so for
  8149. /// these ranges, which are the subset of the viewport that is
  8150. /// actually drawn.
  8151. get visibleRanges() { return this.viewState.visibleRanges; }
  8152. /// Returns false when the editor is entirely scrolled out of view
  8153. /// or otherwise hidden.
  8154. get inView() { return this.viewState.inView; }
  8155. /// Indicates whether the user is currently composing text via
  8156. /// [IME](https://developer.mozilla.org/en-US/docs/Mozilla/IME_handling_guide).
  8157. get composing() { return this.inputState.composing > 0; }
  8158. dispatch(...input) {
  8159. this._dispatch(input.length == 1 && input[0] instanceof Transaction ? input[0]
  8160. : this.state.update(...input));
  8161. }
  8162. /// Update the view for the given array of transactions. This will
  8163. /// update the visible document and selection to match the state
  8164. /// produced by the transactions, and notify view plugins of the
  8165. /// change. You should usually call
  8166. /// [`dispatch`](#view.EditorView.dispatch) instead, which uses this
  8167. /// as a primitive.
  8168. update(transactions) {
  8169. if (this.updateState != 0 /* Idle */)
  8170. throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
  8171. let redrawn = false, update;
  8172. this.updateState = 2 /* Updating */;
  8173. try {
  8174. let state = this.state;
  8175. for (let tr of transactions) {
  8176. if (tr.startState != state)
  8177. throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
  8178. state = tr.state;
  8179. }
  8180. update = new ViewUpdate(this, state, transactions);
  8181. let scrollTo = transactions.some(tr => tr.scrollIntoView) ? state.selection.main : null;
  8182. this.viewState.update(update, scrollTo);
  8183. this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
  8184. if (!update.empty)
  8185. this.updatePlugins(update);
  8186. redrawn = this.docView.update(update);
  8187. if (this.state.facet(styleModule) != this.styleModules)
  8188. this.mountStyles();
  8189. this.updateAttrs();
  8190. }
  8191. finally {
  8192. this.updateState = 0 /* Idle */;
  8193. }
  8194. if (redrawn || scrollTo || this.viewState.mustEnforceCursorAssoc)
  8195. this.requestMeasure();
  8196. if (!update.empty)
  8197. for (let listener of this.state.facet(updateListener))
  8198. listener(update);
  8199. }
  8200. /// Reset the view to the given state. (This will cause the entire
  8201. /// document to be redrawn and all view plugins to be reinitialized,
  8202. /// so you should probably only use it when the new state isn't
  8203. /// derived from the old state. Otherwise, use
  8204. /// [`dispatch`](#view.EditorView.dispatch) instead.)
  8205. setState(newState) {
  8206. if (this.updateState != 0 /* Idle */)
  8207. throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
  8208. this.updateState = 2 /* Updating */;
  8209. try {
  8210. for (let plugin of this.plugins)
  8211. plugin.destroy(this);
  8212. this.viewState = new ViewState(newState);
  8213. this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec).update(this));
  8214. this.docView = new DocView(this);
  8215. this.inputState.ensureHandlers(this);
  8216. this.mountStyles();
  8217. this.updateAttrs();
  8218. this.bidiCache = [];
  8219. }
  8220. finally {
  8221. this.updateState = 0 /* Idle */;
  8222. }
  8223. this.requestMeasure();
  8224. }
  8225. updatePlugins(update) {
  8226. let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin);
  8227. if (prevSpecs != specs) {
  8228. let newPlugins = [];
  8229. for (let spec of specs) {
  8230. let found = prevSpecs.indexOf(spec);
  8231. if (found < 0) {
  8232. newPlugins.push(new PluginInstance(spec));
  8233. }
  8234. else {
  8235. let plugin = this.plugins[found];
  8236. plugin.mustUpdate = update;
  8237. newPlugins.push(plugin);
  8238. }
  8239. }
  8240. for (let plugin of this.plugins)
  8241. if (plugin.mustUpdate != update)
  8242. plugin.destroy(this);
  8243. this.plugins = newPlugins;
  8244. this.inputState.ensureHandlers(this);
  8245. }
  8246. else {
  8247. for (let p of this.plugins)
  8248. p.mustUpdate = update;
  8249. }
  8250. for (let i = 0; i < this.plugins.length; i++)
  8251. this.plugins[i] = this.plugins[i].update(this);
  8252. }
  8253. /// @internal
  8254. measure() {
  8255. if (this.measureScheduled > -1)
  8256. cancelAnimationFrame(this.measureScheduled);
  8257. this.measureScheduled = -1; // Prevent requestMeasure calls from scheduling another animation frame
  8258. let updated = null;
  8259. try {
  8260. for (let i = 0;; i++) {
  8261. this.updateState = 1 /* Measuring */;
  8262. let changed = this.viewState.measure(this.docView, i > 0);
  8263. let measuring = this.measureRequests;
  8264. if (!changed && !measuring.length && this.viewState.scrollTo == null)
  8265. break;
  8266. this.measureRequests = [];
  8267. if (i > 5) {
  8268. console.warn("Viewport failed to stabilize");
  8269. break;
  8270. }
  8271. let measured = measuring.map(m => {
  8272. try {
  8273. return m.read(this);
  8274. }
  8275. catch (e) {
  8276. logException(this.state, e);
  8277. return BadMeasure;
  8278. }
  8279. });
  8280. let update = new ViewUpdate(this, this.state);
  8281. update.flags |= changed;
  8282. if (!updated)
  8283. updated = update;
  8284. else
  8285. updated.flags |= changed;
  8286. this.updateState = 2 /* Updating */;
  8287. if (!update.empty)
  8288. this.updatePlugins(update);
  8289. this.updateAttrs();
  8290. if (changed)
  8291. this.docView.update(update);
  8292. for (let i = 0; i < measuring.length; i++)
  8293. if (measured[i] != BadMeasure) {
  8294. try {
  8295. measuring[i].write(measured[i], this);
  8296. }
  8297. catch (e) {
  8298. logException(this.state, e);
  8299. }
  8300. }
  8301. if (this.viewState.scrollTo) {
  8302. this.docView.scrollPosIntoView(this.viewState.scrollTo.head, this.viewState.scrollTo.assoc);
  8303. this.viewState.scrollTo = null;
  8304. }
  8305. if (!(changed & 4 /* Viewport */) && this.measureRequests.length == 0)
  8306. break;
  8307. }
  8308. }
  8309. finally {
  8310. this.updateState = 0 /* Idle */;
  8311. }
  8312. this.measureScheduled = -1;
  8313. if (updated && !updated.empty)
  8314. for (let listener of this.state.facet(updateListener))
  8315. listener(updated);
  8316. }
  8317. /// Get the CSS classes for the currently active editor themes.
  8318. get themeClasses() {
  8319. return baseThemeID + " " +
  8320. (this.state.facet(darkTheme) ? "cm-dark" : "cm-light") + " " +
  8321. this.state.facet(theme);
  8322. }
  8323. updateAttrs() {
  8324. let editorAttrs = combineAttrs(this.state.facet(editorAttributes), {
  8325. class: themeClass("wrap") + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
  8326. });
  8327. updateAttrs(this.dom, this.editorAttrs, editorAttrs);
  8328. this.editorAttrs = editorAttrs;
  8329. let contentAttrs = combineAttrs(this.state.facet(contentAttributes), {
  8330. spellcheck: "false",
  8331. contenteditable: String(this.state.facet(editable)),
  8332. class: themeClass("content"),
  8333. style: `${browser.tabSize}: ${this.state.tabSize}`,
  8334. role: "textbox",
  8335. "aria-multiline": "true"
  8336. });
  8337. updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
  8338. this.contentAttrs = contentAttrs;
  8339. }
  8340. mountStyles() {
  8341. this.styleModules = this.state.facet(styleModule);
  8342. StyleModule.mount(this.root, this.styleModules.concat(baseTheme).reverse());
  8343. }
  8344. readMeasured() {
  8345. if (this.updateState == 2 /* Updating */)
  8346. throw new Error("Reading the editor layout isn't allowed during an update");
  8347. if (this.updateState == 0 /* Idle */ && this.measureScheduled > -1)
  8348. this.measure();
  8349. }
  8350. /// Make sure plugins get a chance to measure the DOM layout before
  8351. /// the next frame. Calling this is preferable reading DOM layout
  8352. /// directly from, for example, an event handler, because it'll make
  8353. /// sure measuring and drawing done by other components is
  8354. /// synchronized, avoiding unnecessary DOM layout computations.
  8355. requestMeasure(request) {
  8356. if (this.measureScheduled < 0)
  8357. this.measureScheduled = requestAnimationFrame(() => this.measure());
  8358. if (request) {
  8359. if (request.key != null)
  8360. for (let i = 0; i < this.measureRequests.length; i++) {
  8361. if (this.measureRequests[i].key === request.key) {
  8362. this.measureRequests[i] = request;
  8363. return;
  8364. }
  8365. }
  8366. this.measureRequests.push(request);
  8367. }
  8368. }
  8369. /// Collect all values provided by the active plugins for a given
  8370. /// field.
  8371. pluginField(field) {
  8372. let result = [];
  8373. for (let plugin of this.plugins)
  8374. plugin.update(this).takeField(field, result);
  8375. return result;
  8376. }
  8377. /// Get the value of a specific plugin, if present. Note that
  8378. /// plugins that crash can be dropped from a view, so even when you
  8379. /// know you registered a given plugin, it is recommended to check
  8380. /// the return value of this method.
  8381. plugin(plugin) {
  8382. for (let inst of this.plugins)
  8383. if (inst.spec == plugin)
  8384. return inst.update(this).value;
  8385. return null;
  8386. }
  8387. /// Find the line or block widget at the given vertical position.
  8388. /// `editorTop`, if given, provides the vertical position of the top
  8389. /// of the editor. It defaults to the editor's screen position
  8390. /// (which will force a DOM layout). You can explicitly pass 0 to
  8391. /// use editor-relative offsets.
  8392. blockAtHeight(height, editorTop) {
  8393. this.readMeasured();
  8394. return this.viewState.blockAtHeight(height, ensureTop(editorTop, this.contentDOM));
  8395. }
  8396. /// Find information for the visual line (see
  8397. /// [`visualLineAt`](#view.EditorView.visualLineAt)) at the given
  8398. /// vertical position. The resulting block info might hold another
  8399. /// array of block info structs in its `type` field if this line
  8400. /// consists of more than one block.
  8401. ///
  8402. /// Heights are interpreted relative to the given `editorTop`
  8403. /// position. When not given, the top position of the editor's
  8404. /// [content element](#view.EditorView.contentDOM) is taken.
  8405. visualLineAtHeight(height, editorTop) {
  8406. this.readMeasured();
  8407. return this.viewState.lineAtHeight(height, ensureTop(editorTop, this.contentDOM));
  8408. }
  8409. /// Iterate over the height information of the visual lines in the
  8410. /// viewport.
  8411. viewportLines(f, editorTop) {
  8412. let { from, to } = this.viewport;
  8413. this.viewState.forEachLine(from, to, f, ensureTop(editorTop, this.contentDOM));
  8414. }
  8415. /// Find the extent and height of the visual line (the content shown
  8416. /// in the editor as a line, which may be smaller than a document
  8417. /// line when broken up by block widgets, or bigger than a document
  8418. /// line when line breaks are covered by replaced decorations) at
  8419. /// the given position.
  8420. ///
  8421. /// Vertical positions are computed relative to the `editorTop`
  8422. /// argument, which defaults to 0 for this method. You can pass
  8423. /// `view.contentDOM.getBoundingClientRect().top` here to get screen
  8424. /// coordinates.
  8425. visualLineAt(pos, editorTop = 0) {
  8426. return this.viewState.lineAt(pos, editorTop);
  8427. }
  8428. /// The editor's total content height.
  8429. get contentHeight() {
  8430. return this.viewState.heightMap.height + this.viewState.paddingTop + this.viewState.paddingBottom;
  8431. }
  8432. /// Move a cursor position by [grapheme
  8433. /// cluster](#text.findClusterBreak). `forward` determines whether
  8434. /// the motion is away from the line start, or towards it. Motion in
  8435. /// bidirectional text is in visual order, in the editor's [text
  8436. /// direction](#view.EditorView.textDirection). When the start
  8437. /// position was the last one on the line, the returned position
  8438. /// will be across the line break. If there is no further line, the
  8439. /// original position is returned.
  8440. ///
  8441. /// By default, this method moves over a single cluster. The
  8442. /// optional `by` argument can be used to move across more. It will
  8443. /// be called with the first cluster as argument, and should return
  8444. /// a predicate that determines, for each subsequent cluster,
  8445. /// whether it should also be moved over.
  8446. moveByChar(start, forward, by) {
  8447. return moveByChar(this, start, forward, by);
  8448. }
  8449. /// Move a cursor position across the next group of either
  8450. /// [letters](#state.EditorState.charCategorizer) or non-letter
  8451. /// non-whitespace characters.
  8452. moveByGroup(start, forward) {
  8453. return moveByChar(this, start, forward, initial => byGroup(this, start.head, initial));
  8454. }
  8455. /// Move to the next line boundary in the given direction. If
  8456. /// `includeWrap` is true, line wrapping is on, and there is a
  8457. /// further wrap point on the current line, the wrap point will be
  8458. /// returned. Otherwise this function will return the start or end
  8459. /// of the line.
  8460. moveToLineBoundary(start, forward, includeWrap = true) {
  8461. return moveToLineBoundary(this, start, forward, includeWrap);
  8462. }
  8463. /// Move a cursor position vertically. When `distance` isn't given,
  8464. /// it defaults to moving to the next line (including wrapped
  8465. /// lines). Otherwise, `distance` should provide a positive distance
  8466. /// in pixels.
  8467. ///
  8468. /// When `start` has a
  8469. /// [`goalColumn`](#state.SelectionRange.goalColumn), the vertical
  8470. /// motion will use that as a target horizontal position. Otherwise,
  8471. /// the cursor's own horizontal position is used. The returned
  8472. /// cursor will have its goal column set to whichever column was
  8473. /// used.
  8474. moveVertically(start, forward, distance) {
  8475. return moveVertically(this, start, forward, distance);
  8476. }
  8477. /// Scroll the given document position into view.
  8478. scrollPosIntoView(pos) {
  8479. this.viewState.scrollTo = EditorSelection.cursor(pos);
  8480. this.requestMeasure();
  8481. }
  8482. /// Find the DOM parent node and offset (child offset if `node` is
  8483. /// an element, character offset when it is a text node) at the
  8484. /// given document position.
  8485. domAtPos(pos) {
  8486. return this.docView.domAtPos(pos);
  8487. }
  8488. /// Find the document position at the given DOM node. Can be useful
  8489. /// for associating positions with DOM events. Will raise an error
  8490. /// when `node` isn't part of the editor content.
  8491. posAtDOM(node, offset = 0) {
  8492. return this.docView.posFromDOM(node, offset);
  8493. }
  8494. /// Get the document position at the given screen coordinates.
  8495. /// Returns null if no valid position could be found.
  8496. posAtCoords(coords) {
  8497. this.readMeasured();
  8498. return posAtCoords(this, coords);
  8499. }
  8500. /// Get the screen coordinates at the given document position.
  8501. /// `side` determines whether the coordinates are based on the
  8502. /// element before (-1) or after (1) the position (if no element is
  8503. /// available on the given side, the method will transparently use
  8504. /// another strategy to get reasonable coordinates).
  8505. coordsAtPos(pos, side = 1) {
  8506. this.readMeasured();
  8507. let rect = this.docView.coordsAt(pos, side);
  8508. if (!rect || rect.left == rect.right)
  8509. return rect;
  8510. let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line);
  8511. let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
  8512. return flattenRect(rect, (span.dir == Direction.LTR) == (side > 0));
  8513. }
  8514. /// The default width of a character in the editor. May not
  8515. /// accurately reflect the width of all characters (given variable
  8516. /// width fonts or styling of invididual ranges).
  8517. get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth; }
  8518. /// The default height of a line in the editor. May not be accurate
  8519. /// for all lines.
  8520. get defaultLineHeight() { return this.viewState.heightOracle.lineHeight; }
  8521. /// The text direction
  8522. /// ([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
  8523. /// CSS property) of the editor.
  8524. get textDirection() { return this.viewState.heightOracle.direction; }
  8525. /// Whether this editor [wraps lines](#view.EditorView.lineWrapping)
  8526. /// (as determined by the
  8527. /// [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
  8528. /// CSS property of its content element).
  8529. get lineWrapping() { return this.viewState.heightOracle.lineWrapping; }
  8530. /// Returns the bidirectional text structure of the given line
  8531. /// (which should be in the current document) as an array of span
  8532. /// objects. The order of these spans matches the [text
  8533. /// direction](#view.EditorView.textDirection)—if that is
  8534. /// left-to-right, the leftmost spans come first, otherwise the
  8535. /// rightmost spans come first.
  8536. bidiSpans(line) {
  8537. if (line.length > MaxBidiLine)
  8538. return trivialOrder(line.length);
  8539. let dir = this.textDirection;
  8540. for (let entry of this.bidiCache)
  8541. if (entry.from == line.from && entry.dir == dir)
  8542. return entry.order;
  8543. let order = computeOrder(line.text, this.textDirection);
  8544. this.bidiCache.push(new CachedOrder(line.from, line.to, dir, order));
  8545. return order;
  8546. }
  8547. /// Check whether the editor has focus.
  8548. get hasFocus() {
  8549. return document.hasFocus() && this.root.activeElement == this.contentDOM;
  8550. }
  8551. /// Put focus on the editor.
  8552. focus() {
  8553. this.observer.ignore(() => {
  8554. focusPreventScroll(this.contentDOM);
  8555. this.docView.updateSelection();
  8556. });
  8557. }
  8558. /// Clean up this editor view, removing its element from the
  8559. /// document, unregistering event handlers, and notifying
  8560. /// plugins. The view instance can no longer be used after
  8561. /// calling this.
  8562. destroy() {
  8563. for (let plugin of this.plugins)
  8564. plugin.destroy(this);
  8565. this.inputState.destroy();
  8566. this.dom.remove();
  8567. this.observer.destroy();
  8568. if (this.measureScheduled > -1)
  8569. cancelAnimationFrame(this.measureScheduled);
  8570. }
  8571. /// Facet that can be used to add DOM event handlers. The value
  8572. /// should be an object mapping event names to handler functions. The
  8573. /// first such function to return true will be assumed to have handled
  8574. /// that event, and no other handlers or built-in behavior will be
  8575. /// activated for it.
  8576. /// These are registered on the [content
  8577. /// element](#view.EditorView.contentDOM), except for `scroll`
  8578. /// handlers, which will be called any time the editor's [scroll
  8579. /// element](#view.EditorView.scrollDOM) or one of its parent nodes
  8580. /// is scrolled.
  8581. static domEventHandlers(handlers) {
  8582. return ViewPlugin.define(() => ({}), { eventHandlers: handlers });
  8583. }
  8584. /// Create a theme extension. The first argument can be a
  8585. /// [`style-mod`](https://github.com/marijnh/style-mod#documentation)
  8586. /// style spec providing the styles for the theme. These will be
  8587. /// prefixed with a generated class for the style.
  8588. ///
  8589. /// It is highly recommended you use _theme classes_, rather than
  8590. /// regular CSS classes, in your selectors. These are prefixed with
  8591. /// a `$` instead of a `.`, and will be expanded (as with
  8592. /// [`themeClass`](#view.themeClass)) to one or more prefixed class
  8593. /// names. So for example `$content` targets the editor's [content
  8594. /// element](#view.EditorView.contentDOM).
  8595. ///
  8596. /// Because the selectors will be prefixed with a scope class,
  8597. /// directly matching the editor's [wrapper
  8598. /// element](#view.EditorView.dom), which is the element on which
  8599. /// the scope class will be added, needs to be explicitly
  8600. /// differentiated by adding an additional `$` to the front of the
  8601. /// pattern. For example `$$focused $panel` will expand to something
  8602. /// like `.[scope].cm-focused .cm-panel`.
  8603. ///
  8604. /// When `dark` is set to true, the theme will be marked as dark,
  8605. /// which will add the `$dark` selector to the wrapper element (as
  8606. /// opposed to `$light` when a light theme is active).
  8607. static theme(spec, options) {
  8608. let prefix = StyleModule.newName();
  8609. let result = [theme.of(prefix), styleModule.of(buildTheme(`.${baseThemeID}.${prefix}`, spec))];
  8610. if (options && options.dark)
  8611. result.push(darkTheme.of(true));
  8612. return result;
  8613. }
  8614. /// Create an extension that adds styles to the base theme. The
  8615. /// given object works much like the one passed to
  8616. /// [`theme`](#view.EditorView^theme). You'll often want to qualify
  8617. /// base styles with `$dark` or `$light` so they only apply when
  8618. /// there is a dark or light theme active. For example `"$$dark
  8619. /// $myHighlight"`.
  8620. static baseTheme(spec) {
  8621. return Prec.fallback(styleModule.of(buildTheme("." + baseThemeID, spec)));
  8622. }
  8623. }
  8624. /// Facet to add a [style
  8625. /// module](https://github.com/marijnh/style-mod#documentation) to
  8626. /// an editor view. The view will ensure that the module is
  8627. /// mounted in its [document
  8628. /// root](#view.EditorView.constructor^config.root).
  8629. EditorView.styleModule = styleModule;
  8630. /// An input handler can override the way changes to the editable
  8631. /// DOM content are handled. Handlers are passed the document
  8632. /// positions between which the change was found, and the new
  8633. /// content. When one returns true, no further input handlers are
  8634. /// called and the default behavior is prevented.
  8635. EditorView.inputHandler = inputHandler;
  8636. /// Allows you to provide a function that should be called when the
  8637. /// library catches an exception from an extension (mostly from view
  8638. /// plugins, but may be used by other extensions to route exceptions
  8639. /// from user-code-provided callbacks). This is mostly useful for
  8640. /// debugging and logging. See [`logException`](#view.logException).
  8641. EditorView.exceptionSink = exceptionSink;
  8642. /// A facet that can be used to register a function to be called
  8643. /// every time the view updates.
  8644. EditorView.updateListener = updateListener;
  8645. /// Facet that controls whether the editor content is editable. When
  8646. /// its highest-precedence value is `false`, editing is disabled,
  8647. /// and the content element will no longer have its
  8648. /// `contenteditable` attribute set to `true`. (Note that this
  8649. /// doesn't affect API calls that change the editor content, even
  8650. /// when those are bound to keys or buttons.)
  8651. EditorView.editable = editable;
  8652. /// Allows you to influence the way mouse selection happens. The
  8653. /// functions in this facet will be called for a `mousedown` event
  8654. /// on the editor, and can return an object that overrides the way a
  8655. /// selection is computed from that mouse click or drag.
  8656. EditorView.mouseSelectionStyle = mouseSelectionStyle;
  8657. /// Facet used to configure whether a given selection drag event
  8658. /// should move or copy the selection. The given predicate will be
  8659. /// called with the `mousedown` event, and can return `true` when
  8660. /// the drag should move the content.
  8661. EditorView.dragMovesSelection = dragMovesSelection;
  8662. /// Facet used to configure whether a given selecting click adds
  8663. /// a new range to the existing selection or replaces it entirely.
  8664. EditorView.clickAddsSelectionRange = clickAddsSelectionRange;
  8665. /// A facet that determines which [decorations](#view.Decoration)
  8666. /// are shown in the view. See also [view
  8667. /// plugins](#view.EditorView^decorations), which have a separate
  8668. /// mechanism for providing decorations.
  8669. EditorView.decorations = decorations;
  8670. /// An extension that enables line wrapping in the editor (by
  8671. /// setting CSS `white-space` to `pre-wrap` in the content).
  8672. EditorView.lineWrapping = EditorView.theme({ $content: { whiteSpace: "pre-wrap" } });
  8673. /// Facet that provides additional DOM attributes for the editor's
  8674. /// editable DOM element.
  8675. EditorView.contentAttributes = contentAttributes;
  8676. /// Facet that provides DOM attributes for the editor's outer
  8677. /// element.
  8678. EditorView.editorAttributes = editorAttributes;
  8679. // Maximum line length for which we compute accurate bidi info
  8680. const MaxBidiLine = 4096;
  8681. function ensureTop(given, dom) {
  8682. return given == null ? dom.getBoundingClientRect().top : given;
  8683. }
  8684. let resizeDebounce = -1;
  8685. function ensureGlobalHandler() {
  8686. window.addEventListener("resize", () => {
  8687. if (resizeDebounce == -1)
  8688. resizeDebounce = setTimeout(handleResize, 50);
  8689. });
  8690. }
  8691. function handleResize() {
  8692. resizeDebounce = -1;
  8693. let found = document.querySelectorAll(".cm-content");
  8694. for (let i = 0; i < found.length; i++) {
  8695. let docView = ContentView.get(found[i]);
  8696. if (docView)
  8697. docView.editorView.requestMeasure();
  8698. }
  8699. }
  8700. const BadMeasure = {};
  8701. class CachedOrder {
  8702. constructor(from, to, dir, order) {
  8703. this.from = from;
  8704. this.to = to;
  8705. this.dir = dir;
  8706. this.order = order;
  8707. }
  8708. static update(cache, changes) {
  8709. if (changes.empty)
  8710. return cache;
  8711. let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : Direction.LTR;
  8712. for (let i = Math.max(0, cache.length - 10); i < cache.length; i++) {
  8713. let entry = cache[i];
  8714. if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to))
  8715. result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.order));
  8716. }
  8717. return result;
  8718. }
  8719. }
  8720. const currentPlatform = typeof navigator == "undefined" ? "key"
  8721. : /Mac/.test(navigator.platform) ? "mac"
  8722. : /Win/.test(navigator.platform) ? "win"
  8723. : /Linux|X11/.test(navigator.platform) ? "linux"
  8724. : "key";
  8725. function normalizeKeyName(name, platform) {
  8726. const parts = name.split(/-(?!$)/);
  8727. let result = parts[parts.length - 1];
  8728. if (result == "Space")
  8729. result = " ";
  8730. let alt, ctrl, shift, meta;
  8731. for (let i = 0; i < parts.length - 1; ++i) {
  8732. const mod = parts[i];
  8733. if (/^(cmd|meta|m)$/i.test(mod))
  8734. meta = true;
  8735. else if (/^a(lt)?$/i.test(mod))
  8736. alt = true;
  8737. else if (/^(c|ctrl|control)$/i.test(mod))
  8738. ctrl = true;
  8739. else if (/^s(hift)?$/i.test(mod))
  8740. shift = true;
  8741. else if (/^mod$/i.test(mod)) {
  8742. if (platform == "mac")
  8743. meta = true;
  8744. else
  8745. ctrl = true;
  8746. }
  8747. else
  8748. throw new Error("Unrecognized modifier name: " + mod);
  8749. }
  8750. if (alt)
  8751. result = "Alt-" + result;
  8752. if (ctrl)
  8753. result = "Ctrl-" + result;
  8754. if (meta)
  8755. result = "Meta-" + result;
  8756. if (shift)
  8757. result = "Shift-" + result;
  8758. return result;
  8759. }
  8760. function modifiers(name, event, shift) {
  8761. if (event.altKey)
  8762. name = "Alt-" + name;
  8763. if (event.ctrlKey)
  8764. name = "Ctrl-" + name;
  8765. if (event.metaKey)
  8766. name = "Meta-" + name;
  8767. if (shift !== false && event.shiftKey)
  8768. name = "Shift-" + name;
  8769. return name;
  8770. }
  8771. const handleKeyEvents = EditorView.domEventHandlers({
  8772. keydown(event, view) {
  8773. return runHandlers(getKeymap(view.state), event, view, "editor");
  8774. }
  8775. });
  8776. /// Facet used for registering keymaps.
  8777. ///
  8778. /// You can add multiple keymaps to an editor. Their priorities
  8779. /// determine their precedence (the ones specified early or with high
  8780. /// priority get checked first). When a handler has returned `true`
  8781. /// for a given key, no further handlers are called.
  8782. const keymap = Facet.define({ enables: handleKeyEvents });
  8783. const Keymaps = new WeakMap();
  8784. // This is hidden behind an indirection, rather than directly computed
  8785. // by the facet, to keep internal types out of the facet's type.
  8786. function getKeymap(state) {
  8787. let bindings = state.facet(keymap);
  8788. let map = Keymaps.get(bindings);
  8789. if (!map)
  8790. Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
  8791. return map;
  8792. }
  8793. /// Run the key handlers registered for a given scope. The event
  8794. /// object should be `"keydown"` event. Returns true if any of the
  8795. /// handlers handled it.
  8796. function runScopeHandlers(view, event, scope) {
  8797. return runHandlers(getKeymap(view.state), event, view, scope);
  8798. }
  8799. let storedPrefix = null;
  8800. const PrefixTimeout = 4000;
  8801. function buildKeymap(bindings, platform = currentPlatform) {
  8802. let bound = Object.create(null);
  8803. let isPrefix = Object.create(null);
  8804. let checkPrefix = (name, is) => {
  8805. let current = isPrefix[name];
  8806. if (current == null)
  8807. isPrefix[name] = is;
  8808. else if (current != is)
  8809. throw new Error("Key binding " + name + " is used both as a regular binding and as a multi-stroke prefix");
  8810. };
  8811. let add = (scope, key, command, preventDefault) => {
  8812. let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
  8813. let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
  8814. for (let i = 1; i < parts.length; i++) {
  8815. let prefix = parts.slice(0, i).join(" ");
  8816. checkPrefix(prefix, true);
  8817. if (!scopeObj[prefix])
  8818. scopeObj[prefix] = {
  8819. preventDefault: true,
  8820. commands: [(view) => {
  8821. let ourObj = storedPrefix = { view, prefix, scope };
  8822. setTimeout(() => { if (storedPrefix == ourObj)
  8823. storedPrefix = null; }, PrefixTimeout);
  8824. return true;
  8825. }]
  8826. };
  8827. }
  8828. let full = parts.join(" ");
  8829. checkPrefix(full, false);
  8830. let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: false, commands: [] });
  8831. binding.commands.push(command);
  8832. if (preventDefault)
  8833. binding.preventDefault = true;
  8834. };
  8835. for (let b of bindings) {
  8836. let name = b[platform] || b.key;
  8837. if (!name)
  8838. continue;
  8839. for (let scope of b.scope ? b.scope.split(" ") : ["editor"]) {
  8840. add(scope, name, b.run, b.preventDefault);
  8841. if (b.shift)
  8842. add(scope, "Shift-" + name, b.shift, b.preventDefault);
  8843. }
  8844. }
  8845. return bound;
  8846. }
  8847. function runHandlers(map, event, view, scope) {
  8848. let name = keyName(event), isChar = name.length == 1 && name != " ";
  8849. let prefix = "", fallthrough = false;
  8850. if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
  8851. prefix = storedPrefix.prefix + " ";
  8852. if (fallthrough = modifierCodes.indexOf(event.keyCode) < 0)
  8853. storedPrefix = null;
  8854. }
  8855. let runFor = (binding) => {
  8856. if (binding) {
  8857. for (let cmd of binding.commands)
  8858. if (cmd(view))
  8859. return true;
  8860. if (binding.preventDefault)
  8861. fallthrough = true;
  8862. }
  8863. return false;
  8864. };
  8865. let scopeObj = map[scope], baseName;
  8866. if (scopeObj) {
  8867. if (runFor(scopeObj[prefix + modifiers(name, event, !isChar)]))
  8868. return true;
  8869. if (isChar && (event.shiftKey || event.altKey || event.metaKey) &&
  8870. (baseName = base[event.keyCode]) && baseName != name) {
  8871. if (runFor(scopeObj[prefix + modifiers(baseName, event, true)]))
  8872. return true;
  8873. }
  8874. else if (isChar && event.shiftKey) {
  8875. if (runFor(scopeObj[prefix + modifiers(name, event, true)]))
  8876. return true;
  8877. }
  8878. }
  8879. return fallthrough;
  8880. }
  8881. const CanHidePrimary = !browser.ios; // FIXME test IE
  8882. const selectionConfig = Facet.define({
  8883. combine(configs) {
  8884. return combineConfig(configs, {
  8885. cursorBlinkRate: 1200,
  8886. drawRangeCursor: true
  8887. }, {
  8888. cursorBlinkRate: (a, b) => Math.min(a, b),
  8889. drawRangeCursor: (a, b) => a || b
  8890. });
  8891. }
  8892. });
  8893. /// Returns an extension that hides the browser's native selection and
  8894. /// cursor, replacing the selection with a background behind the text
  8895. /// (labeled with the `$selectionBackground` theme class), and the
  8896. /// cursors with elements overlaid over the code (using
  8897. /// `$cursor.primary` and `$cursor.secondary`).
  8898. ///
  8899. /// This allows the editor to display secondary selection ranges, and
  8900. /// tends to produce a type of selection more in line with that users
  8901. /// expect in a text editor (the native selection styling will often
  8902. /// leave gaps between lines and won't fill the horizontal space after
  8903. /// a line when the selection continues past it).
  8904. ///
  8905. /// It does have a performance cost, in that it requires an extra DOM
  8906. /// layout cycle for many updates (the selection is drawn based on DOM
  8907. /// layout information that's only available after laying out the
  8908. /// content).
  8909. function drawSelection(config = {}) {
  8910. return [
  8911. selectionConfig.of(config),
  8912. drawSelectionPlugin,
  8913. hideNativeSelection
  8914. ];
  8915. }
  8916. class Piece {
  8917. constructor(left, top, width, height, className) {
  8918. this.left = left;
  8919. this.top = top;
  8920. this.width = width;
  8921. this.height = height;
  8922. this.className = className;
  8923. }
  8924. draw() {
  8925. let elt = document.createElement("div");
  8926. elt.className = this.className;
  8927. this.adjust(elt);
  8928. return elt;
  8929. }
  8930. adjust(elt) {
  8931. elt.style.left = this.left + "px";
  8932. elt.style.top = this.top + "px";
  8933. if (this.width >= 0)
  8934. elt.style.width = this.width + "px";
  8935. elt.style.height = this.height + "px";
  8936. }
  8937. eq(p) {
  8938. return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height &&
  8939. this.className == p.className;
  8940. }
  8941. }
  8942. const drawSelectionPlugin = ViewPlugin.fromClass(class {
  8943. constructor(view) {
  8944. this.view = view;
  8945. this.rangePieces = [];
  8946. this.cursors = [];
  8947. this.measureReq = { read: this.readPos.bind(this), write: this.drawSel.bind(this) };
  8948. this.selectionLayer = view.scrollDOM.appendChild(document.createElement("div"));
  8949. this.selectionLayer.className = themeClass("selectionLayer");
  8950. this.selectionLayer.setAttribute("aria-hidden", "true");
  8951. this.cursorLayer = view.scrollDOM.appendChild(document.createElement("div"));
  8952. this.cursorLayer.className = themeClass("cursorLayer");
  8953. this.cursorLayer.setAttribute("aria-hidden", "true");
  8954. view.requestMeasure(this.measureReq);
  8955. this.setBlinkRate();
  8956. }
  8957. setBlinkRate() {
  8958. this.cursorLayer.style.animationDuration = this.view.state.facet(selectionConfig).cursorBlinkRate + "ms";
  8959. }
  8960. update(update) {
  8961. let confChanged = update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
  8962. if (confChanged || update.selectionSet || update.geometryChanged || update.viewportChanged)
  8963. this.view.requestMeasure(this.measureReq);
  8964. if (update.transactions.some(tr => tr.scrollIntoView))
  8965. this.cursorLayer.style.animationName = this.cursorLayer.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
  8966. if (confChanged)
  8967. this.setBlinkRate();
  8968. }
  8969. readPos() {
  8970. let { state } = this.view, conf = state.facet(selectionConfig);
  8971. let rangePieces = state.selection.ranges.map(r => r.empty ? [] : measureRange(this.view, r)).reduce((a, b) => a.concat(b));
  8972. let cursors = [];
  8973. for (let r of state.selection.ranges) {
  8974. let prim = r == state.selection.main;
  8975. if (r.empty ? !prim || CanHidePrimary : conf.drawRangeCursor) {
  8976. let piece = measureCursor(this.view, r, prim);
  8977. if (piece)
  8978. cursors.push(piece);
  8979. }
  8980. }
  8981. return { rangePieces, cursors };
  8982. }
  8983. drawSel({ rangePieces, cursors }) {
  8984. if (rangePieces.length != this.rangePieces.length || rangePieces.some((p, i) => !p.eq(this.rangePieces[i]))) {
  8985. this.selectionLayer.textContent = "";
  8986. for (let p of rangePieces)
  8987. this.selectionLayer.appendChild(p.draw());
  8988. this.rangePieces = rangePieces;
  8989. }
  8990. if (cursors.length != this.cursors.length || cursors.some((c, i) => !c.eq(this.cursors[i]))) {
  8991. let oldCursors = this.cursorLayer.children;
  8992. if (oldCursors.length !== cursors.length) {
  8993. this.cursorLayer.textContent = "";
  8994. for (const c of cursors)
  8995. this.cursorLayer.appendChild(c.draw());
  8996. }
  8997. else {
  8998. cursors.forEach((c, idx) => c.adjust(oldCursors[idx]));
  8999. }
  9000. this.cursors = cursors;
  9001. }
  9002. }
  9003. destroy() {
  9004. this.selectionLayer.remove();
  9005. this.cursorLayer.remove();
  9006. }
  9007. });
  9008. const themeSpec = {
  9009. $line: {
  9010. "& ::selection": { backgroundColor: "transparent !important" },
  9011. "&::selection": { backgroundColor: "transparent !important" }
  9012. }
  9013. };
  9014. if (CanHidePrimary)
  9015. themeSpec.$line.caretColor = "transparent !important";
  9016. const hideNativeSelection = Prec.override(EditorView.theme(themeSpec));
  9017. const selectionClass = themeClass("selectionBackground");
  9018. function getBase(view) {
  9019. let rect = view.scrollDOM.getBoundingClientRect();
  9020. return { left: rect.left - view.scrollDOM.scrollLeft, top: rect.top - view.scrollDOM.scrollTop };
  9021. }
  9022. function wrappedLine(view, pos, inside) {
  9023. let range = EditorSelection.cursor(pos);
  9024. return { from: Math.max(inside.from, view.moveToLineBoundary(range, false, true).from),
  9025. to: Math.min(inside.to, view.moveToLineBoundary(range, true, true).from) };
  9026. }
  9027. function measureRange(view, range) {
  9028. if (range.to <= view.viewport.from || range.from >= view.viewport.to)
  9029. return [];
  9030. let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to);
  9031. let ltr = view.textDirection == Direction.LTR;
  9032. let content = view.contentDOM, contentRect = content.getBoundingClientRect(), base = getBase(view);
  9033. let lineStyle = window.getComputedStyle(content.firstChild);
  9034. let leftSide = contentRect.left + parseInt(lineStyle.paddingLeft);
  9035. let rightSide = contentRect.right - parseInt(lineStyle.paddingRight);
  9036. let visualStart = view.visualLineAt(from);
  9037. let visualEnd = view.visualLineAt(to);
  9038. if (view.lineWrapping) {
  9039. visualStart = wrappedLine(view, from, visualStart);
  9040. visualEnd = wrappedLine(view, to, visualEnd);
  9041. }
  9042. if (visualStart.from == visualEnd.from) {
  9043. return pieces(drawForLine(range.from, range.to));
  9044. }
  9045. else {
  9046. let top = drawForLine(range.from, null);
  9047. let bottom = drawForLine(null, range.to);
  9048. let between = [];
  9049. if (visualStart.to < visualEnd.from - 1)
  9050. between.push(piece(leftSide, top.bottom, rightSide, bottom.top));
  9051. else if (top.bottom < bottom.top && bottom.top - top.bottom < 4)
  9052. top.bottom = bottom.top = (top.bottom + bottom.top) / 2;
  9053. return pieces(top).concat(between).concat(pieces(bottom));
  9054. }
  9055. function piece(left, top, right, bottom) {
  9056. return new Piece(left - base.left, top - base.top, right - left, bottom - top, selectionClass);
  9057. }
  9058. function pieces({ top, bottom, horizontal }) {
  9059. let pieces = [];
  9060. for (let i = 0; i < horizontal.length; i += 2)
  9061. pieces.push(piece(horizontal[i], top, horizontal[i + 1], bottom));
  9062. return pieces;
  9063. }
  9064. // Gets passed from/to in line-local positions
  9065. function drawForLine(from, to) {
  9066. let top = 1e9, bottom = -1e9, horizontal = [];
  9067. function addSpan(from, fromOpen, to, toOpen, dir) {
  9068. let fromCoords = view.coordsAtPos(from, 1), toCoords = view.coordsAtPos(to, -1);
  9069. top = Math.min(fromCoords.top, toCoords.top, top);
  9070. bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
  9071. if (dir == Direction.LTR)
  9072. horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);
  9073. else
  9074. horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
  9075. }
  9076. let start = from !== null && from !== void 0 ? from : view.moveToLineBoundary(EditorSelection.cursor(to, 1), false).head;
  9077. let end = to !== null && to !== void 0 ? to : view.moveToLineBoundary(EditorSelection.cursor(from, -1), true).head;
  9078. // Split the range by visible range and document line
  9079. for (let r of view.visibleRanges)
  9080. if (r.to > start && r.from < end) {
  9081. for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
  9082. let docLine = view.state.doc.lineAt(pos);
  9083. for (let span of view.bidiSpans(docLine)) {
  9084. let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from;
  9085. if (spanFrom >= endPos)
  9086. break;
  9087. if (spanTo > pos)
  9088. addSpan(Math.max(spanFrom, pos), from == null && spanFrom <= start, Math.min(spanTo, endPos), to == null && spanTo >= end, span.dir);
  9089. }
  9090. pos = docLine.to + 1;
  9091. if (pos >= endPos)
  9092. break;
  9093. }
  9094. }
  9095. if (horizontal.length == 0) {
  9096. let coords = view.coordsAtPos(start, -1);
  9097. top = Math.min(coords.top, top);
  9098. bottom = Math.max(coords.bottom, bottom);
  9099. }
  9100. return { top, bottom, horizontal };
  9101. }
  9102. }
  9103. const primaryCursorClass = themeClass("cursor.primary");
  9104. const cursorClass = themeClass("cursor.secondary");
  9105. function measureCursor(view, cursor, primary) {
  9106. let pos = view.coordsAtPos(cursor.head, cursor.assoc || 1);
  9107. if (!pos)
  9108. return null;
  9109. let base = getBase(view);
  9110. return new Piece(pos.left - base.left, pos.top - base.top, -1, pos.bottom - pos.top, primary ? primaryCursorClass : cursorClass);
  9111. }
  9112. function iterMatches(doc, re, from, to, f) {
  9113. re.lastIndex = 0;
  9114. for (let cursor = doc.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) {
  9115. if (!cursor.lineBreak)
  9116. while (m = re.exec(cursor.value))
  9117. f(pos + m.index, pos + m.index + m[0].length, m);
  9118. }
  9119. }
  9120. /// Helper class used to make it easier to maintain decorations on
  9121. /// visible code that matches a given regular expression. To be used
  9122. /// in a [view plugin](#view.ViewPlugin). Instances of this object
  9123. /// represent a matching configuration.
  9124. class MatchDecorator {
  9125. /// Create a decorator.
  9126. constructor(config) {
  9127. let { regexp, decoration, boundary } = config;
  9128. if (!regexp.global)
  9129. throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
  9130. this.regexp = regexp;
  9131. this.getDeco = typeof decoration == "function" ? decoration : () => decoration;
  9132. this.boundary = boundary;
  9133. }
  9134. /// Compute the full set of decorations for matches in the given
  9135. /// view's viewport. You'll want to call this when initializing your
  9136. /// plugin.
  9137. createDeco(view) {
  9138. let build = new RangeSetBuilder();
  9139. for (let { from, to } of view.visibleRanges)
  9140. iterMatches(view.state.doc, this.regexp, from, to, (a, b, m) => build.add(a, b, this.getDeco(m, view, a)));
  9141. return build.finish();
  9142. }
  9143. /// Update a set of decorations for a view update. `deco` _must_ be
  9144. /// the set of decorations produced by _this_ `MatchDecorator` for
  9145. /// the view state before the update.
  9146. updateDeco(update, deco) {
  9147. let changeFrom = 1e9, changeTo = -1;
  9148. if (update.docChanged)
  9149. update.changes.iterChanges((_f, _t, from, to) => {
  9150. if (to > update.view.viewport.from && from < update.view.viewport.to) {
  9151. changeFrom = Math.min(from, changeFrom);
  9152. changeTo = Math.max(to, changeTo);
  9153. }
  9154. });
  9155. if (update.viewportChanged || changeTo - changeFrom > 1000)
  9156. return this.createDeco(update.view);
  9157. if (changeTo > -1)
  9158. return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
  9159. return deco;
  9160. }
  9161. updateRange(view, deco, updateFrom, updateTo) {
  9162. for (let r of view.visibleRanges) {
  9163. let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo);
  9164. if (to > from) {
  9165. let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
  9166. let start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to);
  9167. if (this.boundary) {
  9168. for (; from > fromLine.from; from--)
  9169. if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
  9170. start = from;
  9171. break;
  9172. }
  9173. for (; to < toLine.to; to++)
  9174. if (this.boundary.test(toLine.text[to - toLine.from])) {
  9175. end = to;
  9176. break;
  9177. }
  9178. }
  9179. let ranges = [], m;
  9180. if (fromLine == toLine) {
  9181. this.regexp.lastIndex = start - fromLine.from;
  9182. while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) {
  9183. let pos = m.index + fromLine.from;
  9184. ranges.push(this.getDeco(m, view, pos).range(pos, pos + m[0].length));
  9185. }
  9186. }
  9187. else {
  9188. iterMatches(view.state.doc, this.regexp, start, end, (from, to, m) => ranges.push(this.getDeco(m, view, from).range(from, to)));
  9189. }
  9190. deco = deco.update({ filterFrom: start, filterTo: end, filter: () => false, add: ranges });
  9191. }
  9192. }
  9193. return deco;
  9194. }
  9195. }
  9196. const UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
  9197. const Specials = new RegExp("[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]", UnicodeRegexpSupport);
  9198. const Names = {
  9199. 0: "null",
  9200. 7: "bell",
  9201. 8: "backspace",
  9202. 10: "newline",
  9203. 11: "vertical tab",
  9204. 13: "carriage return",
  9205. 27: "escape",
  9206. 8203: "zero width space",
  9207. 8204: "zero width non-joiner",
  9208. 8205: "zero width joiner",
  9209. 8206: "left-to-right mark",
  9210. 8207: "right-to-left mark",
  9211. 8232: "line separator",
  9212. 8233: "paragraph separator",
  9213. 65279: "zero width no-break space",
  9214. 65532: "object replacement"
  9215. };
  9216. let _supportsTabSize = null;
  9217. function supportsTabSize() {
  9218. if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
  9219. let styles = document.body.style;
  9220. _supportsTabSize = (styles.tabSize || styles.MozTabSize) != null;
  9221. }
  9222. return _supportsTabSize || false;
  9223. }
  9224. const specialCharConfig = Facet.define({
  9225. combine(configs) {
  9226. let config = combineConfig(configs, {
  9227. render: null,
  9228. specialChars: Specials,
  9229. addSpecialChars: null
  9230. });
  9231. if (config.replaceTabs = !supportsTabSize())
  9232. config.specialChars = new RegExp("\t|" + config.specialChars.source, UnicodeRegexpSupport);
  9233. if (config.addSpecialChars)
  9234. config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport);
  9235. return config;
  9236. }
  9237. });
  9238. /// Returns an extension that installs highlighting of special
  9239. /// characters.
  9240. function highlightSpecialChars(
  9241. /// Configuration options.
  9242. config = {}) {
  9243. return [specialCharConfig.of(config), specialCharPlugin()];
  9244. }
  9245. let _plugin = null;
  9246. function specialCharPlugin() {
  9247. return _plugin || (_plugin = ViewPlugin.fromClass(class {
  9248. constructor(view) {
  9249. this.view = view;
  9250. this.decorations = Decoration.none;
  9251. this.decorationCache = Object.create(null);
  9252. this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
  9253. this.decorations = this.decorator.createDeco(view);
  9254. }
  9255. makeDecorator(conf) {
  9256. return new MatchDecorator({
  9257. regexp: conf.specialChars,
  9258. decoration: (m, view, pos) => {
  9259. let { doc } = view.state;
  9260. let code = codePointAt(m[0], 0);
  9261. if (code == 9) {
  9262. let line = doc.lineAt(pos);
  9263. let size = view.state.tabSize, col = countColumn(doc.sliceString(line.from, pos), 0, size);
  9264. return Decoration.replace({ widget: new TabWidget((size - (col % size)) * this.view.defaultCharacterWidth) });
  9265. }
  9266. return this.decorationCache[code] ||
  9267. (this.decorationCache[code] = Decoration.replace({ widget: new SpecialCharWidget(conf, code) }));
  9268. },
  9269. boundary: conf.replaceTabs ? undefined : /[^]/
  9270. });
  9271. }
  9272. update(update) {
  9273. let conf = update.state.facet(specialCharConfig);
  9274. if (update.startState.facet(specialCharConfig) != conf) {
  9275. this.decorator = this.makeDecorator(conf);
  9276. this.decorations = this.decorator.createDeco(update.view);
  9277. }
  9278. else {
  9279. this.decorations = this.decorator.updateDeco(update, this.decorations);
  9280. }
  9281. }
  9282. }, {
  9283. decorations: v => v.decorations
  9284. }));
  9285. }
  9286. const DefaultPlaceholder = "\u2022";
  9287. // Assigns placeholder characters from the Control Pictures block to
  9288. // ASCII control characters
  9289. function placeholder(code) {
  9290. if (code >= 32)
  9291. return DefaultPlaceholder;
  9292. if (code == 10)
  9293. return "\u2424";
  9294. return String.fromCharCode(9216 + code);
  9295. }
  9296. class SpecialCharWidget extends WidgetType {
  9297. constructor(options, code) {
  9298. super();
  9299. this.options = options;
  9300. this.code = code;
  9301. }
  9302. eq(other) { return other.code == this.code; }
  9303. toDOM(view) {
  9304. let ph = placeholder(this.code);
  9305. let desc = view.state.phrase("Control character ") + (Names[this.code] || "0x" + this.code.toString(16));
  9306. let custom = this.options.render && this.options.render(this.code, desc, ph);
  9307. if (custom)
  9308. return custom;
  9309. let span = document.createElement("span");
  9310. span.textContent = ph;
  9311. span.title = desc;
  9312. span.setAttribute("aria-label", desc);
  9313. span.className = themeClass("specialChar");
  9314. return span;
  9315. }
  9316. ignoreEvent() { return false; }
  9317. }
  9318. class TabWidget extends WidgetType {
  9319. constructor(width) {
  9320. super();
  9321. this.width = width;
  9322. }
  9323. eq(other) { return other.width == this.width; }
  9324. toDOM() {
  9325. let span = document.createElement("span");
  9326. span.textContent = "\t";
  9327. span.className = themeClass("tab");
  9328. span.style.width = this.width + "px";
  9329. return span;
  9330. }
  9331. ignoreEvent() { return false; }
  9332. }
  9333. /// Mark lines that have a cursor on them with the `$activeLine`
  9334. /// theme class.
  9335. function highlightActiveLine() {
  9336. return activeLineHighlighter;
  9337. }
  9338. const lineDeco = Decoration.line({ attributes: { class: themeClass("activeLine") } });
  9339. const activeLineHighlighter = ViewPlugin.fromClass(class {
  9340. constructor(view) {
  9341. this.decorations = this.getDeco(view);
  9342. }
  9343. update(update) {
  9344. if (update.docChanged || update.selectionSet)
  9345. this.decorations = this.getDeco(update.view);
  9346. }
  9347. getDeco(view) {
  9348. let lastLineStart = -1, deco = [];
  9349. for (let r of view.state.selection.ranges) {
  9350. if (!r.empty)
  9351. continue;
  9352. let line = view.visualLineAt(r.head);
  9353. if (line.from > lastLineStart) {
  9354. deco.push(lineDeco.range(line.from));
  9355. lastLineStart = line.from;
  9356. }
  9357. }
  9358. return Decoration.set(deco);
  9359. }
  9360. }, {
  9361. decorations: v => v.decorations
  9362. });
  9363. const fromHistory = Annotation.define();
  9364. /// Transaction annotation that will prevent that transaction from
  9365. /// being combined with other transactions in the undo history. Given
  9366. /// `"before"`, it'll prevent merging with previous transactions. With
  9367. /// `"after"`, subsequent transactions won't be combined with this
  9368. /// one. With `"full"`, the transaction is isolated on both sides.
  9369. const isolateHistory = Annotation.define();
  9370. /// This facet provides a way to register functions that, given a
  9371. /// transaction, provide a set of effects that the history should
  9372. /// store when inverting the transaction. This can be used to
  9373. /// integrate some kinds of effects in the history, so that they can
  9374. /// be undone (and redone again).
  9375. const invertedEffects = Facet.define();
  9376. const historyConfig = Facet.define({
  9377. combine(configs) {
  9378. return combineConfig(configs, {
  9379. minDepth: 100,
  9380. newGroupDelay: 500
  9381. }, { minDepth: Math.max, newGroupDelay: Math.min });
  9382. }
  9383. });
  9384. const historyField = StateField.define({
  9385. create() {
  9386. return HistoryState.empty;
  9387. },
  9388. update(state, tr) {
  9389. let config = tr.state.facet(historyConfig);
  9390. let fromHist = tr.annotation(fromHistory);
  9391. if (fromHist) {
  9392. let item = HistEvent.fromTransaction(tr), from = fromHist.side;
  9393. let other = from == 0 /* Done */ ? state.undone : state.done;
  9394. if (item)
  9395. other = updateBranch(other, other.length, config.minDepth, item);
  9396. else
  9397. other = addSelection(other, tr.startState.selection);
  9398. return new HistoryState(from == 0 /* Done */ ? fromHist.rest : other, from == 0 /* Done */ ? other : fromHist.rest);
  9399. }
  9400. let isolate = tr.annotation(isolateHistory);
  9401. if (isolate == "full" || isolate == "before")
  9402. state = state.isolate();
  9403. if (tr.annotation(Transaction.addToHistory) === false)
  9404. return tr.changes.length ? state.addMapping(tr.changes.desc) : state;
  9405. let event = HistEvent.fromTransaction(tr);
  9406. let time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent);
  9407. if (event)
  9408. state = state.addChanges(event, time, userEvent, config.newGroupDelay, config.minDepth);
  9409. else if (tr.selection)
  9410. state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay);
  9411. if (isolate == "full" || isolate == "after")
  9412. state = state.isolate();
  9413. return state;
  9414. }
  9415. });
  9416. /// Create a history extension with the given configuration.
  9417. function history(config = {}) {
  9418. return [
  9419. historyField,
  9420. historyConfig.of(config),
  9421. EditorView.domEventHandlers({
  9422. beforeinput(e, view) {
  9423. if (e.inputType == "historyUndo")
  9424. return undo(view);
  9425. if (e.inputType == "historyRedo")
  9426. return redo(view);
  9427. return false;
  9428. }
  9429. })
  9430. ];
  9431. }
  9432. function cmd(side, selection) {
  9433. return function ({ state, dispatch }) {
  9434. let historyState = state.field(historyField, false);
  9435. if (!historyState)
  9436. return false;
  9437. let tr = historyState.pop(side, state, selection);
  9438. if (!tr)
  9439. return false;
  9440. dispatch(tr);
  9441. return true;
  9442. };
  9443. }
  9444. /// Undo a single group of history events. Returns false if no group
  9445. /// was available.
  9446. const undo = cmd(0 /* Done */, false);
  9447. /// Redo a group of history events. Returns false if no group was
  9448. /// available.
  9449. const redo = cmd(1 /* Undone */, false);
  9450. /// Undo a selection change.
  9451. const undoSelection = cmd(0 /* Done */, true);
  9452. /// Redo a selection change.
  9453. const redoSelection = cmd(1 /* Undone */, true);
  9454. // History events store groups of changes or effects that need to be
  9455. // undone/redone together.
  9456. class HistEvent {
  9457. constructor(
  9458. // The changes in this event. Normal events hold at least one
  9459. // change or effect. But it may be necessary to store selection
  9460. // events before the first change, in which case a special type of
  9461. // instance is created which doesn't hold any changes, with
  9462. // changes == startSelection == undefined
  9463. changes,
  9464. // The effects associated with this event
  9465. effects, mapped,
  9466. // The selection before this event
  9467. startSelection,
  9468. // Stores selection changes after this event, to be used for
  9469. // selection undo/redo.
  9470. selectionsAfter) {
  9471. this.changes = changes;
  9472. this.effects = effects;
  9473. this.mapped = mapped;
  9474. this.startSelection = startSelection;
  9475. this.selectionsAfter = selectionsAfter;
  9476. }
  9477. setSelAfter(after) {
  9478. return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
  9479. }
  9480. // This does not check `addToHistory` and such, it assumes the
  9481. // transaction needs to be converted to an item. Returns null when
  9482. // there are no changes or effects in the transaction.
  9483. static fromTransaction(tr) {
  9484. let effects = none$5;
  9485. for (let invert of tr.startState.facet(invertedEffects)) {
  9486. let result = invert(tr);
  9487. if (result.length)
  9488. effects = effects.concat(result);
  9489. }
  9490. if (!effects.length && tr.changes.empty)
  9491. return null;
  9492. return new HistEvent(tr.changes.invert(tr.startState.doc), effects, undefined, tr.startState.selection, none$5);
  9493. }
  9494. static selection(selections) {
  9495. return new HistEvent(undefined, none$5, undefined, undefined, selections);
  9496. }
  9497. }
  9498. function updateBranch(branch, to, maxLen, newEvent) {
  9499. let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
  9500. let newBranch = branch.slice(start, to);
  9501. newBranch.push(newEvent);
  9502. return newBranch;
  9503. }
  9504. function isAdjacent(a, b) {
  9505. let ranges = [], isAdjacent = false;
  9506. a.iterChangedRanges((f, t) => ranges.push(f, t));
  9507. b.iterChangedRanges((_f, _t, f, t) => {
  9508. for (let i = 0; i < ranges.length;) {
  9509. let from = ranges[i++], to = ranges[i++];
  9510. if (t >= from && f <= to)
  9511. isAdjacent = true;
  9512. }
  9513. });
  9514. return isAdjacent;
  9515. }
  9516. function eqSelectionShape(a, b) {
  9517. return a.ranges.length == b.ranges.length &&
  9518. a.ranges.filter((r, i) => r.empty != b.ranges[i].empty).length === 0;
  9519. }
  9520. function conc(a, b) {
  9521. return !a.length ? b : !b.length ? a : a.concat(b);
  9522. }
  9523. const none$5 = [];
  9524. const MaxSelectionsPerEvent = 200;
  9525. function addSelection(branch, selection) {
  9526. if (!branch.length) {
  9527. return [HistEvent.selection([selection])];
  9528. }
  9529. else {
  9530. let lastEvent = branch[branch.length - 1];
  9531. let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
  9532. if (sels.length && sels[sels.length - 1].eq(selection))
  9533. return branch;
  9534. sels.push(selection);
  9535. return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
  9536. }
  9537. }
  9538. // Assumes the top item has one or more selectionAfter values
  9539. function popSelection(branch) {
  9540. let last = branch[branch.length - 1];
  9541. let newBranch = branch.slice();
  9542. newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
  9543. return newBranch;
  9544. }
  9545. // Add a mapping to the top event in the given branch. If this maps
  9546. // away all the changes and effects in that item, drop it and
  9547. // propagate the mapping to the next item.
  9548. function addMappingToBranch(branch, mapping) {
  9549. if (!branch.length)
  9550. return branch;
  9551. let length = branch.length, selections = none$5;
  9552. while (length) {
  9553. let event = mapEvent(branch[length - 1], mapping, selections);
  9554. if (event.changes && !event.changes.empty || event.effects.length) { // Event survived mapping
  9555. let result = branch.slice(0, length);
  9556. result[length - 1] = event;
  9557. return result;
  9558. }
  9559. else { // Drop this event, since there's no changes or effects left
  9560. mapping = event.mapped;
  9561. length--;
  9562. selections = event.selectionsAfter;
  9563. }
  9564. }
  9565. return selections.length ? [HistEvent.selection(selections)] : none$5;
  9566. }
  9567. function mapEvent(event, mapping, extraSelections) {
  9568. let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$5, extraSelections);
  9569. // Change-less events don't store mappings (they are always the last event in a branch)
  9570. if (!event.changes)
  9571. return HistEvent.selection(selections);
  9572. let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, true);
  9573. let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
  9574. return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
  9575. }
  9576. class HistoryState {
  9577. constructor(done, undone, prevTime = 0, prevUserEvent = undefined) {
  9578. this.done = done;
  9579. this.undone = undone;
  9580. this.prevTime = prevTime;
  9581. this.prevUserEvent = prevUserEvent;
  9582. }
  9583. isolate() {
  9584. return this.prevTime ? new HistoryState(this.done, this.undone) : this;
  9585. }
  9586. addChanges(event, time, userEvent, newGroupDelay, maxLen) {
  9587. let done = this.done, lastEvent = done[done.length - 1];
  9588. if (lastEvent && lastEvent.changes &&
  9589. time - this.prevTime < newGroupDelay &&
  9590. !lastEvent.selectionsAfter.length &&
  9591. lastEvent.changes.length && event.changes &&
  9592. isAdjacent(lastEvent.changes, event.changes)) {
  9593. done = updateBranch(done, done.length - 1, maxLen, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$5));
  9594. }
  9595. else {
  9596. done = updateBranch(done, done.length, maxLen, event);
  9597. }
  9598. return new HistoryState(done, none$5, time, userEvent);
  9599. }
  9600. addSelection(selection, time, userEvent, newGroupDelay) {
  9601. let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$5;
  9602. if (last.length > 0 &&
  9603. time - this.prevTime < newGroupDelay &&
  9604. userEvent == "keyboardselection" && this.prevUserEvent == userEvent &&
  9605. eqSelectionShape(last[last.length - 1], selection))
  9606. return this;
  9607. return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
  9608. }
  9609. addMapping(mapping) {
  9610. return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
  9611. }
  9612. pop(side, state, selection) {
  9613. let branch = side == 0 /* Done */ ? this.done : this.undone;
  9614. if (branch.length == 0)
  9615. return null;
  9616. let event = branch[branch.length - 1];
  9617. if (selection && event.selectionsAfter.length) {
  9618. return state.update({
  9619. selection: event.selectionsAfter[event.selectionsAfter.length - 1],
  9620. annotations: fromHistory.of({ side, rest: popSelection(branch) })
  9621. });
  9622. }
  9623. else if (!event.changes) {
  9624. return null;
  9625. }
  9626. else {
  9627. let rest = branch.length == 1 ? none$5 : branch.slice(0, branch.length - 1);
  9628. if (event.mapped)
  9629. rest = addMappingToBranch(rest, event.mapped);
  9630. return state.update({
  9631. changes: event.changes,
  9632. selection: event.startSelection,
  9633. effects: event.effects,
  9634. annotations: fromHistory.of({ side, rest }),
  9635. filter: false
  9636. });
  9637. }
  9638. }
  9639. }
  9640. HistoryState.empty = new HistoryState(none$5, none$5);
  9641. /// Default key bindings for the undo history.
  9642. ///
  9643. /// - Mod-z: [`undo`](#history.undo).
  9644. /// - Mod-y (Mod-Shift-z on macOS): [`redo`](#history.redo).
  9645. /// - Mod-u: [`undoSelection`](#history.undoSelection).
  9646. /// - Alt-u (Mod-Shift-u on macOS): [`redoSelection`](#history.redoSelection).
  9647. const historyKeymap = [
  9648. { key: "Mod-z", run: undo, preventDefault: true },
  9649. { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: true },
  9650. { key: "Mod-u", run: undoSelection, preventDefault: true },
  9651. { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: true }
  9652. ];
  9653. /// The default maximum length of a `TreeBuffer` node.
  9654. const DefaultBufferLength = 1024;
  9655. let nextPropID = 0;
  9656. const CachedNode = new WeakMap();
  9657. /// Each [node type](#tree.NodeType) can have metadata associated with
  9658. /// it in props. Instances of this class represent prop names.
  9659. class NodeProp {
  9660. /// Create a new node prop type. You can optionally pass a
  9661. /// `deserialize` function.
  9662. constructor({ deserialize } = {}) {
  9663. this.id = nextPropID++;
  9664. this.deserialize = deserialize || (() => {
  9665. throw new Error("This node type doesn't define a deserialize function");
  9666. });
  9667. }
  9668. /// Create a string-valued node prop whose deserialize function is
  9669. /// the identity function.
  9670. static string() { return new NodeProp({ deserialize: str => str }); }
  9671. /// Create a number-valued node prop whose deserialize function is
  9672. /// just `Number`.
  9673. static number() { return new NodeProp({ deserialize: Number }); }
  9674. /// Creates a boolean-valued node prop whose deserialize function
  9675. /// returns true for any input.
  9676. static flag() { return new NodeProp({ deserialize: () => true }); }
  9677. /// Store a value for this prop in the given object. This can be
  9678. /// useful when building up a prop object to pass to the
  9679. /// [`NodeType`](#tree.NodeType) constructor. Returns its first
  9680. /// argument.
  9681. set(propObj, value) {
  9682. propObj[this.id] = value;
  9683. return propObj;
  9684. }
  9685. /// This is meant to be used with
  9686. /// [`NodeSet.extend`](#tree.NodeSet.extend) or
  9687. /// [`Parser.withProps`](#lezer.Parser.withProps) to compute prop
  9688. /// values for each node type in the set. Takes a [match
  9689. /// object](#tree.NodeType^match) or function that returns undefined
  9690. /// if the node type doesn't get this prop, and the prop's value if
  9691. /// it does.
  9692. add(match) {
  9693. if (typeof match != "function")
  9694. match = NodeType.match(match);
  9695. return (type) => {
  9696. let result = match(type);
  9697. return result === undefined ? null : [this, result];
  9698. };
  9699. }
  9700. }
  9701. /// Prop that is used to describe matching delimiters. For opening
  9702. /// delimiters, this holds an array of node names (written as a
  9703. /// space-separated string when declaring this prop in a grammar)
  9704. /// for the node types of closing delimiters that match it.
  9705. NodeProp.closedBy = new NodeProp({ deserialize: str => str.split(" ") });
  9706. /// The inverse of [`openedBy`](#tree.NodeProp^closedBy). This is
  9707. /// attached to closing delimiters, holding an array of node names
  9708. /// of types of matching opening delimiters.
  9709. NodeProp.openedBy = new NodeProp({ deserialize: str => str.split(" ") });
  9710. /// Used to assign node types to groups (for example, all node
  9711. /// types that represent an expression could be tagged with an
  9712. /// `"Expression"` group).
  9713. NodeProp.group = new NodeProp({ deserialize: str => str.split(" ") });
  9714. const noProps = Object.create(null);
  9715. /// Each node in a syntax tree has a node type associated with it.
  9716. class NodeType {
  9717. /// @internal
  9718. constructor(
  9719. /// The name of the node type. Not necessarily unique, but if the
  9720. /// grammar was written properly, different node types with the
  9721. /// same name within a node set should play the same semantic
  9722. /// role.
  9723. name,
  9724. /// @internal
  9725. props,
  9726. /// The id of this node in its set. Corresponds to the term ids
  9727. /// used in the parser.
  9728. id,
  9729. /// @internal
  9730. flags = 0) {
  9731. this.name = name;
  9732. this.props = props;
  9733. this.id = id;
  9734. this.flags = flags;
  9735. }
  9736. static define(spec) {
  9737. let props = spec.props && spec.props.length ? Object.create(null) : noProps;
  9738. let flags = (spec.top ? 1 /* Top */ : 0) | (spec.skipped ? 2 /* Skipped */ : 0) |
  9739. (spec.error ? 4 /* Error */ : 0) | (spec.name == null ? 8 /* Anonymous */ : 0);
  9740. let type = new NodeType(spec.name || "", props, spec.id, flags);
  9741. if (spec.props)
  9742. for (let src of spec.props) {
  9743. if (!Array.isArray(src))
  9744. src = src(type);
  9745. if (src)
  9746. src[0].set(props, src[1]);
  9747. }
  9748. return type;
  9749. }
  9750. /// Retrieves a node prop for this type. Will return `undefined` if
  9751. /// the prop isn't present on this node.
  9752. prop(prop) { return this.props[prop.id]; }
  9753. /// True when this is the top node of a grammar.
  9754. get isTop() { return (this.flags & 1 /* Top */) > 0; }
  9755. /// True when this node is produced by a skip rule.
  9756. get isSkipped() { return (this.flags & 2 /* Skipped */) > 0; }
  9757. /// Indicates whether this is an error node.
  9758. get isError() { return (this.flags & 4 /* Error */) > 0; }
  9759. /// When true, this node type doesn't correspond to a user-declared
  9760. /// named node, for example because it is used to cache repetition.
  9761. get isAnonymous() { return (this.flags & 8 /* Anonymous */) > 0; }
  9762. /// Returns true when this node's name or one of its
  9763. /// [groups](#tree.NodeProp^group) matches the given string.
  9764. is(name) {
  9765. if (typeof name == 'string') {
  9766. if (this.name == name)
  9767. return true;
  9768. let group = this.prop(NodeProp.group);
  9769. return group ? group.indexOf(name) > -1 : false;
  9770. }
  9771. return this.id == name;
  9772. }
  9773. /// Create a function from node types to arbitrary values by
  9774. /// specifying an object whose property names are node or
  9775. /// [group](#tree.NodeProp^group) names. Often useful with
  9776. /// [`NodeProp.add`](#tree.NodeProp.add). You can put multiple
  9777. /// names, separated by spaces, in a single property name to map
  9778. /// multiple node names to a single value.
  9779. static match(map) {
  9780. let direct = Object.create(null);
  9781. for (let prop in map)
  9782. for (let name of prop.split(" "))
  9783. direct[name] = map[prop];
  9784. return (node) => {
  9785. for (let groups = node.prop(NodeProp.group), i = -1; i < (groups ? groups.length : 0); i++) {
  9786. let found = direct[i < 0 ? node.name : groups[i]];
  9787. if (found)
  9788. return found;
  9789. }
  9790. };
  9791. }
  9792. }
  9793. /// An empty dummy node type to use when no actual type is available.
  9794. NodeType.none = new NodeType("", Object.create(null), 0, 8 /* Anonymous */);
  9795. /// A node set holds a collection of node types. It is used to
  9796. /// compactly represent trees by storing their type ids, rather than a
  9797. /// full pointer to the type object, in a number array. Each parser
  9798. /// [has](#lezer.Parser.nodeSet) a node set, and [tree
  9799. /// buffers](#tree.TreeBuffer) can only store collections of nodes
  9800. /// from the same set. A set can have a maximum of 2**16 (65536)
  9801. /// node types in it, so that the ids fit into 16-bit typed array
  9802. /// slots.
  9803. class NodeSet {
  9804. /// Create a set with the given types. The `id` property of each
  9805. /// type should correspond to its position within the array.
  9806. constructor(
  9807. /// The node types in this set, by id.
  9808. types) {
  9809. this.types = types;
  9810. for (let i = 0; i < types.length; i++)
  9811. if (types[i].id != i)
  9812. throw new RangeError("Node type ids should correspond to array positions when creating a node set");
  9813. }
  9814. /// Create a copy of this set with some node properties added. The
  9815. /// arguments to this method should be created with
  9816. /// [`NodeProp.add`](#tree.NodeProp.add).
  9817. extend(...props) {
  9818. let newTypes = [];
  9819. for (let type of this.types) {
  9820. let newProps = null;
  9821. for (let source of props) {
  9822. let add = source(type);
  9823. if (add) {
  9824. if (!newProps)
  9825. newProps = Object.assign({}, type.props);
  9826. add[0].set(newProps, add[1]);
  9827. }
  9828. }
  9829. newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
  9830. }
  9831. return new NodeSet(newTypes);
  9832. }
  9833. }
  9834. /// A piece of syntax tree. There are two ways to approach these
  9835. /// trees: the way they are actually stored in memory, and the
  9836. /// convenient way.
  9837. ///
  9838. /// Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
  9839. /// objects. By packing detail information into `TreeBuffer` leaf
  9840. /// nodes, the representation is made a lot more memory-efficient.
  9841. ///
  9842. /// However, when you want to actually work with tree nodes, this
  9843. /// representation is very awkward, so most client code will want to
  9844. /// use the `TreeCursor` interface instead, which provides a view on
  9845. /// some part of this data structure, and can be used to move around
  9846. /// to adjacent nodes.
  9847. class Tree {
  9848. /// Construct a new tree. You usually want to go through
  9849. /// [`Tree.build`](#tree.Tree^build) instead.
  9850. constructor(type,
  9851. /// The tree's child nodes. Children small enough to fit in a
  9852. /// `TreeBuffer will be represented as such, other children can be
  9853. /// further `Tree` instances with their own internal structure.
  9854. children,
  9855. /// The positions (offsets relative to the start of this tree) of
  9856. /// the children.
  9857. positions,
  9858. /// The total length of this tree
  9859. length) {
  9860. this.type = type;
  9861. this.children = children;
  9862. this.positions = positions;
  9863. this.length = length;
  9864. }
  9865. /// @internal
  9866. toString() {
  9867. let children = this.children.map(c => c.toString()).join();
  9868. return !this.type.name ? children :
  9869. (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) +
  9870. (children.length ? "(" + children + ")" : "");
  9871. }
  9872. /// Get a [tree cursor](#tree.TreeCursor) rooted at this tree. When
  9873. /// `pos` is given, the cursor is [moved](#tree.TreeCursor.moveTo)
  9874. /// to the given position and side.
  9875. cursor(pos, side = 0) {
  9876. let scope = (pos != null && CachedNode.get(this)) || this.topNode;
  9877. let cursor = new TreeCursor(scope);
  9878. if (pos != null) {
  9879. cursor.moveTo(pos, side);
  9880. CachedNode.set(this, cursor._tree);
  9881. }
  9882. return cursor;
  9883. }
  9884. /// Get a [tree cursor](#tree.TreeCursor) that, unlike regular
  9885. /// cursors, doesn't skip [anonymous](#tree.NodeType.isAnonymous)
  9886. /// nodes.
  9887. fullCursor() {
  9888. return new TreeCursor(this.topNode, true);
  9889. }
  9890. /// Get a [syntax node](#tree.SyntaxNode) object for the top of the
  9891. /// tree.
  9892. get topNode() {
  9893. return new TreeNode(this, 0, 0, null);
  9894. }
  9895. /// Get the [syntax node](#tree.SyntaxNode) at the given position.
  9896. /// If `side` is -1, this will move into nodes that end at the
  9897. /// position. If 1, it'll move into nodes that start at the
  9898. /// position. With 0, it'll only enter nodes that cover the position
  9899. /// from both sides.
  9900. resolve(pos, side = 0) {
  9901. return this.cursor(pos, side).node;
  9902. }
  9903. /// Iterate over the tree and its children, calling `enter` for any
  9904. /// node that touches the `from`/`to` region (if given) before
  9905. /// running over such a node's children, and `leave` (if given) when
  9906. /// leaving the node. When `enter` returns `false`, the given node
  9907. /// will not have its children iterated over (or `leave` called).
  9908. iterate(spec) {
  9909. let { enter, leave, from = 0, to = this.length } = spec;
  9910. for (let c = this.cursor();;) {
  9911. let mustLeave = false;
  9912. if (c.from <= to && c.to >= from && (c.type.isAnonymous || enter(c.type, c.from, c.to) !== false)) {
  9913. if (c.firstChild())
  9914. continue;
  9915. if (!c.type.isAnonymous)
  9916. mustLeave = true;
  9917. }
  9918. for (;;) {
  9919. if (mustLeave && leave)
  9920. leave(c.type, c.from, c.to);
  9921. mustLeave = c.type.isAnonymous;
  9922. if (c.nextSibling())
  9923. break;
  9924. if (!c.parent())
  9925. return;
  9926. mustLeave = true;
  9927. }
  9928. }
  9929. }
  9930. /// Balance the direct children of this tree.
  9931. balance(maxBufferLength = DefaultBufferLength) {
  9932. return this.children.length <= BalanceBranchFactor ? this
  9933. : balanceRange(this.type, NodeType.none, this.children, this.positions, 0, this.children.length, 0, maxBufferLength, this.length);
  9934. }
  9935. /// Build a tree from a postfix-ordered buffer of node information,
  9936. /// or a cursor over such a buffer.
  9937. static build(data) { return buildTree(data); }
  9938. }
  9939. /// The empty tree
  9940. Tree.empty = new Tree(NodeType.none, [], [], 0);
  9941. /// Tree buffers contain (type, start, end, endIndex) quads for each
  9942. /// node. In such a buffer, nodes are stored in prefix order (parents
  9943. /// before children, with the endIndex of the parent indicating which
  9944. /// children belong to it)
  9945. class TreeBuffer {
  9946. /// Create a tree buffer @internal
  9947. constructor(
  9948. /// @internal
  9949. buffer,
  9950. // The total length of the group of nodes in the buffer.
  9951. length,
  9952. /// @internal
  9953. set, type = NodeType.none) {
  9954. this.buffer = buffer;
  9955. this.length = length;
  9956. this.set = set;
  9957. this.type = type;
  9958. }
  9959. /// @internal
  9960. toString() {
  9961. let result = [];
  9962. for (let index = 0; index < this.buffer.length;) {
  9963. result.push(this.childString(index));
  9964. index = this.buffer[index + 3];
  9965. }
  9966. return result.join(",");
  9967. }
  9968. /// @internal
  9969. childString(index) {
  9970. let id = this.buffer[index], endIndex = this.buffer[index + 3];
  9971. let type = this.set.types[id], result = type.name;
  9972. if (/\W/.test(result) && !type.isError)
  9973. result = JSON.stringify(result);
  9974. index += 4;
  9975. if (endIndex == index)
  9976. return result;
  9977. let children = [];
  9978. while (index < endIndex) {
  9979. children.push(this.childString(index));
  9980. index = this.buffer[index + 3];
  9981. }
  9982. return result + "(" + children.join(",") + ")";
  9983. }
  9984. /// @internal
  9985. findChild(startIndex, endIndex, dir, after) {
  9986. let { buffer } = this, pick = -1;
  9987. for (let i = startIndex; i != endIndex; i = buffer[i + 3]) {
  9988. if (after != -100000000 /* None */) {
  9989. let start = buffer[i + 1], end = buffer[i + 2];
  9990. if (dir > 0) {
  9991. if (end > after)
  9992. pick = i;
  9993. if (end > after)
  9994. break;
  9995. }
  9996. else {
  9997. if (start < after)
  9998. pick = i;
  9999. if (end >= after)
  10000. break;
  10001. }
  10002. }
  10003. else {
  10004. pick = i;
  10005. if (dir > 0)
  10006. break;
  10007. }
  10008. }
  10009. return pick;
  10010. }
  10011. }
  10012. class TreeNode {
  10013. constructor(node, from, index, _parent) {
  10014. this.node = node;
  10015. this.from = from;
  10016. this.index = index;
  10017. this._parent = _parent;
  10018. }
  10019. get type() { return this.node.type; }
  10020. get name() { return this.node.type.name; }
  10021. get to() { return this.from + this.node.length; }
  10022. nextChild(i, dir, after, full = false) {
  10023. for (let parent = this;;) {
  10024. for (let { children, positions } = parent.node, e = dir > 0 ? children.length : -1; i != e; i += dir) {
  10025. let next = children[i], start = positions[i] + parent.from;
  10026. if (after != -100000000 /* None */ && (dir < 0 ? start >= after : start + next.length <= after))
  10027. continue;
  10028. if (next instanceof TreeBuffer) {
  10029. let index = next.findChild(0, next.buffer.length, dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - start);
  10030. if (index > -1)
  10031. return new BufferNode(new BufferContext(parent, next, i, start), null, index);
  10032. }
  10033. else if (full || (!next.type.isAnonymous || hasChild(next))) {
  10034. let inner = new TreeNode(next, start, i, parent);
  10035. return full || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, after);
  10036. }
  10037. }
  10038. if (full || !parent.type.isAnonymous)
  10039. return null;
  10040. i = parent.index + dir;
  10041. parent = parent._parent;
  10042. if (!parent)
  10043. return null;
  10044. }
  10045. }
  10046. get firstChild() { return this.nextChild(0, 1, -100000000 /* None */); }
  10047. get lastChild() { return this.nextChild(this.node.children.length - 1, -1, -100000000 /* None */); }
  10048. childAfter(pos) { return this.nextChild(0, 1, pos); }
  10049. childBefore(pos) { return this.nextChild(this.node.children.length - 1, -1, pos); }
  10050. nextSignificantParent() {
  10051. let val = this;
  10052. while (val.type.isAnonymous && val._parent)
  10053. val = val._parent;
  10054. return val;
  10055. }
  10056. get parent() {
  10057. return this._parent ? this._parent.nextSignificantParent() : null;
  10058. }
  10059. get nextSibling() {
  10060. return this._parent ? this._parent.nextChild(this.index + 1, 1, -1) : null;
  10061. }
  10062. get prevSibling() {
  10063. return this._parent ? this._parent.nextChild(this.index - 1, -1, -1) : null;
  10064. }
  10065. get cursor() { return new TreeCursor(this); }
  10066. resolve(pos, side = 0) {
  10067. return this.cursor.moveTo(pos, side).node;
  10068. }
  10069. getChild(type, before = null, after = null) {
  10070. let r = getChildren(this, type, before, after);
  10071. return r.length ? r[0] : null;
  10072. }
  10073. getChildren(type, before = null, after = null) {
  10074. return getChildren(this, type, before, after);
  10075. }
  10076. /// @internal
  10077. toString() { return this.node.toString(); }
  10078. }
  10079. function getChildren(node, type, before, after) {
  10080. let cur = node.cursor, result = [];
  10081. if (!cur.firstChild())
  10082. return result;
  10083. if (before != null)
  10084. while (!cur.type.is(before))
  10085. if (!cur.nextSibling())
  10086. return result;
  10087. for (;;) {
  10088. if (after != null && cur.type.is(after))
  10089. return result;
  10090. if (cur.type.is(type))
  10091. result.push(cur.node);
  10092. if (!cur.nextSibling())
  10093. return after == null ? result : [];
  10094. }
  10095. }
  10096. class BufferContext {
  10097. constructor(parent, buffer, index, start) {
  10098. this.parent = parent;
  10099. this.buffer = buffer;
  10100. this.index = index;
  10101. this.start = start;
  10102. }
  10103. }
  10104. class BufferNode {
  10105. constructor(context, _parent, index) {
  10106. this.context = context;
  10107. this._parent = _parent;
  10108. this.index = index;
  10109. this.type = context.buffer.set.types[context.buffer.buffer[index]];
  10110. }
  10111. get name() { return this.type.name; }
  10112. get from() { return this.context.start + this.context.buffer.buffer[this.index + 1]; }
  10113. get to() { return this.context.start + this.context.buffer.buffer[this.index + 2]; }
  10114. child(dir, after) {
  10115. let { buffer } = this.context;
  10116. let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - this.context.start);
  10117. return index < 0 ? null : new BufferNode(this.context, this, index);
  10118. }
  10119. get firstChild() { return this.child(1, -100000000 /* None */); }
  10120. get lastChild() { return this.child(-1, -100000000 /* None */); }
  10121. childAfter(pos) { return this.child(1, pos); }
  10122. childBefore(pos) { return this.child(-1, pos); }
  10123. get parent() {
  10124. return this._parent || this.context.parent.nextSignificantParent();
  10125. }
  10126. externalSibling(dir) {
  10127. return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, -1);
  10128. }
  10129. get nextSibling() {
  10130. let { buffer } = this.context;
  10131. let after = buffer.buffer[this.index + 3];
  10132. if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length))
  10133. return new BufferNode(this.context, this._parent, after);
  10134. return this.externalSibling(1);
  10135. }
  10136. get prevSibling() {
  10137. let { buffer } = this.context;
  10138. let parentStart = this._parent ? this._parent.index + 4 : 0;
  10139. if (this.index == parentStart)
  10140. return this.externalSibling(-1);
  10141. return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, -100000000 /* None */));
  10142. }
  10143. get cursor() { return new TreeCursor(this); }
  10144. resolve(pos, side = 0) {
  10145. return this.cursor.moveTo(pos, side).node;
  10146. }
  10147. /// @internal
  10148. toString() { return this.context.buffer.childString(this.index); }
  10149. getChild(type, before = null, after = null) {
  10150. let r = getChildren(this, type, before, after);
  10151. return r.length ? r[0] : null;
  10152. }
  10153. getChildren(type, before = null, after = null) {
  10154. return getChildren(this, type, before, after);
  10155. }
  10156. }
  10157. /// A tree cursor object focuses on a given node in a syntax tree, and
  10158. /// allows you to move to adjacent nodes.
  10159. class TreeCursor {
  10160. /// @internal
  10161. constructor(node, full = false) {
  10162. this.full = full;
  10163. this.buffer = null;
  10164. this.stack = [];
  10165. this.index = 0;
  10166. this.bufferNode = null;
  10167. if (node instanceof TreeNode) {
  10168. this.yieldNode(node);
  10169. }
  10170. else {
  10171. this._tree = node.context.parent;
  10172. this.buffer = node.context;
  10173. for (let n = node._parent; n; n = n._parent)
  10174. this.stack.unshift(n.index);
  10175. this.bufferNode = node;
  10176. this.yieldBuf(node.index);
  10177. }
  10178. }
  10179. /// Shorthand for `.type.name`.
  10180. get name() { return this.type.name; }
  10181. yieldNode(node) {
  10182. if (!node)
  10183. return false;
  10184. this._tree = node;
  10185. this.type = node.type;
  10186. this.from = node.from;
  10187. this.to = node.to;
  10188. return true;
  10189. }
  10190. yieldBuf(index, type) {
  10191. this.index = index;
  10192. let { start, buffer } = this.buffer;
  10193. this.type = type || buffer.set.types[buffer.buffer[index]];
  10194. this.from = start + buffer.buffer[index + 1];
  10195. this.to = start + buffer.buffer[index + 2];
  10196. return true;
  10197. }
  10198. yield(node) {
  10199. if (!node)
  10200. return false;
  10201. if (node instanceof TreeNode) {
  10202. this.buffer = null;
  10203. return this.yieldNode(node);
  10204. }
  10205. this.buffer = node.context;
  10206. return this.yieldBuf(node.index, node.type);
  10207. }
  10208. /// @internal
  10209. toString() {
  10210. return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
  10211. }
  10212. /// @internal
  10213. enter(dir, after) {
  10214. if (!this.buffer)
  10215. return this.yield(this._tree.nextChild(dir < 0 ? this._tree.node.children.length - 1 : 0, dir, after, this.full));
  10216. let { buffer } = this.buffer;
  10217. let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, after == -100000000 /* None */ ? -100000000 /* None */ : after - this.buffer.start);
  10218. if (index < 0)
  10219. return false;
  10220. this.stack.push(this.index);
  10221. return this.yieldBuf(index);
  10222. }
  10223. /// Move the cursor to this node's first child. When this returns
  10224. /// false, the node has no child, and the cursor has not been moved.
  10225. firstChild() { return this.enter(1, -100000000 /* None */); }
  10226. /// Move the cursor to this node's last child.
  10227. lastChild() { return this.enter(-1, -100000000 /* None */); }
  10228. /// Move the cursor to the first child that starts at or after `pos`.
  10229. childAfter(pos) { return this.enter(1, pos); }
  10230. /// Move to the last child that ends at or before `pos`.
  10231. childBefore(pos) { return this.enter(-1, pos); }
  10232. /// Move the node's parent node, if this isn't the top node.
  10233. parent() {
  10234. if (!this.buffer)
  10235. return this.yieldNode(this.full ? this._tree._parent : this._tree.parent);
  10236. if (this.stack.length)
  10237. return this.yieldBuf(this.stack.pop());
  10238. let parent = this.full ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
  10239. this.buffer = null;
  10240. return this.yieldNode(parent);
  10241. }
  10242. /// @internal
  10243. sibling(dir) {
  10244. if (!this.buffer)
  10245. return !this._tree._parent ? false
  10246. : this.yield(this._tree._parent.nextChild(this._tree.index + dir, dir, -100000000 /* None */, this.full));
  10247. let { buffer } = this.buffer, d = this.stack.length - 1;
  10248. if (dir < 0) {
  10249. let parentStart = d < 0 ? 0 : this.stack[d] + 4;
  10250. if (this.index != parentStart)
  10251. return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, -100000000 /* None */));
  10252. }
  10253. else {
  10254. let after = buffer.buffer[this.index + 3];
  10255. if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3]))
  10256. return this.yieldBuf(after);
  10257. }
  10258. return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, -100000000 /* None */, this.full)) : false;
  10259. }
  10260. /// Move to this node's next sibling, if any.
  10261. nextSibling() { return this.sibling(1); }
  10262. /// Move to this node's previous sibling, if any.
  10263. prevSibling() { return this.sibling(-1); }
  10264. atLastNode(dir) {
  10265. let index, parent, { buffer } = this;
  10266. if (buffer) {
  10267. if (dir > 0) {
  10268. if (this.index < buffer.buffer.buffer.length)
  10269. return false;
  10270. }
  10271. else {
  10272. for (let i = 0; i < this.index; i++)
  10273. if (buffer.buffer.buffer[i + 3] < this.index)
  10274. return false;
  10275. }
  10276. ({ index, parent } = buffer);
  10277. }
  10278. else {
  10279. ({ index, _parent: parent } = this._tree);
  10280. }
  10281. for (; parent; { index, _parent: parent } = parent) {
  10282. for (let i = index + dir, e = dir < 0 ? -1 : parent.node.children.length; i != e; i += dir) {
  10283. let child = parent.node.children[i];
  10284. if (this.full || !child.type.isAnonymous || child instanceof TreeBuffer || hasChild(child))
  10285. return false;
  10286. }
  10287. }
  10288. return true;
  10289. }
  10290. move(dir) {
  10291. if (this.enter(dir, -100000000 /* None */))
  10292. return true;
  10293. for (;;) {
  10294. if (this.sibling(dir))
  10295. return true;
  10296. if (this.atLastNode(dir) || !this.parent())
  10297. return false;
  10298. }
  10299. }
  10300. /// Move to the next node in a
  10301. /// [pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))
  10302. /// traversal, going from a node to its first child or, if the
  10303. /// current node is empty, its next sibling or the next sibling of
  10304. /// the first parent node that has one.
  10305. next() { return this.move(1); }
  10306. /// Move to the next node in a last-to-first pre-order traveral. A
  10307. /// node is followed by ist last child or, if it has none, its
  10308. /// previous sibling or the previous sibling of the first parent
  10309. /// node that has one.
  10310. prev() { return this.move(-1); }
  10311. /// Move the cursor to the innermost node that covers `pos`. If
  10312. /// `side` is -1, it will enter nodes that end at `pos`. If it is 1,
  10313. /// it will enter nodes that start at `pos`.
  10314. moveTo(pos, side = 0) {
  10315. // Move up to a node that actually holds the position, if possible
  10316. while (this.from == this.to ||
  10317. (side < 1 ? this.from >= pos : this.from > pos) ||
  10318. (side > -1 ? this.to <= pos : this.to < pos))
  10319. if (!this.parent())
  10320. break;
  10321. // Then scan down into child nodes as far as possible
  10322. for (;;) {
  10323. if (side < 0 ? !this.childBefore(pos) : !this.childAfter(pos))
  10324. break;
  10325. if (this.from == this.to ||
  10326. (side < 1 ? this.from >= pos : this.from > pos) ||
  10327. (side > -1 ? this.to <= pos : this.to < pos)) {
  10328. this.parent();
  10329. break;
  10330. }
  10331. }
  10332. return this;
  10333. }
  10334. /// Get a [syntax node](#tree.SyntaxNode) at the cursor's current
  10335. /// position.
  10336. get node() {
  10337. if (!this.buffer)
  10338. return this._tree;
  10339. let cache = this.bufferNode, result = null, depth = 0;
  10340. if (cache && cache.context == this.buffer) {
  10341. scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
  10342. for (let c = cache; c; c = c._parent)
  10343. if (c.index == index) {
  10344. if (index == this.index)
  10345. return c;
  10346. result = c;
  10347. depth = d + 1;
  10348. break scan;
  10349. }
  10350. index = this.stack[--d];
  10351. }
  10352. }
  10353. for (let i = depth; i < this.stack.length; i++)
  10354. result = new BufferNode(this.buffer, result, this.stack[i]);
  10355. return this.bufferNode = new BufferNode(this.buffer, result, this.index);
  10356. }
  10357. /// Get the [tree](#tree.Tree) that represents the current node, if
  10358. /// any. Will return null when the node is in a [tree
  10359. /// buffer](#tree.TreeBuffer).
  10360. get tree() {
  10361. return this.buffer ? null : this._tree.node;
  10362. }
  10363. }
  10364. function hasChild(tree) {
  10365. return tree.children.some(ch => !ch.type.isAnonymous || ch instanceof TreeBuffer || hasChild(ch));
  10366. }
  10367. class FlatBufferCursor {
  10368. constructor(buffer, index) {
  10369. this.buffer = buffer;
  10370. this.index = index;
  10371. }
  10372. get id() { return this.buffer[this.index - 4]; }
  10373. get start() { return this.buffer[this.index - 3]; }
  10374. get end() { return this.buffer[this.index - 2]; }
  10375. get size() { return this.buffer[this.index - 1]; }
  10376. get pos() { return this.index; }
  10377. next() { this.index -= 4; }
  10378. fork() { return new FlatBufferCursor(this.buffer, this.index); }
  10379. }
  10380. const BalanceBranchFactor = 8;
  10381. function buildTree(data) {
  10382. var _a;
  10383. let { buffer, nodeSet, topID = 0, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet.types.length } = data;
  10384. let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
  10385. let types = nodeSet.types;
  10386. function takeNode(parentStart, minPos, children, positions, inRepeat) {
  10387. let { id, start, end, size } = cursor;
  10388. while (id == inRepeat) {
  10389. cursor.next();
  10390. ({ id, start, end, size } = cursor);
  10391. }
  10392. let startPos = start - parentStart;
  10393. if (size < 0) { // Reused node
  10394. children.push(reused[id]);
  10395. positions.push(startPos);
  10396. cursor.next();
  10397. return;
  10398. }
  10399. let type = types[id], node, buffer;
  10400. if (end - start <= maxBufferLength && (buffer = findBufferSize(cursor.pos - minPos, inRepeat))) {
  10401. // Small enough for a buffer, and no reused nodes inside
  10402. let data = new Uint16Array(buffer.size - buffer.skip);
  10403. let endPos = cursor.pos - buffer.size, index = data.length;
  10404. while (cursor.pos > endPos)
  10405. index = copyToBuffer(buffer.start, data, index, inRepeat);
  10406. node = new TreeBuffer(data, end - buffer.start, nodeSet, inRepeat < 0 ? NodeType.none : types[inRepeat]);
  10407. startPos = buffer.start - parentStart;
  10408. }
  10409. else { // Make it a node
  10410. let endPos = cursor.pos - size;
  10411. cursor.next();
  10412. let localChildren = [], localPositions = [];
  10413. let localInRepeat = id >= minRepeatType ? id : -1;
  10414. while (cursor.pos > endPos)
  10415. takeNode(start, endPos, localChildren, localPositions, localInRepeat);
  10416. localChildren.reverse();
  10417. localPositions.reverse();
  10418. if (localInRepeat > -1 && localChildren.length > BalanceBranchFactor)
  10419. node = balanceRange(type, type, localChildren, localPositions, 0, localChildren.length, 0, maxBufferLength, end - start);
  10420. else
  10421. node = new Tree(type, localChildren, localPositions, end - start);
  10422. }
  10423. children.push(node);
  10424. positions.push(startPos);
  10425. }
  10426. function findBufferSize(maxSize, inRepeat) {
  10427. // Scan through the buffer to find previous siblings that fit
  10428. // together in a TreeBuffer, and don't contain any reused nodes
  10429. // (which can't be stored in a buffer).
  10430. // If `inRepeat` is > -1, ignore node boundaries of that type for
  10431. // nesting, but make sure the end falls either at the start
  10432. // (`maxSize`) or before such a node.
  10433. let fork = cursor.fork();
  10434. let size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength;
  10435. let result = { size: 0, start: 0, skip: 0 };
  10436. scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
  10437. // Pretend nested repeat nodes of the same type don't exist
  10438. if (fork.id == inRepeat) {
  10439. // Except that we store the current state as a valid return
  10440. // value.
  10441. result.size = size;
  10442. result.start = start;
  10443. result.skip = skip;
  10444. skip += 4;
  10445. size += 4;
  10446. fork.next();
  10447. continue;
  10448. }
  10449. let nodeSize = fork.size, startPos = fork.pos - nodeSize;
  10450. if (nodeSize < 0 || startPos < minPos || fork.start < minStart)
  10451. break;
  10452. let localSkipped = fork.id >= minRepeatType ? 4 : 0;
  10453. let nodeStart = fork.start;
  10454. fork.next();
  10455. while (fork.pos > startPos) {
  10456. if (fork.size < 0)
  10457. break scan;
  10458. if (fork.id >= minRepeatType)
  10459. localSkipped += 4;
  10460. fork.next();
  10461. }
  10462. start = nodeStart;
  10463. size += nodeSize;
  10464. skip += localSkipped;
  10465. }
  10466. if (inRepeat < 0 || size == maxSize) {
  10467. result.size = size;
  10468. result.start = start;
  10469. result.skip = skip;
  10470. }
  10471. return result.size > 4 ? result : undefined;
  10472. }
  10473. function copyToBuffer(bufferStart, buffer, index, inRepeat) {
  10474. let { id, start, end, size } = cursor;
  10475. cursor.next();
  10476. if (id == inRepeat)
  10477. return index;
  10478. let startIndex = index;
  10479. if (size > 4) {
  10480. let endPos = cursor.pos - (size - 4);
  10481. while (cursor.pos > endPos)
  10482. index = copyToBuffer(bufferStart, buffer, index, inRepeat);
  10483. }
  10484. if (id < minRepeatType) { // Don't copy repeat nodes into buffers
  10485. buffer[--index] = startIndex;
  10486. buffer[--index] = end - bufferStart;
  10487. buffer[--index] = start - bufferStart;
  10488. buffer[--index] = id;
  10489. }
  10490. return index;
  10491. }
  10492. let children = [], positions = [];
  10493. while (cursor.pos > 0)
  10494. takeNode(data.start || 0, 0, children, positions, -1);
  10495. let length = (_a = data.length) !== null && _a !== void 0 ? _a : (children.length ? positions[0] + children[0].length : 0);
  10496. return new Tree(types[topID], children.reverse(), positions.reverse(), length);
  10497. }
  10498. function balanceRange(outerType, innerType, children, positions, from, to, start, maxBufferLength, length) {
  10499. let localChildren = [], localPositions = [];
  10500. if (length <= maxBufferLength) {
  10501. for (let i = from; i < to; i++) {
  10502. localChildren.push(children[i]);
  10503. localPositions.push(positions[i] - start);
  10504. }
  10505. }
  10506. else {
  10507. let maxChild = Math.max(maxBufferLength, Math.ceil(length * 1.5 / BalanceBranchFactor));
  10508. for (let i = from; i < to;) {
  10509. let groupFrom = i, groupStart = positions[i];
  10510. i++;
  10511. for (; i < to; i++) {
  10512. let nextEnd = positions[i] + children[i].length;
  10513. if (nextEnd - groupStart > maxChild)
  10514. break;
  10515. }
  10516. if (i == groupFrom + 1) {
  10517. let only = children[groupFrom];
  10518. if (only instanceof Tree && only.type == innerType && only.length > maxChild << 1) { // Too big, collapse
  10519. for (let j = 0; j < only.children.length; j++) {
  10520. localChildren.push(only.children[j]);
  10521. localPositions.push(only.positions[j] + groupStart - start);
  10522. }
  10523. continue;
  10524. }
  10525. localChildren.push(only);
  10526. }
  10527. else if (i == groupFrom + 1) {
  10528. localChildren.push(children[groupFrom]);
  10529. }
  10530. else {
  10531. let inner = balanceRange(innerType, innerType, children, positions, groupFrom, i, groupStart, maxBufferLength, positions[i - 1] + children[i - 1].length - groupStart);
  10532. if (innerType != NodeType.none && !containsType(inner.children, innerType))
  10533. inner = new Tree(NodeType.none, inner.children, inner.positions, inner.length);
  10534. localChildren.push(inner);
  10535. }
  10536. localPositions.push(groupStart - start);
  10537. }
  10538. }
  10539. return new Tree(outerType, localChildren, localPositions, length);
  10540. }
  10541. function containsType(nodes, type) {
  10542. for (let elt of nodes)
  10543. if (elt.type == type)
  10544. return true;
  10545. return false;
  10546. }
  10547. /// Tree fragments are used during [incremental
  10548. /// parsing](#lezer.ParseOptions.fragments) to track parts of old
  10549. /// trees that can be reused in a new parse. An array of fragments is
  10550. /// used to track regions of an old tree whose nodes might be reused
  10551. /// in new parses. Use the static
  10552. /// [`applyChanges`](#tree.TreeFragment^applyChanges) method to update
  10553. /// fragments for document changes.
  10554. class TreeFragment {
  10555. constructor(
  10556. /// The start of the unchanged range pointed to by this fragment.
  10557. /// This refers to an offset in the _updated_ document (as opposed
  10558. /// to the original tree).
  10559. from,
  10560. /// The end of the unchanged range.
  10561. to,
  10562. /// The tree that this fragment is based on.
  10563. tree,
  10564. /// The offset between the fragment's tree and the document that
  10565. /// this fragment can be used against. Add this when going from
  10566. /// document to tree positions, subtract it to go from tree to
  10567. /// document positions.
  10568. offset, open) {
  10569. this.from = from;
  10570. this.to = to;
  10571. this.tree = tree;
  10572. this.offset = offset;
  10573. this.open = open;
  10574. }
  10575. get openStart() { return (this.open & 1 /* Start */) > 0; }
  10576. get openEnd() { return (this.open & 2 /* End */) > 0; }
  10577. /// Apply a set of edits to an array of fragments, removing or
  10578. /// splitting fragments as necessary to remove edited ranges, and
  10579. /// adjusting offsets for fragments that moved.
  10580. static applyChanges(fragments, changes, minGap = 128) {
  10581. if (!changes.length)
  10582. return fragments;
  10583. let result = [];
  10584. let fI = 1, nextF = fragments.length ? fragments[0] : null;
  10585. let cI = 0, pos = 0, off = 0;
  10586. for (;;) {
  10587. let nextC = cI < changes.length ? changes[cI++] : null;
  10588. let nextPos = nextC ? nextC.fromA : 1e9;
  10589. if (nextPos - pos >= minGap)
  10590. while (nextF && nextF.from < nextPos) {
  10591. let cut = nextF;
  10592. if (pos >= cut.from || nextPos <= cut.to || off) {
  10593. let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off;
  10594. cut = fFrom >= fTo ? null :
  10595. new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, (cI > 0 ? 1 /* Start */ : 0) | (nextC ? 2 /* End */ : 0));
  10596. }
  10597. if (cut)
  10598. result.push(cut);
  10599. if (nextF.to > nextPos)
  10600. break;
  10601. nextF = fI < fragments.length ? fragments[fI++] : null;
  10602. }
  10603. if (!nextC)
  10604. break;
  10605. pos = nextC.toA;
  10606. off = nextC.toA - nextC.toB;
  10607. }
  10608. return result;
  10609. }
  10610. /// Create a set of fragments from a freshly parsed tree, or update
  10611. /// an existing set of fragments by replacing the ones that overlap
  10612. /// with a tree with content from the new tree. When `partial` is
  10613. /// true, the parse is treated as incomplete, and the token at its
  10614. /// end is not included in [`safeTo`](#tree.TreeFragment.safeTo).
  10615. static addTree(tree, fragments = [], partial = false) {
  10616. let result = [new TreeFragment(0, tree.length, tree, 0, partial ? 2 /* End */ : 0)];
  10617. for (let f of fragments)
  10618. if (f.to > tree.length)
  10619. result.push(f);
  10620. return result;
  10621. }
  10622. }
  10623. // Creates an `Input` that is backed by a single, flat string.
  10624. function stringInput(input) { return new StringInput(input); }
  10625. class StringInput {
  10626. constructor(string, length = string.length) {
  10627. this.string = string;
  10628. this.length = length;
  10629. }
  10630. get(pos) {
  10631. return pos < 0 || pos >= this.length ? -1 : this.string.charCodeAt(pos);
  10632. }
  10633. lineAfter(pos) {
  10634. if (pos < 0)
  10635. return "";
  10636. let end = this.string.indexOf("\n", pos);
  10637. return this.string.slice(pos, end < 0 ? this.length : Math.min(end, this.length));
  10638. }
  10639. read(from, to) { return this.string.slice(from, Math.min(this.length, to)); }
  10640. clip(at) { return new StringInput(this.string, at); }
  10641. }
  10642. /// Node prop stored in a grammar's top syntax node to provide the
  10643. /// facet that stores language data for that language.
  10644. const languageDataProp = new NodeProp();
  10645. /// Helper function to define a facet (to be added to the top syntax
  10646. /// node(s) for a language via
  10647. /// [`languageDataProp`](#language.languageDataProp)), that will be
  10648. /// used to associate language data with the language. You
  10649. /// probably only need this when subclassing
  10650. /// [`Language`](#language.Language).
  10651. function defineLanguageFacet(baseData) {
  10652. return Facet.define({
  10653. combine: baseData ? values => values.concat(baseData) : undefined
  10654. });
  10655. }
  10656. /// A language object manages parsing and per-language
  10657. /// [metadata](#state.EditorState.languageDataAt). Parse data is
  10658. /// managed as a [Lezer](https://lezer.codemirror.net) tree. You'll
  10659. /// want to subclass this class for custom parsers, or use the
  10660. /// [`LezerLanguage`](#language.LezerLanguage) or
  10661. /// [`StreamLanguage`](#stream-parser.StreamLanguage) abstractions for
  10662. /// [Lezer](https://lezer.codemirror.net/) or stream parsers.
  10663. class Language {
  10664. /// Construct a language object. You usually don't need to invoke
  10665. /// this directly. But when you do, make sure you use
  10666. /// [`defineLanguageFacet`](#language.defineLanguageFacet) to create
  10667. /// the first argument.
  10668. constructor(
  10669. /// The [language data](#state.EditorState.languageDataAt) data
  10670. /// facet used for this language.
  10671. data, parser, extraExtensions = []) {
  10672. this.data = data;
  10673. // Kludge to define EditorState.tree as a debugging helper,
  10674. // without the EditorState package actually knowing about
  10675. // languages and lezer trees.
  10676. if (!EditorState.prototype.hasOwnProperty("tree"))
  10677. Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
  10678. this.parser = parser;
  10679. this.extension = [
  10680. language.of(this),
  10681. EditorState.languageData.of((state, pos) => state.facet(languageDataFacetAt(state, pos)))
  10682. ].concat(extraExtensions);
  10683. }
  10684. /// Query whether this language is active at the given position.
  10685. isActiveAt(state, pos) {
  10686. return languageDataFacetAt(state, pos) == this.data;
  10687. }
  10688. /// Find the document regions that were parsed using this language.
  10689. /// The returned regions will _include_ any nested languages rooted
  10690. /// in this language, when those exist.
  10691. findRegions(state) {
  10692. let lang = state.facet(language);
  10693. if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
  10694. return [{ from: 0, to: state.doc.length }];
  10695. if (!lang || !lang.allowsNesting)
  10696. return [];
  10697. let result = [];
  10698. syntaxTree(state).iterate({
  10699. enter: (type, from, to) => {
  10700. if (type.isTop && type.prop(languageDataProp) == this.data) {
  10701. result.push({ from, to });
  10702. return false;
  10703. }
  10704. return undefined;
  10705. }
  10706. });
  10707. return result;
  10708. }
  10709. /// Indicates whether this language allows nested languages. The
  10710. /// default implementation returns true.
  10711. get allowsNesting() { return true; }
  10712. /// Use this language to parse the given string into a tree.
  10713. parseString(code) {
  10714. let doc = Text.of(code.split("\n"));
  10715. let parse = this.parser.startParse(new DocInput(doc), 0, new EditorParseContext(this.parser, EditorState.create({ doc }), [], Tree.empty, { from: 0, to: code.length }, []));
  10716. let tree;
  10717. while (!(tree = parse.advance())) { }
  10718. return tree;
  10719. }
  10720. }
  10721. /// @internal
  10722. Language.setState = StateEffect.define();
  10723. function languageDataFacetAt(state, pos) {
  10724. let topLang = state.facet(language);
  10725. if (!topLang)
  10726. return null;
  10727. if (!topLang.allowsNesting)
  10728. return topLang.data;
  10729. let tree = syntaxTree(state);
  10730. let target = tree.resolve(pos, -1);
  10731. while (target) {
  10732. let facet = target.type.prop(languageDataProp);
  10733. if (facet)
  10734. return facet;
  10735. target = target.parent;
  10736. }
  10737. return topLang.data;
  10738. }
  10739. /// A subclass of [`Language`](#language.Language) for use with
  10740. /// [Lezer](https://lezer.codemirror.net/docs/ref#lezer.Parser)
  10741. /// parsers.
  10742. class LezerLanguage extends Language {
  10743. constructor(data, parser) {
  10744. super(data, parser);
  10745. this.parser = parser;
  10746. }
  10747. /// Define a language from a parser.
  10748. static define(spec) {
  10749. let data = defineLanguageFacet(spec.languageData);
  10750. return new LezerLanguage(data, spec.parser.configure({
  10751. props: [languageDataProp.add(type => type.isTop ? data : undefined)]
  10752. }));
  10753. }
  10754. /// Create a new instance of this language with a reconfigured
  10755. /// version of its parser.
  10756. configure(options) {
  10757. return new LezerLanguage(this.data, this.parser.configure(options));
  10758. }
  10759. get allowsNesting() { return this.parser.hasNested; }
  10760. }
  10761. /// Get the syntax tree for a state, which is the current (possibly
  10762. /// incomplete) parse tree of active [language](#language.Language),
  10763. /// or the empty tree if there is no language available.
  10764. function syntaxTree(state) {
  10765. let field = state.field(Language.state, false);
  10766. return field ? field.tree : Tree.empty;
  10767. }
  10768. // Lezer-style Input object for a Text document.
  10769. class DocInput {
  10770. constructor(doc, length = doc.length) {
  10771. this.doc = doc;
  10772. this.length = length;
  10773. this.cursorPos = 0;
  10774. this.string = "";
  10775. this.prevString = "";
  10776. this.cursor = doc.iter();
  10777. }
  10778. syncTo(pos) {
  10779. if (pos < this.cursorPos) { // Reset the cursor if we have to go back
  10780. this.cursor = this.doc.iter();
  10781. this.cursorPos = 0;
  10782. }
  10783. this.prevString = pos == this.cursorPos ? this.string : "";
  10784. this.string = this.cursor.next(pos - this.cursorPos).value;
  10785. this.cursorPos = pos + this.string.length;
  10786. return this.cursorPos - this.string.length;
  10787. }
  10788. get(pos) {
  10789. if (pos >= this.length)
  10790. return -1;
  10791. let stringStart = this.cursorPos - this.string.length;
  10792. if (pos < stringStart || pos >= this.cursorPos) {
  10793. if (pos < stringStart && pos >= stringStart - this.prevString.length)
  10794. return this.prevString.charCodeAt(pos - (stringStart - this.prevString.length));
  10795. stringStart = this.syncTo(pos);
  10796. }
  10797. return this.string.charCodeAt(pos - stringStart);
  10798. }
  10799. lineAfter(pos) {
  10800. if (pos >= this.length || pos < 0)
  10801. return "";
  10802. let stringStart = this.cursorPos - this.string.length;
  10803. if (pos < stringStart || pos >= this.cursorPos)
  10804. stringStart = this.syncTo(pos);
  10805. return this.cursor.lineBreak ? "" : this.string.slice(pos - stringStart);
  10806. }
  10807. read(from, to) {
  10808. let stringStart = this.cursorPos - this.string.length;
  10809. if (from < stringStart || to >= this.cursorPos)
  10810. return this.doc.sliceString(from, to);
  10811. else
  10812. return this.string.slice(from - stringStart, to - stringStart);
  10813. }
  10814. clip(at) {
  10815. return new DocInput(this.doc, at);
  10816. }
  10817. }
  10818. /// A parse context provided to parsers working on the editor content.
  10819. class EditorParseContext {
  10820. /// @internal
  10821. constructor(parser,
  10822. /// The current editor state.
  10823. state,
  10824. /// Tree fragments that can be reused by incremental re-parses.
  10825. fragments = [],
  10826. /// @internal
  10827. tree,
  10828. /// The current editor viewport (or some overapproximation
  10829. /// thereof). Intended to be used for opportunistically avoiding
  10830. /// work (in which case
  10831. /// [`skipUntilInView`](#language.EditorParseContext.skipUntilInView)
  10832. /// should be called to make sure the parser is restarted when the
  10833. /// skipped region becomes visible).
  10834. viewport,
  10835. /// @internal
  10836. skipped) {
  10837. this.parser = parser;
  10838. this.state = state;
  10839. this.fragments = fragments;
  10840. this.tree = tree;
  10841. this.viewport = viewport;
  10842. this.skipped = skipped;
  10843. this.parse = null;
  10844. /// @internal
  10845. this.tempSkipped = [];
  10846. }
  10847. /// @internal
  10848. work(time, upto) {
  10849. if (this.tree != Tree.empty && (upto == null ? this.tree.length == this.state.doc.length : this.tree.length >= upto)) {
  10850. this.takeTree();
  10851. return true;
  10852. }
  10853. if (!this.parse)
  10854. this.parse = this.parser.startParse(new DocInput(this.state.doc), 0, this);
  10855. let endTime = Date.now() + time;
  10856. for (;;) {
  10857. let done = this.parse.advance();
  10858. if (done) {
  10859. this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done));
  10860. this.parse = null;
  10861. this.tree = done;
  10862. return true;
  10863. }
  10864. else if (upto != null && this.parse.pos >= upto) {
  10865. this.takeTree();
  10866. return true;
  10867. }
  10868. if (Date.now() > endTime)
  10869. return false;
  10870. }
  10871. }
  10872. /// @internal
  10873. takeTree() {
  10874. if (this.parse && this.parse.pos > this.tree.length) {
  10875. this.tree = this.parse.forceFinish();
  10876. this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
  10877. }
  10878. }
  10879. withoutTempSkipped(fragments) {
  10880. for (let r; r = this.tempSkipped.pop();)
  10881. fragments = cutFragments(fragments, r.from, r.to);
  10882. return fragments;
  10883. }
  10884. /// @internal
  10885. changes(changes, newState) {
  10886. let { fragments, tree, viewport, skipped } = this;
  10887. this.takeTree();
  10888. if (!changes.empty) {
  10889. let ranges = [];
  10890. changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
  10891. fragments = TreeFragment.applyChanges(fragments, ranges);
  10892. tree = Tree.empty;
  10893. viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
  10894. if (this.skipped.length) {
  10895. skipped = [];
  10896. for (let r of this.skipped) {
  10897. let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
  10898. if (from < to)
  10899. skipped.push({ from, to });
  10900. }
  10901. }
  10902. }
  10903. return new EditorParseContext(this.parser, newState, fragments, tree, viewport, skipped);
  10904. }
  10905. /// @internal
  10906. updateViewport(viewport) {
  10907. this.viewport = viewport;
  10908. let startLen = this.skipped.length;
  10909. for (let i = 0; i < this.skipped.length; i++) {
  10910. let { from, to } = this.skipped[i];
  10911. if (from < viewport.to && to > viewport.from) {
  10912. this.fragments = cutFragments(this.fragments, from, to);
  10913. this.skipped.splice(i--, 1);
  10914. }
  10915. }
  10916. return this.skipped.length < startLen;
  10917. }
  10918. /// @internal
  10919. reset() {
  10920. if (this.parse) {
  10921. this.takeTree();
  10922. this.parse = null;
  10923. }
  10924. }
  10925. /// Notify the parse scheduler that the given region was skipped
  10926. /// because it wasn't in view, and the parse should be restarted
  10927. /// when it comes into view.
  10928. skipUntilInView(from, to) {
  10929. this.skipped.push({ from, to });
  10930. }
  10931. /// @internal
  10932. movedPast(pos) {
  10933. return this.tree.length < pos && this.parse && this.parse.pos >= pos;
  10934. }
  10935. }
  10936. /// A parser intended to be used as placeholder when asynchronously
  10937. /// loading a nested parser. It'll skip its input and mark it as
  10938. /// not-really-parsed, so that the next update will parse it again.
  10939. EditorParseContext.skippingParser = {
  10940. startParse(input, startPos, context) {
  10941. return {
  10942. pos: startPos,
  10943. advance() {
  10944. context.tempSkipped.push({ from: startPos, to: input.length });
  10945. this.pos = input.length;
  10946. return new Tree(NodeType.none, [], [], input.length - startPos);
  10947. },
  10948. forceFinish() { return this.advance(); }
  10949. };
  10950. }
  10951. };
  10952. function cutFragments(fragments, from, to) {
  10953. return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
  10954. }
  10955. class LanguageState {
  10956. constructor(
  10957. // A mutable parse state that is used to preserve work done during
  10958. // the lifetime of a state when moving to the next state.
  10959. context) {
  10960. this.context = context;
  10961. this.tree = context.tree;
  10962. }
  10963. apply(tr) {
  10964. if (!tr.docChanged)
  10965. return this;
  10966. let newCx = this.context.changes(tr.changes, tr.state);
  10967. // If the previous parse wasn't done, go forward only up to its
  10968. // end position or the end of the viewport, to avoid slowing down
  10969. // state updates with parse work beyond the viewport.
  10970. let upto = this.context.tree.length == tr.startState.doc.length ? undefined
  10971. : Math.max(tr.changes.mapPos(this.context.tree.length), newCx.viewport.to);
  10972. if (!newCx.work(25 /* Apply */, upto))
  10973. newCx.takeTree();
  10974. return new LanguageState(newCx);
  10975. }
  10976. static init(state) {
  10977. let parseState = new EditorParseContext(state.facet(language).parser, state, [], Tree.empty, { from: 0, to: state.doc.length }, []);
  10978. if (!parseState.work(25 /* Apply */))
  10979. parseState.takeTree();
  10980. return new LanguageState(parseState);
  10981. }
  10982. }
  10983. Language.state = StateField.define({
  10984. create: LanguageState.init,
  10985. update(value, tr) {
  10986. for (let e of tr.effects)
  10987. if (e.is(Language.setState))
  10988. return e.value;
  10989. if (tr.startState.facet(language) != tr.state.facet(language))
  10990. return LanguageState.init(tr.state);
  10991. return value.apply(tr);
  10992. }
  10993. });
  10994. let requestIdle = typeof window != "undefined" && window.requestIdleCallback ||
  10995. ((callback, { timeout }) => setTimeout(callback, timeout));
  10996. let cancelIdle = typeof window != "undefined" && window.cancelIdleCallback || clearTimeout;
  10997. const parseWorker = ViewPlugin.fromClass(class ParseWorker {
  10998. constructor(view) {
  10999. this.view = view;
  11000. this.working = -1;
  11001. // End of the current time chunk
  11002. this.chunkEnd = -1;
  11003. // Milliseconds of budget left for this chunk
  11004. this.chunkBudget = -1;
  11005. this.work = this.work.bind(this);
  11006. this.scheduleWork();
  11007. }
  11008. update(update) {
  11009. if (update.viewportChanged) {
  11010. let cx = this.view.state.field(Language.state).context;
  11011. if (cx.updateViewport(update.view.viewport))
  11012. cx.reset();
  11013. if (this.view.viewport.to > cx.tree.length)
  11014. this.scheduleWork();
  11015. }
  11016. if (update.docChanged) {
  11017. if (this.view.hasFocus)
  11018. this.chunkBudget += 50 /* ChangeBonus */;
  11019. this.scheduleWork();
  11020. }
  11021. }
  11022. scheduleWork() {
  11023. if (this.working > -1)
  11024. return;
  11025. let { state } = this.view, field = state.field(Language.state);
  11026. if (field.tree.length >= state.doc.length)
  11027. return;
  11028. this.working = requestIdle(this.work, { timeout: 500 /* Pause */ });
  11029. }
  11030. work(deadline) {
  11031. this.working = -1;
  11032. let now = Date.now();
  11033. if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
  11034. this.chunkEnd = now + 30000 /* ChunkTime */;
  11035. this.chunkBudget = 3000 /* ChunkBudget */;
  11036. }
  11037. if (this.chunkBudget <= 0)
  11038. return; // No more budget
  11039. let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
  11040. if (field.tree.length >= vpTo + 1000000 /* MaxParseAhead */)
  11041. return;
  11042. let time = Math.min(this.chunkBudget, deadline ? Math.max(25 /* MinSlice */, deadline.timeRemaining()) : 100 /* Slice */);
  11043. let done = field.context.work(time, vpTo + 1000000 /* MaxParseAhead */);
  11044. this.chunkBudget -= Date.now() - now;
  11045. if (done || this.chunkBudget <= 0 || field.context.movedPast(vpTo)) {
  11046. field.context.takeTree();
  11047. this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
  11048. }
  11049. if (!done && this.chunkBudget > 0)
  11050. this.scheduleWork();
  11051. }
  11052. destroy() {
  11053. if (this.working >= 0)
  11054. cancelIdle(this.working);
  11055. }
  11056. }, {
  11057. eventHandlers: { focus() { this.scheduleWork(); } }
  11058. });
  11059. /// The facet used to associate a language with an editor state.
  11060. const language = Facet.define({
  11061. combine(languages) { return languages.length ? languages[0] : null; },
  11062. enables: [Language.state, parseWorker]
  11063. });
  11064. /// This class bundles a [language object](#language.Language) with an
  11065. /// optional set of supporting extensions. Language packages are
  11066. /// encouraged to export a function that optionally takes a
  11067. /// configuration object and returns a `LanguageSupport` instance, as
  11068. /// the main way for client code to use the package.
  11069. class LanguageSupport {
  11070. /// Create a support object.
  11071. constructor(
  11072. /// The language object.
  11073. language,
  11074. /// An optional set of supporting extensions. When nesting a
  11075. /// language in another language, the outer language is encouraged
  11076. /// to include the supporting extensions for its inner languages
  11077. /// in its own set of support extensions.
  11078. support = []) {
  11079. this.language = language;
  11080. this.support = support;
  11081. this.extension = [language, support];
  11082. }
  11083. }
  11084. /// Language descriptions are used to store metadata about languages
  11085. /// and to dynamically load them. Their main role is finding the
  11086. /// appropriate language for a filename or dynamically loading nested
  11087. /// parsers.
  11088. class LanguageDescription {
  11089. constructor(
  11090. /// The name of this language.
  11091. name,
  11092. /// Alternative names for the mode (lowercased, includes `this.name`).
  11093. alias,
  11094. /// File extensions associated with this language.
  11095. extensions,
  11096. /// Optional filename pattern that should be associated with this
  11097. /// language.
  11098. filename, loadFunc) {
  11099. this.name = name;
  11100. this.alias = alias;
  11101. this.extensions = extensions;
  11102. this.filename = filename;
  11103. this.loadFunc = loadFunc;
  11104. /// If the language has been loaded, this will hold its value.
  11105. this.support = undefined;
  11106. this.loading = null;
  11107. }
  11108. /// Start loading the the language. Will return a promise that
  11109. /// resolves to a [`LanguageSupport`](#language.LanguageSupport)
  11110. /// object when the language successfully loads.
  11111. load() {
  11112. return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => { this.loading = null; throw err; }));
  11113. }
  11114. /// Create a language description.
  11115. static of(spec) {
  11116. return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, spec.load);
  11117. }
  11118. /// Look for a language in the given array of descriptions that
  11119. /// matches the filename. Will first match
  11120. /// [`filename`](#language.LanguageDescription.filename) patterns,
  11121. /// and then [extensions](#language.LanguageDescription.extensions),
  11122. /// and return the first language that matches.
  11123. static matchFilename(descs, filename) {
  11124. for (let d of descs)
  11125. if (d.filename && d.filename.test(filename))
  11126. return d;
  11127. let ext = /\.([^.]+)$/.exec(filename);
  11128. if (ext)
  11129. for (let d of descs)
  11130. if (d.extensions.indexOf(ext[1]) > -1)
  11131. return d;
  11132. return null;
  11133. }
  11134. /// Look for a language whose name or alias matches the the given
  11135. /// name (case-insensitively). If `fuzzy` is true, and no direct
  11136. /// matchs is found, this'll also search for a language whose name
  11137. /// or alias occurs in the string (for names shorter than three
  11138. /// characters, only when surrounded by non-word characters).
  11139. static matchLanguageName(descs, name, fuzzy = true) {
  11140. name = name.toLowerCase();
  11141. for (let d of descs)
  11142. if (d.alias.some(a => a == name))
  11143. return d;
  11144. if (fuzzy)
  11145. for (let d of descs)
  11146. for (let a of d.alias) {
  11147. let found = name.indexOf(a);
  11148. if (found > -1 && (a.length > 2 || !/\w/.test(name[found - 1]) && !/\w/.test(name[found + a.length])))
  11149. return d;
  11150. }
  11151. return null;
  11152. }
  11153. }
  11154. /// Facet that defines a way to provide a function that computes the
  11155. /// appropriate indentation depth at the start of a given line, or
  11156. /// `null` to indicate no appropriate indentation could be determined.
  11157. const indentService = Facet.define();
  11158. /// Facet for overriding the unit by which indentation happens.
  11159. /// Should be a string consisting either entirely of spaces or
  11160. /// entirely of tabs. When not set, this defaults to 2 spaces.
  11161. const indentUnit = Facet.define({
  11162. combine: values => {
  11163. if (!values.length)
  11164. return " ";
  11165. if (!/^(?: +|\t+)$/.test(values[0]))
  11166. throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
  11167. return values[0];
  11168. }
  11169. });
  11170. /// Return the _column width_ of an indent unit in the state.
  11171. /// Determined by the [`indentUnit`](#language.indentUnit)
  11172. /// facet, and [`tabSize`](#state.EditorState^tabSize) when that
  11173. /// contains tabs.
  11174. function getIndentUnit(state) {
  11175. let unit = state.facet(indentUnit);
  11176. return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
  11177. }
  11178. /// Create an indentation string that covers columns 0 to `cols`.
  11179. /// Will use tabs for as much of the columns as possible when the
  11180. /// [`indentUnit`](#language.indentUnit) facet contains
  11181. /// tabs.
  11182. function indentString(state, cols) {
  11183. let result = "", ts = state.tabSize;
  11184. if (state.facet(indentUnit).charCodeAt(0) == 9)
  11185. while (cols >= ts) {
  11186. result += "\t";
  11187. cols -= ts;
  11188. }
  11189. for (let i = 0; i < cols; i++)
  11190. result += " ";
  11191. return result;
  11192. }
  11193. /// Get the indentation at the given position. Will first consult any
  11194. /// [indent services](#language.indentService) that are registered,
  11195. /// and if none of those return an indentation, this will check the
  11196. /// syntax tree for the [indent node prop](#language.indentNodeProp)
  11197. /// and use that if found. Returns a number when an indentation could
  11198. /// be determined, and null otherwise.
  11199. function getIndentation(context, pos) {
  11200. if (context instanceof EditorState)
  11201. context = new IndentContext(context);
  11202. for (let service of context.state.facet(indentService)) {
  11203. let result = service(context, pos);
  11204. if (result != null)
  11205. return result;
  11206. }
  11207. let tree = syntaxTree(context.state);
  11208. return tree ? syntaxIndentation(context, tree, pos) : null;
  11209. }
  11210. /// Indentation contexts are used when calling [indentation
  11211. /// services](#language.indentService). They provide helper utilities
  11212. /// useful in indentation logic, and can selectively override the
  11213. /// indentation reported for some lines.
  11214. class IndentContext {
  11215. /// Create an indent context.
  11216. constructor(
  11217. /// The editor state.
  11218. state,
  11219. /// @internal
  11220. options = {}) {
  11221. this.state = state;
  11222. this.options = options;
  11223. this.unit = getIndentUnit(state);
  11224. }
  11225. /// Get the text directly after `pos`, either the entire line
  11226. /// or the next 100 characters, whichever is shorter.
  11227. textAfterPos(pos) {
  11228. var _a, _b;
  11229. let sim = (_a = this.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;
  11230. if (pos == sim && ((_b = this.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak))
  11231. return "";
  11232. return this.state.sliceDoc(pos, Math.min(pos + 100, sim != null && sim > pos ? sim : 1e9, this.state.doc.lineAt(pos).to));
  11233. }
  11234. /// Find the column for the given position.
  11235. column(pos) {
  11236. var _a;
  11237. let line = this.state.doc.lineAt(pos), text = line.text.slice(0, pos - line.from);
  11238. let result = this.countColumn(text, pos - line.from);
  11239. let override = ((_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation) ? this.options.overrideIndentation(line.from) : -1;
  11240. if (override > -1)
  11241. result += override - this.countColumn(text, text.search(/\S/));
  11242. return result;
  11243. }
  11244. /// find the column position (taking tabs into account) of the given
  11245. /// position in the given string.
  11246. countColumn(line, pos) {
  11247. return countColumn(pos < 0 ? line : line.slice(0, pos), 0, this.state.tabSize);
  11248. }
  11249. /// Find the indentation column of the given document line.
  11250. lineIndent(line) {
  11251. var _a;
  11252. let override = (_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation;
  11253. if (override) {
  11254. let overriden = override(line.from);
  11255. if (overriden > -1)
  11256. return overriden;
  11257. }
  11258. return this.countColumn(line.text, line.text.search(/\S/));
  11259. }
  11260. }
  11261. /// A syntax tree node prop used to associate indentation strategies
  11262. /// with node types. Such a strategy is a function from an indentation
  11263. /// context to a column number or null, where null indicates that no
  11264. /// definitive indentation can be determined.
  11265. const indentNodeProp = new NodeProp();
  11266. // Compute the indentation for a given position from the syntax tree.
  11267. function syntaxIndentation(cx, ast, pos) {
  11268. let tree = ast.resolve(pos);
  11269. // Enter previous nodes that end in empty error terms, which means
  11270. // they were broken off by error recovery, so that indentation
  11271. // works even if the constructs haven't been finished.
  11272. for (let scan = tree, scanPos = pos;;) {
  11273. let last = scan.childBefore(scanPos);
  11274. if (!last)
  11275. break;
  11276. if (last.type.isError && last.from == last.to) {
  11277. tree = scan;
  11278. scanPos = last.from;
  11279. }
  11280. else {
  11281. scan = last;
  11282. scanPos = scan.to + 1;
  11283. }
  11284. }
  11285. for (; tree; tree = tree.parent) {
  11286. let strategy = indentStrategy(tree);
  11287. if (strategy)
  11288. return strategy(new TreeIndentContext(cx, pos, tree));
  11289. }
  11290. return null;
  11291. }
  11292. function ignoreClosed(cx) {
  11293. var _a, _b;
  11294. return cx.pos == ((_a = cx.options) === null || _a === void 0 ? void 0 : _a.simulateBreak) && ((_b = cx.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak);
  11295. }
  11296. function indentStrategy(tree) {
  11297. let strategy = tree.type.prop(indentNodeProp);
  11298. if (strategy)
  11299. return strategy;
  11300. let first = tree.firstChild, close;
  11301. if (first && (close = first.type.prop(NodeProp.closedBy))) {
  11302. let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
  11303. return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
  11304. }
  11305. return tree.parent == null ? topIndent : null;
  11306. }
  11307. function topIndent() { return 0; }
  11308. /// Objects of this type provide context information and helper
  11309. /// methods to indentation functions.
  11310. class TreeIndentContext extends IndentContext {
  11311. /// @internal
  11312. constructor(base,
  11313. /// The position at which indentation is being computed.
  11314. pos,
  11315. /// The syntax tree node to which the indentation strategy
  11316. /// applies.
  11317. node) {
  11318. super(base.state, base.options);
  11319. this.pos = pos;
  11320. this.node = node;
  11321. }
  11322. /// Get the text directly after `this.pos`, either the entire line
  11323. /// or the next 100 characters, whichever is shorter.
  11324. get textAfter() {
  11325. return this.textAfterPos(this.pos);
  11326. }
  11327. /// Get the indentation at the reference line for `this.node`, which
  11328. /// is the line on which it starts, unless there is a node that is
  11329. /// _not_ a parent of this node covering the start of that line. If
  11330. /// so, the line at the start of that node is tried, again skipping
  11331. /// on if it is covered by another such node.
  11332. get baseIndent() {
  11333. let line = this.state.doc.lineAt(this.node.from);
  11334. // Skip line starts that are covered by a sibling (or cousin, etc)
  11335. for (;;) {
  11336. let atBreak = this.node.resolve(line.from);
  11337. while (atBreak.parent && atBreak.parent.from == atBreak.from)
  11338. atBreak = atBreak.parent;
  11339. if (isParent(atBreak, this.node))
  11340. break;
  11341. line = this.state.doc.lineAt(atBreak.from);
  11342. }
  11343. return this.lineIndent(line);
  11344. }
  11345. }
  11346. function isParent(parent, of) {
  11347. for (let cur = of; cur; cur = cur.parent)
  11348. if (parent == cur)
  11349. return true;
  11350. return false;
  11351. }
  11352. // Check whether a delimited node is aligned (meaning there are
  11353. // non-skipped nodes on the same line as the opening delimiter). And
  11354. // if so, return the opening token.
  11355. function bracketedAligned(context) {
  11356. var _a;
  11357. let tree = context.node;
  11358. let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  11359. if (!openToken)
  11360. return null;
  11361. let sim = (_a = context.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;
  11362. let openLine = context.state.doc.lineAt(openToken.from);
  11363. let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  11364. for (let pos = openToken.to;;) {
  11365. let next = tree.childAfter(pos);
  11366. if (!next || next == last)
  11367. return null;
  11368. if (!next.type.isSkipped)
  11369. return next.from < lineEnd ? openToken : null;
  11370. pos = next.to;
  11371. }
  11372. }
  11373. /// An indentation strategy for delimited (usually bracketed) nodes.
  11374. /// Will, by default, indent one unit more than the parent's base
  11375. /// indent unless the line starts with a closing token. When `align`
  11376. /// is true and there are non-skipped nodes on the node's opening
  11377. /// line, the content of the node will be aligned with the end of the
  11378. /// opening node, like this:
  11379. ///
  11380. /// foo(bar,
  11381. /// baz)
  11382. function delimitedIndent({ closing, align = true, units = 1 }) {
  11383. return (context) => delimitedStrategy(context, align, units, closing);
  11384. }
  11385. function delimitedStrategy(context, align, units, closing, closedAt) {
  11386. let after = context.textAfter, space = after.match(/^\s*/)[0].length;
  11387. let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
  11388. let aligned = align ? bracketedAligned(context) : null;
  11389. if (aligned)
  11390. return closed ? context.column(aligned.from) : context.column(aligned.to);
  11391. return context.baseIndent + (closed ? 0 : context.unit * units);
  11392. }
  11393. /// An indentation strategy that aligns a node's content to its base
  11394. /// indentation.
  11395. const flatIndent = (context) => context.baseIndent;
  11396. /// Creates an indentation strategy that, by default, indents
  11397. /// continued lines one unit more than the node's base indentation.
  11398. /// You can provide `except` to prevent indentation of lines that
  11399. /// match a pattern (for example `/^else\b/` in `if`/`else`
  11400. /// constructs), and you can change the amount of units used with the
  11401. /// `units` option.
  11402. function continuedIndent({ except, units = 1 } = {}) {
  11403. return (context) => {
  11404. let matchExcept = except && except.test(context.textAfter);
  11405. return context.baseIndent + (matchExcept ? 0 : units * context.unit);
  11406. };
  11407. }
  11408. const DontIndentBeyond = 200;
  11409. /// Enables reindentation on input. When a language defines an
  11410. /// `indentOnInput` field in its [language
  11411. /// data](#state.EditorState.languageDataAt), which must hold a regular
  11412. /// expression, the line at the cursor will be reindented whenever new
  11413. /// text is typed and the input from the start of the line up to the
  11414. /// cursor matches that regexp.
  11415. ///
  11416. /// To avoid unneccesary reindents, it is recommended to start the
  11417. /// regexp with `^` (usually followed by `\s*`), and end it with `$`.
  11418. /// For example, `/^\s*\}$/` will reindent when a closing brace is
  11419. /// added at the start of a line.
  11420. function indentOnInput() {
  11421. return EditorState.transactionFilter.of(tr => {
  11422. if (!tr.docChanged || tr.annotation(Transaction.userEvent) != "input")
  11423. return tr;
  11424. let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
  11425. if (!rules.length)
  11426. return tr;
  11427. let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
  11428. if (head > line.from + DontIndentBeyond)
  11429. return tr;
  11430. let lineStart = doc.sliceString(line.from, head);
  11431. if (!rules.some(r => r.test(lineStart)))
  11432. return tr;
  11433. let { state } = tr, last = -1, changes = [];
  11434. for (let { head } of state.selection.ranges) {
  11435. let line = state.doc.lineAt(head);
  11436. if (line.from == last)
  11437. continue;
  11438. last = line.from;
  11439. let indent = getIndentation(state, line.from);
  11440. if (indent == null)
  11441. continue;
  11442. let cur = /^\s*/.exec(line.text)[0];
  11443. let norm = indentString(state, indent);
  11444. if (cur != norm)
  11445. changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
  11446. }
  11447. return changes.length ? [tr, { changes }] : tr;
  11448. });
  11449. }
  11450. /// A facet that registers a code folding service. When called with
  11451. /// the extent of a line, such a function should return a foldable
  11452. /// range that starts on that line (but continues beyond it), if one
  11453. /// can be found.
  11454. const foldService = Facet.define();
  11455. /// This node prop is used to associate folding information with
  11456. /// syntax node types. Given a syntax node, it should check whether
  11457. /// that tree is foldable and return the range that can be collapsed
  11458. /// when it is.
  11459. const foldNodeProp = new NodeProp();
  11460. function syntaxFolding(state, start, end) {
  11461. let tree = syntaxTree(state);
  11462. if (tree.length == 0)
  11463. return null;
  11464. let inner = tree.resolve(end);
  11465. let found = null;
  11466. for (let cur = inner; cur; cur = cur.parent) {
  11467. if (cur.to <= end || cur.from > end)
  11468. continue;
  11469. if (found && cur.from < start)
  11470. break;
  11471. let prop = cur.type.prop(foldNodeProp);
  11472. if (prop) {
  11473. let value = prop(cur, state);
  11474. if (value && value.from <= end && value.from >= start && value.to > end)
  11475. found = value;
  11476. }
  11477. }
  11478. return found;
  11479. }
  11480. /// Check whether the given line is foldable. First asks any fold
  11481. /// services registered through
  11482. /// [`foldService`](#language.foldService), and if none of them return
  11483. /// a result, tries to query the [fold node
  11484. /// prop](#language.foldNodeProp) of syntax nodes that cover the end
  11485. /// of the line.
  11486. function foldable(state, lineStart, lineEnd) {
  11487. for (let service of state.facet(foldService)) {
  11488. let result = service(state, lineStart, lineEnd);
  11489. if (result)
  11490. return result;
  11491. }
  11492. return syntaxFolding(state, lineStart, lineEnd);
  11493. }
  11494. /// A gutter marker represents a bit of information attached to a line
  11495. /// in a specific gutter. Your own custom markers have to extend this
  11496. /// class.
  11497. class GutterMarker extends RangeValue {
  11498. /// @internal
  11499. compare(other) {
  11500. return this == other || this.constructor == other.constructor && this.eq(other);
  11501. }
  11502. /// Render the DOM node for this marker, if any.
  11503. toDOM(_view) { return null; }
  11504. /// Create a range that places this marker at the given position.
  11505. at(pos) { return this.range(pos); }
  11506. }
  11507. GutterMarker.prototype.elementClass = "";
  11508. GutterMarker.prototype.mapMode = MapMode.TrackBefore;
  11509. const defaults = {
  11510. style: "",
  11511. renderEmptyElements: false,
  11512. elementStyle: "",
  11513. markers: () => RangeSet.empty,
  11514. lineMarker: () => null,
  11515. initialSpacer: null,
  11516. updateSpacer: null,
  11517. domEventHandlers: {}
  11518. };
  11519. const activeGutters = Facet.define();
  11520. /// Define an editor gutter. The order in which the gutters appear is
  11521. /// determined by their extension priority.
  11522. function gutter(config) {
  11523. return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults), config))];
  11524. }
  11525. const baseTheme$1 = EditorView.baseTheme({
  11526. $gutters: {
  11527. display: "flex",
  11528. height: "100%",
  11529. boxSizing: "border-box",
  11530. left: 0
  11531. },
  11532. "$$light $gutters": {
  11533. backgroundColor: "#f5f5f5",
  11534. color: "#999",
  11535. borderRight: "1px solid #ddd"
  11536. },
  11537. "$$dark $gutters": {
  11538. backgroundColor: "#333338",
  11539. color: "#ccc"
  11540. },
  11541. $gutter: {
  11542. display: "flex !important",
  11543. flexDirection: "column",
  11544. flexShrink: 0,
  11545. boxSizing: "border-box",
  11546. height: "100%",
  11547. overflow: "hidden"
  11548. },
  11549. $gutterElement: {
  11550. boxSizing: "border-box"
  11551. },
  11552. "$gutterElement.lineNumber": {
  11553. padding: "0 3px 0 5px",
  11554. minWidth: "20px",
  11555. textAlign: "right",
  11556. whiteSpace: "nowrap"
  11557. }
  11558. });
  11559. const unfixGutters = Facet.define({
  11560. combine: values => values.some(x => x)
  11561. });
  11562. /// The gutter-drawing plugin is automatically enabled when you add a
  11563. /// gutter, but you can use this function to explicitly configure it.
  11564. ///
  11565. /// Unless `fixed` is explicitly set to `false`, the gutters are
  11566. /// fixed, meaning they don't scroll along with the content
  11567. /// horizontally (except on Internet Explorer, which doesn't support
  11568. /// CSS [`position:
  11569. /// sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
  11570. function gutters(config) {
  11571. let result = [
  11572. gutterView,
  11573. baseTheme$1
  11574. ];
  11575. if (config && config.fixed === false)
  11576. result.push(unfixGutters.of(true));
  11577. return result;
  11578. }
  11579. const gutterView = ViewPlugin.fromClass(class {
  11580. constructor(view) {
  11581. this.view = view;
  11582. this.dom = document.createElement("div");
  11583. this.dom.className = themeClass("gutters");
  11584. this.dom.setAttribute("aria-hidden", "true");
  11585. this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
  11586. for (let gutter of this.gutters)
  11587. this.dom.appendChild(gutter.dom);
  11588. this.fixed = !view.state.facet(unfixGutters);
  11589. if (this.fixed) {
  11590. // FIXME IE11 fallback, which doesn't support position: sticky,
  11591. // by using position: relative + event handlers that realign the
  11592. // gutter (or just force fixed=false on IE11?)
  11593. this.dom.style.position = "sticky";
  11594. }
  11595. view.scrollDOM.insertBefore(this.dom, view.contentDOM);
  11596. }
  11597. update(update) {
  11598. if (!this.updateGutters(update))
  11599. return;
  11600. let contexts = this.gutters.map(gutter => new UpdateContext(gutter, this.view.viewport));
  11601. this.view.viewportLines(line => {
  11602. let text;
  11603. if (Array.isArray(line.type)) {
  11604. for (let b of line.type)
  11605. if (b.type == BlockType.Text) {
  11606. text = b;
  11607. break;
  11608. }
  11609. }
  11610. else {
  11611. text = line.type == BlockType.Text ? line : undefined;
  11612. }
  11613. if (!text)
  11614. return;
  11615. for (let cx of contexts)
  11616. cx.line(this.view, text);
  11617. }, 0);
  11618. for (let cx of contexts)
  11619. cx.finish();
  11620. this.dom.style.minHeight = this.view.contentHeight + "px";
  11621. if (update.state.facet(unfixGutters) != !this.fixed) {
  11622. this.fixed = !this.fixed;
  11623. this.dom.style.position = this.fixed ? "sticky" : "";
  11624. }
  11625. }
  11626. updateGutters(update) {
  11627. let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters);
  11628. let change = update.docChanged || update.heightChanged || update.viewportChanged;
  11629. if (prev == cur) {
  11630. for (let gutter of this.gutters)
  11631. if (gutter.update(update))
  11632. change = true;
  11633. }
  11634. else {
  11635. change = true;
  11636. let gutters = [];
  11637. for (let conf of cur) {
  11638. let known = prev.indexOf(conf);
  11639. if (known < 0) {
  11640. gutters.push(new SingleGutterView(this.view, conf));
  11641. }
  11642. else {
  11643. this.gutters[known].update(update);
  11644. gutters.push(this.gutters[known]);
  11645. }
  11646. }
  11647. for (let g of this.gutters)
  11648. g.dom.remove();
  11649. for (let g of gutters)
  11650. this.dom.appendChild(g.dom);
  11651. this.gutters = gutters;
  11652. }
  11653. return change;
  11654. }
  11655. destroy() {
  11656. this.dom.remove();
  11657. }
  11658. }, {
  11659. provide: PluginField.scrollMargins.from(value => {
  11660. if (value.gutters.length == 0 || !value.fixed)
  11661. return null;
  11662. return value.view.textDirection == Direction.LTR ? { left: value.dom.offsetWidth } : { right: value.dom.offsetWidth };
  11663. })
  11664. });
  11665. function asArray$1(val) { return (Array.isArray(val) ? val : [val]); }
  11666. class UpdateContext {
  11667. constructor(gutter, viewport) {
  11668. this.gutter = gutter;
  11669. this.localMarkers = [];
  11670. this.i = 0;
  11671. this.height = 0;
  11672. this.cursor = RangeSet.iter(gutter.markers, viewport.from);
  11673. }
  11674. line(view, line) {
  11675. if (this.localMarkers.length)
  11676. this.localMarkers = [];
  11677. while (this.cursor.value && this.cursor.from <= line.from) {
  11678. if (this.cursor.from == line.from)
  11679. this.localMarkers.push(this.cursor.value);
  11680. this.cursor.next();
  11681. }
  11682. let forLine = this.gutter.config.lineMarker(view, line, this.localMarkers);
  11683. if (forLine)
  11684. this.localMarkers.unshift(forLine);
  11685. let gutter = this.gutter;
  11686. if (this.localMarkers.length == 0 && !gutter.config.renderEmptyElements)
  11687. return;
  11688. let above = line.top - this.height;
  11689. if (this.i == gutter.elements.length) {
  11690. let newElt = new GutterElement(view, line.height, above, this.localMarkers, gutter.elementClass);
  11691. gutter.elements.push(newElt);
  11692. gutter.dom.appendChild(newElt.dom);
  11693. }
  11694. else {
  11695. let markers = this.localMarkers, elt = gutter.elements[this.i];
  11696. if (sameMarkers(markers, elt.markers)) {
  11697. markers = elt.markers;
  11698. this.localMarkers.length = 0;
  11699. }
  11700. elt.update(view, line.height, above, markers, gutter.elementClass);
  11701. }
  11702. this.height = line.bottom;
  11703. this.i++;
  11704. }
  11705. finish() {
  11706. let gutter = this.gutter;
  11707. while (gutter.elements.length > this.i)
  11708. gutter.dom.removeChild(gutter.elements.pop().dom);
  11709. }
  11710. }
  11711. class SingleGutterView {
  11712. constructor(view, config) {
  11713. this.view = view;
  11714. this.config = config;
  11715. this.elements = [];
  11716. this.spacer = null;
  11717. this.dom = document.createElement("div");
  11718. this.dom.className = themeClass("gutter" + (this.config.style ? "." + this.config.style : ""));
  11719. this.elementClass = themeClass("gutterElement" + (this.config.style ? "." + this.config.style : ""));
  11720. for (let prop in config.domEventHandlers) {
  11721. this.dom.addEventListener(prop, (event) => {
  11722. let line = view.visualLineAtHeight(event.clientY, view.contentDOM.getBoundingClientRect().top);
  11723. if (config.domEventHandlers[prop](view, line, event))
  11724. event.preventDefault();
  11725. });
  11726. }
  11727. this.markers = asArray$1(config.markers(view));
  11728. if (config.initialSpacer) {
  11729. this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)], this.elementClass);
  11730. this.dom.appendChild(this.spacer.dom);
  11731. this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
  11732. }
  11733. }
  11734. update(update) {
  11735. let prevMarkers = this.markers;
  11736. this.markers = asArray$1(this.config.markers(update.view));
  11737. if (this.spacer && this.config.updateSpacer) {
  11738. let updated = this.config.updateSpacer(this.spacer.markers[0], update);
  11739. if (updated != this.spacer.markers[0])
  11740. this.spacer.update(update.view, 0, 0, [updated], this.elementClass);
  11741. }
  11742. return this.markers != prevMarkers;
  11743. }
  11744. }
  11745. class GutterElement {
  11746. constructor(view, height, above, markers, eltClass) {
  11747. this.height = -1;
  11748. this.above = 0;
  11749. this.dom = document.createElement("div");
  11750. this.update(view, height, above, markers, eltClass);
  11751. }
  11752. update(view, height, above, markers, cssClass) {
  11753. if (this.height != height)
  11754. this.dom.style.height = (this.height = height) + "px";
  11755. if (this.above != above)
  11756. this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
  11757. if (this.markers != markers) {
  11758. this.markers = markers;
  11759. for (let ch; ch = this.dom.lastChild;)
  11760. ch.remove();
  11761. let cls = cssClass;
  11762. for (let m of markers) {
  11763. let dom = m.toDOM(view);
  11764. if (dom)
  11765. this.dom.appendChild(dom);
  11766. let c = m.elementClass;
  11767. if (c)
  11768. cls += " " + c;
  11769. }
  11770. this.dom.className = cls;
  11771. }
  11772. }
  11773. }
  11774. function sameMarkers(a, b) {
  11775. if (a.length != b.length)
  11776. return false;
  11777. for (let i = 0; i < a.length; i++)
  11778. if (!a[i].compare(b[i]))
  11779. return false;
  11780. return true;
  11781. }
  11782. /// Facet used to provide markers to the line number gutter.
  11783. const lineNumberMarkers = Facet.define();
  11784. const lineNumberConfig = Facet.define({
  11785. combine(values) {
  11786. return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, {
  11787. domEventHandlers(a, b) {
  11788. let result = Object.assign({}, a);
  11789. for (let event in b) {
  11790. let exists = result[event], add = b[event];
  11791. result[event] = exists ? (view, line, event) => exists(view, line, event) || add(view, line, event) : add;
  11792. }
  11793. return result;
  11794. }
  11795. });
  11796. }
  11797. });
  11798. class NumberMarker extends GutterMarker {
  11799. constructor(number) {
  11800. super();
  11801. this.number = number;
  11802. }
  11803. eq(other) { return this.number == other.number; }
  11804. toDOM(view) {
  11805. let config = view.state.facet(lineNumberConfig);
  11806. return document.createTextNode(config.formatNumber(this.number));
  11807. }
  11808. }
  11809. const lineNumberGutter = gutter({
  11810. style: "lineNumber",
  11811. markers(view) { return view.state.facet(lineNumberMarkers); },
  11812. lineMarker(view, line, others) {
  11813. if (others.length)
  11814. return null;
  11815. return new NumberMarker(view.state.doc.lineAt(line.from).number);
  11816. },
  11817. initialSpacer(view) {
  11818. return new NumberMarker(maxLineNumber(view.state.doc.lines));
  11819. },
  11820. updateSpacer(spacer, update) {
  11821. let max = maxLineNumber(update.view.state.doc.lines);
  11822. return max == spacer.number ? spacer : new NumberMarker(max);
  11823. }
  11824. });
  11825. /// Create a line number gutter extension.
  11826. function lineNumbers(config = {}) {
  11827. return [
  11828. lineNumberConfig.of(config),
  11829. lineNumberGutter
  11830. ];
  11831. }
  11832. function maxLineNumber(lines) {
  11833. let last = 9;
  11834. while (last < lines)
  11835. last = last * 10 + 9;
  11836. return last;
  11837. }
  11838. function mapRange(range, mapping) {
  11839. let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
  11840. return from >= to ? undefined : { from, to };
  11841. }
  11842. const foldEffect = StateEffect.define({ map: mapRange });
  11843. const unfoldEffect = StateEffect.define({ map: mapRange });
  11844. function selectedLines(view) {
  11845. let lines = [];
  11846. for (let { head } of view.state.selection.ranges) {
  11847. if (lines.some(l => l.from <= head && l.to >= head))
  11848. continue;
  11849. lines.push(view.visualLineAt(head));
  11850. }
  11851. return lines;
  11852. }
  11853. const foldState = StateField.define({
  11854. create() {
  11855. return Decoration.none;
  11856. },
  11857. update(folded, tr) {
  11858. folded = folded.map(tr.changes);
  11859. for (let e of tr.effects) {
  11860. if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to))
  11861. folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] });
  11862. else if (e.is(unfoldEffect)) {
  11863. folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
  11864. filterFrom: e.value.from, filterTo: e.value.to });
  11865. }
  11866. }
  11867. // Clear folded ranges that cover the selection head
  11868. if (tr.selection) {
  11869. let onSelection = false, { head } = tr.selection.main;
  11870. folded.between(head, head, (a, b) => { if (a < head && b > head)
  11871. onSelection = true; });
  11872. if (onSelection)
  11873. folded = folded.update({
  11874. filterFrom: head,
  11875. filterTo: head,
  11876. filter: (a, b) => b <= head || a >= head
  11877. });
  11878. }
  11879. return folded;
  11880. },
  11881. provide: f => EditorView.decorations.compute([f], s => s.field(f))
  11882. });
  11883. function foldInside(state, from, to) {
  11884. var _a;
  11885. let found = null;
  11886. (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
  11887. if (!found || found.from > from)
  11888. found = ({ from, to });
  11889. });
  11890. return found;
  11891. }
  11892. function foldExists(folded, from, to) {
  11893. let found = false;
  11894. folded.between(from, from, (a, b) => { if (a == from && b == to)
  11895. found = true; });
  11896. return found;
  11897. }
  11898. function maybeEnable(state) {
  11899. return state.field(foldState, false) ? undefined : { append: codeFolding() };
  11900. }
  11901. /// Fold the lines that are selected, if possible.
  11902. const foldCode = view => {
  11903. for (let line of selectedLines(view)) {
  11904. let range = foldable(view.state, line.from, line.to);
  11905. if (range) {
  11906. view.dispatch({ effects: foldEffect.of(range),
  11907. reconfigure: maybeEnable(view.state) });
  11908. return true;
  11909. }
  11910. }
  11911. return false;
  11912. };
  11913. /// Unfold folded ranges on selected lines.
  11914. const unfoldCode = view => {
  11915. if (!view.state.field(foldState, false))
  11916. return false;
  11917. let effects = [];
  11918. for (let line of selectedLines(view)) {
  11919. let folded = foldInside(view.state, line.from, line.to);
  11920. if (folded)
  11921. effects.push(unfoldEffect.of(folded));
  11922. }
  11923. if (effects.length)
  11924. view.dispatch({ effects });
  11925. return effects.length > 0;
  11926. };
  11927. /// Fold all top-level foldable ranges.
  11928. const foldAll = view => {
  11929. let { state } = view, effects = [];
  11930. for (let pos = 0; pos < state.doc.length;) {
  11931. let line = view.visualLineAt(pos), range = foldable(state, line.from, line.to);
  11932. if (range)
  11933. effects.push(foldEffect.of(range));
  11934. pos = (range ? view.visualLineAt(range.to) : line).to + 1;
  11935. }
  11936. if (effects.length)
  11937. view.dispatch({ effects, reconfigure: maybeEnable(view.state) });
  11938. return !!effects.length;
  11939. };
  11940. /// Unfold all folded code.
  11941. const unfoldAll = view => {
  11942. let field = view.state.field(foldState, false);
  11943. if (!field || !field.size)
  11944. return false;
  11945. let effects = [];
  11946. field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
  11947. view.dispatch({ effects });
  11948. return true;
  11949. };
  11950. /// Default fold-related key bindings.
  11951. ///
  11952. /// - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](#fold.foldCode).
  11953. /// - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](#fold.unfoldCode).
  11954. /// - Ctrl-Alt-[: [`foldAll`](#fold.foldAll).
  11955. /// - Ctrl-Alt-]: [`unfoldAll`](#fold.unfoldAll).
  11956. const foldKeymap = [
  11957. { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
  11958. { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
  11959. { key: "Ctrl-Alt-[", run: foldAll },
  11960. { key: "Ctrl-Alt-]", run: unfoldAll }
  11961. ];
  11962. const defaultConfig = {
  11963. placeholderDOM: null,
  11964. placeholderText: "…"
  11965. };
  11966. const foldConfig = Facet.define({
  11967. combine(values) { return combineConfig(values, defaultConfig); }
  11968. });
  11969. /// Create an extension that configures code folding.
  11970. function codeFolding(config) {
  11971. let result = [foldState, baseTheme$2];
  11972. if (config)
  11973. result.push(foldConfig.of(config));
  11974. return result;
  11975. }
  11976. const foldWidget = Decoration.replace({ widget: new class extends WidgetType {
  11977. ignoreEvents() { return false; }
  11978. toDOM(view) {
  11979. let { state } = view, conf = state.facet(foldConfig);
  11980. if (conf.placeholderDOM)
  11981. return conf.placeholderDOM();
  11982. let element = document.createElement("span");
  11983. element.textContent = conf.placeholderText;
  11984. element.setAttribute("aria-label", state.phrase("folded code"));
  11985. element.title = state.phrase("unfold");
  11986. element.className = themeClass("foldPlaceholder");
  11987. element.onclick = event => {
  11988. let line = view.visualLineAt(view.posAtDOM(event.target));
  11989. let folded = foldInside(view.state, line.from, line.to);
  11990. if (folded)
  11991. view.dispatch({ effects: unfoldEffect.of(folded) });
  11992. event.preventDefault();
  11993. };
  11994. return element;
  11995. }
  11996. } });
  11997. const foldGutterDefaults = {
  11998. openText: "⌄",
  11999. closedText: "›"
  12000. };
  12001. class FoldMarker extends GutterMarker {
  12002. constructor(config, open) {
  12003. super();
  12004. this.config = config;
  12005. this.open = open;
  12006. }
  12007. eq(other) { return this.config == other.config && this.open == other.open; }
  12008. toDOM(view) {
  12009. let span = document.createElement("span");
  12010. span.textContent = this.open ? this.config.openText : this.config.closedText;
  12011. span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
  12012. return span;
  12013. }
  12014. }
  12015. /// Create an extension that registers a fold gutter, which shows a
  12016. /// fold status indicator before foldable lines (which can be clicked
  12017. /// to fold or unfold the line).
  12018. function foldGutter(config = {}) {
  12019. let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
  12020. let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
  12021. let markers = ViewPlugin.fromClass(class {
  12022. constructor(view) {
  12023. this.from = view.viewport.from;
  12024. this.markers = RangeSet.of(this.buildMarkers(view));
  12025. }
  12026. update(update) {
  12027. let firstChange = -1;
  12028. update.changes.iterChangedRanges(from => { if (firstChange < 0)
  12029. firstChange = from; });
  12030. let foldChange = update.startState.field(foldState, false) != update.state.field(foldState, false);
  12031. if (!foldChange && update.docChanged && update.view.viewport.from == this.from && firstChange > this.from) {
  12032. let start = update.view.visualLineAt(firstChange).from;
  12033. this.markers = this.markers.update({
  12034. filter: () => false,
  12035. filterFrom: start,
  12036. add: this.buildMarkers(update.view, start)
  12037. });
  12038. }
  12039. else if (foldChange || update.docChanged || update.viewportChanged) {
  12040. this.from = update.view.viewport.from;
  12041. this.markers = RangeSet.of(this.buildMarkers(update.view));
  12042. }
  12043. }
  12044. buildMarkers(view, from = 0) {
  12045. let ranges = [];
  12046. view.viewportLines(line => {
  12047. if (line.from >= from) {
  12048. let mark = foldInside(view.state, line.from, line.to) ? canUnfold
  12049. : foldable(view.state, line.from, line.to) ? canFold : null;
  12050. if (mark)
  12051. ranges.push(mark.range(line.from));
  12052. }
  12053. });
  12054. return ranges;
  12055. }
  12056. });
  12057. return [
  12058. markers,
  12059. gutter({
  12060. style: "foldGutter",
  12061. markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || RangeSet.empty; },
  12062. initialSpacer() {
  12063. return new FoldMarker(fullConfig, false);
  12064. },
  12065. domEventHandlers: {
  12066. click: (view, line) => {
  12067. let folded = foldInside(view.state, line.from, line.to);
  12068. if (folded) {
  12069. view.dispatch({ effects: unfoldEffect.of(folded) });
  12070. return true;
  12071. }
  12072. let range = foldable(view.state, line.from, line.to);
  12073. if (range) {
  12074. view.dispatch({ effects: foldEffect.of(range) });
  12075. return true;
  12076. }
  12077. return false;
  12078. }
  12079. }
  12080. }),
  12081. codeFolding()
  12082. ];
  12083. }
  12084. const baseTheme$2 = EditorView.baseTheme({
  12085. $foldPlaceholder: {
  12086. backgroundColor: "#eee",
  12087. border: "1px solid #ddd",
  12088. color: "#888",
  12089. borderRadius: ".2em",
  12090. margin: "0 1px",
  12091. padding: "0 1px",
  12092. cursor: "pointer"
  12093. },
  12094. "$gutterElement.foldGutter": {
  12095. padding: "0 1px",
  12096. cursor: "pointer"
  12097. }
  12098. });
  12099. const baseTheme$3 = EditorView.baseTheme({
  12100. $matchingBracket: { color: "#0b0" },
  12101. $nonmatchingBracket: { color: "#a22" }
  12102. });
  12103. const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
  12104. const bracketMatchingConfig = Facet.define({
  12105. combine(configs) {
  12106. return combineConfig(configs, {
  12107. afterCursor: true,
  12108. brackets: DefaultBrackets,
  12109. maxScanDistance: DefaultScanDist
  12110. });
  12111. }
  12112. });
  12113. const matchingMark = Decoration.mark({ class: themeClass("matchingBracket") }), nonmatchingMark = Decoration.mark({ class: themeClass("nonmatchingBracket") });
  12114. const bracketMatchingState = StateField.define({
  12115. create() { return Decoration.none; },
  12116. update(deco, tr) {
  12117. if (!tr.docChanged && !tr.selection)
  12118. return deco;
  12119. let decorations = [];
  12120. let config = tr.state.facet(bracketMatchingConfig);
  12121. for (let range of tr.state.selection.ranges) {
  12122. if (!range.empty)
  12123. continue;
  12124. let match = matchBrackets(tr.state, range.head, -1, config)
  12125. || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
  12126. || (config.afterCursor &&
  12127. (matchBrackets(tr.state, range.head, 1, config) ||
  12128. (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
  12129. if (!match)
  12130. continue;
  12131. let mark = match.matched ? matchingMark : nonmatchingMark;
  12132. decorations.push(mark.range(match.start.from, match.start.to));
  12133. if (match.end)
  12134. decorations.push(mark.range(match.end.from, match.end.to));
  12135. }
  12136. return Decoration.set(decorations, true);
  12137. },
  12138. provide: f => EditorView.decorations.from(f)
  12139. });
  12140. const bracketMatchingUnique = [
  12141. bracketMatchingState,
  12142. baseTheme$3
  12143. ];
  12144. /// Create an extension that enables bracket matching. Whenever the
  12145. /// cursor is next to a bracket, that bracket and the one it matches
  12146. /// are highlighted. Or, when no matching bracket is found, another
  12147. /// highlighting style is used to indicate this.
  12148. function bracketMatching(config = {}) {
  12149. return [bracketMatchingConfig.of(config), bracketMatchingUnique];
  12150. }
  12151. function matchingNodes(node, dir, brackets) {
  12152. let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
  12153. if (byProp)
  12154. return byProp;
  12155. if (node.name.length == 1) {
  12156. let index = brackets.indexOf(node.name);
  12157. if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
  12158. return [brackets[index + dir]];
  12159. }
  12160. return null;
  12161. }
  12162. /// Find the matching bracket for the token at `pos`, scanning
  12163. /// direction `dir`. Only the `brackets` and `maxScanDistance`
  12164. /// properties are used from `config`, if given. Returns null if no
  12165. /// bracket was found at `pos`, or a match result otherwise.
  12166. function matchBrackets(state, pos, dir, config = {}) {
  12167. let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
  12168. let tree = syntaxTree(state), sub = tree.resolve(pos, dir), matches;
  12169. if (matches = matchingNodes(sub.type, dir, brackets))
  12170. return matchMarkedBrackets(state, pos, dir, sub, matches, brackets);
  12171. else
  12172. return matchPlainBrackets(state, pos, dir, tree, sub.type, maxScanDistance, brackets);
  12173. }
  12174. function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) {
  12175. let parent = token.parent, firstToken = { from: token.from, to: token.to };
  12176. let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor;
  12177. if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
  12178. do {
  12179. if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
  12180. if (depth == 0 && matching.indexOf(cursor.type.name) > -1) {
  12181. return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true };
  12182. }
  12183. else if (matchingNodes(cursor.type, dir, brackets)) {
  12184. depth++;
  12185. }
  12186. else if (matchingNodes(cursor.type, -dir, brackets)) {
  12187. depth--;
  12188. if (depth == 0)
  12189. return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: false };
  12190. }
  12191. }
  12192. } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
  12193. return { start: firstToken, matched: false };
  12194. }
  12195. function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
  12196. let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
  12197. let bracket = brackets.indexOf(startCh);
  12198. if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
  12199. return null;
  12200. let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
  12201. let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
  12202. for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
  12203. let text = iter.value;
  12204. if (dir < 0)
  12205. distance += text.length;
  12206. let basePos = pos + distance * dir;
  12207. for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
  12208. let found = brackets.indexOf(text[pos]);
  12209. if (found < 0 || tree.resolve(basePos + pos, 1).type != tokenType)
  12210. continue;
  12211. if ((found % 2 == 0) == (dir > 0)) {
  12212. depth++;
  12213. }
  12214. else if (depth == 1) { // Closing
  12215. return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
  12216. }
  12217. else {
  12218. depth--;
  12219. }
  12220. }
  12221. if (dir > 0)
  12222. distance += text.length;
  12223. }
  12224. return iter.done ? { start: startToken, matched: false } : null;
  12225. }
  12226. function updateSel(sel, by) {
  12227. return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
  12228. }
  12229. function setSel(state, selection) {
  12230. return state.update({ selection, scrollIntoView: true, annotations: Transaction.userEvent.of("keyboardselection") });
  12231. }
  12232. function moveSel({ state, dispatch }, how) {
  12233. let selection = updateSel(state.selection, how);
  12234. if (selection.eq(state.selection))
  12235. return false;
  12236. dispatch(setSel(state, selection));
  12237. return true;
  12238. }
  12239. function rangeEnd(range, forward) {
  12240. return EditorSelection.cursor(forward ? range.to : range.from);
  12241. }
  12242. function cursorByChar(view, forward) {
  12243. return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
  12244. }
  12245. /// Move the selection one character to the left (which is backward in
  12246. /// left-to-right text, forward in right-to-left text).
  12247. const cursorCharLeft = view => cursorByChar(view, view.textDirection != Direction.LTR);
  12248. /// Move the selection one character to the right.
  12249. const cursorCharRight = view => cursorByChar(view, view.textDirection == Direction.LTR);
  12250. function cursorByGroup(view, forward) {
  12251. return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
  12252. }
  12253. /// Move the selection across one group of word or non-word (but also
  12254. /// non-space) characters.
  12255. const cursorGroupLeft = view => cursorByGroup(view, view.textDirection != Direction.LTR);
  12256. /// Move the selection one group to the right.
  12257. const cursorGroupRight = view => cursorByGroup(view, view.textDirection == Direction.LTR);
  12258. /// Move the selection one group forward.
  12259. const cursorGroupForward = view => cursorByGroup(view, true);
  12260. /// Move the selection one group backward.
  12261. const cursorGroupBackward = view => cursorByGroup(view, false);
  12262. function interestingNode(state, node, bracketProp) {
  12263. if (node.type.prop(bracketProp))
  12264. return true;
  12265. let len = node.to - node.from;
  12266. return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild;
  12267. }
  12268. function moveBySyntax(state, start, forward) {
  12269. let pos = syntaxTree(state).resolve(start.head);
  12270. let bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy;
  12271. // Scan forward through child nodes to see if there's an interesting
  12272. // node ahead.
  12273. for (let at = start.head;;) {
  12274. let next = forward ? pos.childAfter(at) : pos.childBefore(at);
  12275. if (!next)
  12276. break;
  12277. if (interestingNode(state, next, bracketProp))
  12278. pos = next;
  12279. else
  12280. at = forward ? next.to : next.from;
  12281. }
  12282. let bracket = pos.type.prop(bracketProp), match, newPos;
  12283. if (bracket && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched)
  12284. newPos = forward ? match.end.to : match.end.from;
  12285. else
  12286. newPos = forward ? pos.to : pos.from;
  12287. return EditorSelection.cursor(newPos, forward ? -1 : 1);
  12288. }
  12289. /// Move the cursor over the next syntactic element to the left.
  12290. const cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR));
  12291. /// Move the cursor over the next syntactic element to the right.
  12292. const cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR));
  12293. function cursorByLine(view, forward) {
  12294. return moveSel(view, range => range.empty ? view.moveVertically(range, forward) : rangeEnd(range, forward));
  12295. }
  12296. /// Move the selection one line up.
  12297. const cursorLineUp = view => cursorByLine(view, false);
  12298. /// Move the selection one line down.
  12299. const cursorLineDown = view => cursorByLine(view, true);
  12300. function cursorByPage(view, forward) {
  12301. return moveSel(view, range => range.empty ? view.moveVertically(range, forward, view.dom.clientHeight) : rangeEnd(range, forward));
  12302. }
  12303. /// Move the selection one page up.
  12304. const cursorPageUp = view => cursorByPage(view, false);
  12305. /// Move the selection one page down.
  12306. const cursorPageDown = view => cursorByPage(view, true);
  12307. function moveByLineBoundary(view, start, forward) {
  12308. let line = view.visualLineAt(start.head), moved = view.moveToLineBoundary(start, forward);
  12309. if (moved.head == start.head && moved.head != (forward ? line.to : line.from))
  12310. moved = view.moveToLineBoundary(start, forward, false);
  12311. if (!forward && moved.head == line.from && line.length) {
  12312. let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
  12313. if (space && start.head != line.from + space)
  12314. moved = EditorSelection.cursor(line.from + space);
  12315. }
  12316. return moved;
  12317. }
  12318. /// Move the selection to the next line wrap point, or to the end of
  12319. /// the line if there isn't one left on this line.
  12320. const cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
  12321. /// Move the selection to previous line wrap point, or failing that to
  12322. /// the start of the line. If the line is indented, and the cursor
  12323. /// isn't already at the end of the indentation, this will move to the
  12324. /// end of the indentation instead of the start of the line.
  12325. const cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
  12326. /// Move the selection to the start of the line.
  12327. const cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.visualLineAt(range.head).from, 1));
  12328. /// Move the selection to the end of the line.
  12329. const cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.visualLineAt(range.head).to, -1));
  12330. function toMatchingBracket(state, dispatch, extend) {
  12331. let found = false, selection = updateSel(state.selection, range => {
  12332. let matching = matchBrackets(state, range.head, -1)
  12333. || matchBrackets(state, range.head, 1)
  12334. || (range.head > 0 && matchBrackets(state, range.head - 1, 1))
  12335. || (range.head < state.doc.length && matchBrackets(state, range.head + 1, -1));
  12336. if (!matching || !matching.end)
  12337. return range;
  12338. found = true;
  12339. let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
  12340. return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);
  12341. });
  12342. if (!found)
  12343. return false;
  12344. dispatch(setSel(state, selection));
  12345. return true;
  12346. }
  12347. /// Move the selection to the bracket matching the one it is currently
  12348. /// on, if any.
  12349. const cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, false);
  12350. function extendSel(view, how) {
  12351. let selection = updateSel(view.state.selection, range => {
  12352. let head = how(range);
  12353. return EditorSelection.range(range.anchor, head.head, head.goalColumn);
  12354. });
  12355. if (selection.eq(view.state.selection))
  12356. return false;
  12357. view.dispatch(setSel(view.state, selection));
  12358. return true;
  12359. }
  12360. function selectByChar(view, forward) {
  12361. return extendSel(view, range => view.moveByChar(range, forward));
  12362. }
  12363. /// Move the selection head one character to the left, while leaving
  12364. /// the anchor in place.
  12365. const selectCharLeft = view => selectByChar(view, view.textDirection != Direction.LTR);
  12366. /// Move the selection head one character to the right.
  12367. const selectCharRight = view => selectByChar(view, view.textDirection == Direction.LTR);
  12368. function selectByGroup(view, forward) {
  12369. return extendSel(view, range => view.moveByGroup(range, forward));
  12370. }
  12371. /// Move the selection head one [group](#commands.cursorGroupLeft) to
  12372. /// the left.
  12373. const selectGroupLeft = view => selectByGroup(view, view.textDirection != Direction.LTR);
  12374. /// Move the selection head one group to the right.
  12375. const selectGroupRight = view => selectByGroup(view, view.textDirection == Direction.LTR);
  12376. /// Move the selection head one group forward.
  12377. const selectGroupForward = view => selectByGroup(view, true);
  12378. /// Move the selection head one group backward.
  12379. const selectGroupBackward = view => selectByGroup(view, false);
  12380. /// Move the selection head over the next syntactic element to the left.
  12381. const selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection != Direction.LTR));
  12382. /// Move the selection head over the next syntactic element to the right.
  12383. const selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, view.textDirection == Direction.LTR));
  12384. function selectByLine(view, forward) {
  12385. return extendSel(view, range => view.moveVertically(range, forward));
  12386. }
  12387. /// Move the selection head one line up.
  12388. const selectLineUp = view => selectByLine(view, false);
  12389. /// Move the selection head one line down.
  12390. const selectLineDown = view => selectByLine(view, true);
  12391. function selectByPage(view, forward) {
  12392. return extendSel(view, range => view.moveVertically(range, forward, view.dom.clientHeight));
  12393. }
  12394. /// Move the selection head one page up.
  12395. const selectPageUp = view => selectByPage(view, false);
  12396. /// Move the selection head one page down.
  12397. const selectPageDown = view => selectByPage(view, true);
  12398. /// Move the selection head to the next line boundary.
  12399. const selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
  12400. /// Move the selection head to the previous line boundary.
  12401. const selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
  12402. /// Move the selection head to the start of the line.
  12403. const selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.visualLineAt(range.head).from));
  12404. /// Move the selection head to the end of the line.
  12405. const selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.visualLineAt(range.head).to));
  12406. /// Move the selection to the start of the document.
  12407. const cursorDocStart = ({ state, dispatch }) => {
  12408. dispatch(setSel(state, { anchor: 0 }));
  12409. return true;
  12410. };
  12411. /// Move the selection to the end of the document.
  12412. const cursorDocEnd = ({ state, dispatch }) => {
  12413. dispatch(setSel(state, { anchor: state.doc.length }));
  12414. return true;
  12415. };
  12416. /// Move the selection head to the start of the document.
  12417. const selectDocStart = ({ state, dispatch }) => {
  12418. dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 }));
  12419. return true;
  12420. };
  12421. /// Move the selection head to the end of the document.
  12422. const selectDocEnd = ({ state, dispatch }) => {
  12423. dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length }));
  12424. return true;
  12425. };
  12426. /// Select the entire document.
  12427. const selectAll = ({ state, dispatch }) => {
  12428. dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, annotations: Transaction.userEvent.of("keyboardselection") }));
  12429. return true;
  12430. };
  12431. /// Expand the selection to cover entire lines.
  12432. const selectLine = ({ state, dispatch }) => {
  12433. let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
  12434. dispatch(state.update({ selection: EditorSelection.create(ranges), annotations: Transaction.userEvent.of("keyboardselection") }));
  12435. return true;
  12436. };
  12437. /// Select the next syntactic construct that is larger than the
  12438. /// selection. Note that this will only work insofar as the language
  12439. /// [provider](#language.language) you use builds up a full
  12440. /// syntax tree.
  12441. const selectParentSyntax = ({ state, dispatch }) => {
  12442. let selection = updateSel(state.selection, range => {
  12443. var _a;
  12444. let context = syntaxTree(state).resolve(range.head, 1);
  12445. while (!((context.from < range.from && context.to >= range.to) ||
  12446. (context.to > range.to && context.from <= range.from) ||
  12447. !((_a = context.parent) === null || _a === void 0 ? void 0 : _a.parent)))
  12448. context = context.parent;
  12449. return EditorSelection.range(context.to, context.from);
  12450. });
  12451. dispatch(setSel(state, selection));
  12452. return true;
  12453. };
  12454. /// Simplify the current selection. When multiple ranges are selected,
  12455. /// reduce it to its main range. Otherwise, if the selection is
  12456. /// non-empty, convert it to a cursor selection.
  12457. const simplifySelection = ({ state, dispatch }) => {
  12458. let cur = state.selection, selection = null;
  12459. if (cur.ranges.length > 1)
  12460. selection = EditorSelection.create([cur.main]);
  12461. else if (!cur.main.empty)
  12462. selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)]);
  12463. if (!selection)
  12464. return false;
  12465. dispatch(setSel(state, selection));
  12466. return true;
  12467. };
  12468. function deleteBy(view, by) {
  12469. let { state } = view, changes = state.changeByRange(range => {
  12470. let { from, to } = range;
  12471. if (from == to) {
  12472. let towards = by(from);
  12473. from = Math.min(from, towards);
  12474. to = Math.max(to, towards);
  12475. }
  12476. return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from) };
  12477. });
  12478. if (changes.changes.empty)
  12479. return false;
  12480. view.dispatch(changes, { scrollIntoView: true, annotations: Transaction.userEvent.of("delete") });
  12481. return true;
  12482. }
  12483. const deleteByChar = (view, forward, codePoint) => deleteBy(view, pos => {
  12484. let { state } = view, line = state.doc.lineAt(pos), before;
  12485. if (!forward && pos > line.from && pos < line.from + 200 &&
  12486. !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
  12487. if (before[before.length - 1] == "\t")
  12488. return pos - 1;
  12489. let col = countColumn(before, 0, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state);
  12490. for (let i = 0; i < drop && before[before.length - 1 - i] == " "; i++)
  12491. pos--;
  12492. return pos;
  12493. }
  12494. let target;
  12495. if (codePoint) {
  12496. let next = line.text.slice(pos - line.from + (forward ? 0 : -2), pos - line.from + (forward ? 2 : 0));
  12497. let size = next ? codePointSize(codePointAt(next, 0)) : 1;
  12498. target = forward ? Math.min(state.doc.length, pos + size) : Math.max(0, pos - size);
  12499. }
  12500. else {
  12501. target = findClusterBreak(line.text, pos - line.from, forward) + line.from;
  12502. }
  12503. if (target == pos && line.number != (forward ? state.doc.lines : 1))
  12504. target += forward ? 1 : -1;
  12505. return target;
  12506. });
  12507. /// Delete the selection, or, for cursor selections, the code point
  12508. /// before the cursor.
  12509. const deleteCodePointBackward = view => deleteByChar(view, false, true);
  12510. /// Delete the selection, or, for cursor selections, the character
  12511. /// before the cursor.
  12512. const deleteCharBackward = view => deleteByChar(view, false, false);
  12513. /// Delete the selection or the character after the cursor.
  12514. const deleteCharForward = view => deleteByChar(view, true, false);
  12515. const deleteByGroup = (view, forward) => deleteBy(view, pos => {
  12516. let { state } = view, line = state.doc.lineAt(pos), categorize = state.charCategorizer(pos);
  12517. for (let cat = null;;) {
  12518. let next, nextChar;
  12519. if (pos == (forward ? line.to : line.from)) {
  12520. if (line.number == (forward ? state.doc.lines : 1))
  12521. break;
  12522. line = state.doc.line(line.number + (forward ? 1 : -1));
  12523. next = forward ? line.from : line.to;
  12524. nextChar = "\n";
  12525. }
  12526. else {
  12527. next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
  12528. nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
  12529. }
  12530. let nextCat = categorize(nextChar);
  12531. if (cat != null && nextCat != cat)
  12532. break;
  12533. if (nextCat != CharCategory.Space)
  12534. cat = nextCat;
  12535. pos = next;
  12536. }
  12537. return pos;
  12538. });
  12539. /// Delete the selection or backward until the end of the next
  12540. /// [group](#view.EditorView.moveByGroup).
  12541. const deleteGroupBackward = view => deleteByGroup(view, false);
  12542. /// Delete the selection or forward until the end of the next group.
  12543. const deleteGroupForward = view => deleteByGroup(view, true);
  12544. /// Delete the selection, or, if it is a cursor selection, delete to
  12545. /// the end of the line. If the cursor is directly at the end of the
  12546. /// line, delete the line break after it.
  12547. const deleteToLineEnd = view => deleteBy(view, pos => {
  12548. let lineEnd = view.visualLineAt(pos).to;
  12549. if (pos < lineEnd)
  12550. return lineEnd;
  12551. return Math.max(view.state.doc.length, pos + 1);
  12552. });
  12553. /// Replace each selection range with a line break, leaving the cursor
  12554. /// on the line before the break.
  12555. const splitLine = ({ state, dispatch }) => {
  12556. let changes = state.changeByRange(range => {
  12557. return { changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) },
  12558. range: EditorSelection.cursor(range.from) };
  12559. });
  12560. dispatch(state.update(changes, { scrollIntoView: true, annotations: Transaction.userEvent.of("input") }));
  12561. return true;
  12562. };
  12563. /// Flip the characters before and after the cursor(s).
  12564. const transposeChars = ({ state, dispatch }) => {
  12565. let changes = state.changeByRange(range => {
  12566. if (!range.empty || range.from == 0 || range.from == state.doc.length)
  12567. return { range };
  12568. let pos = range.from, line = state.doc.lineAt(pos);
  12569. let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
  12570. let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
  12571. return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) },
  12572. range: EditorSelection.cursor(to) };
  12573. });
  12574. if (changes.changes.empty)
  12575. return false;
  12576. dispatch(state.update(changes, { scrollIntoView: true }));
  12577. return true;
  12578. };
  12579. function selectedLineBlocks(state) {
  12580. let blocks = [], upto = -1;
  12581. for (let range of state.selection.ranges) {
  12582. let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to);
  12583. if (upto == startLine.number)
  12584. blocks[blocks.length - 1].to = endLine.to;
  12585. else
  12586. blocks.push({ from: startLine.from, to: endLine.to });
  12587. upto = endLine.number;
  12588. }
  12589. return blocks;
  12590. }
  12591. function moveLine(state, dispatch, forward) {
  12592. let changes = [];
  12593. for (let block of selectedLineBlocks(state)) {
  12594. if (forward ? block.to == state.doc.length : block.from == 0)
  12595. continue;
  12596. let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
  12597. if (forward)
  12598. changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak });
  12599. else
  12600. changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text });
  12601. }
  12602. if (!changes.length)
  12603. return false;
  12604. dispatch(state.update({ changes, scrollIntoView: true }));
  12605. return true;
  12606. }
  12607. /// Move the selected lines up one line.
  12608. const moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, false);
  12609. /// Move the selected lines down one line.
  12610. const moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, true);
  12611. function copyLine(state, dispatch, forward) {
  12612. let changes = [];
  12613. for (let block of selectedLineBlocks(state)) {
  12614. if (forward)
  12615. changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak });
  12616. else
  12617. changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) });
  12618. }
  12619. dispatch(state.update({ changes, scrollIntoView: true }));
  12620. return true;
  12621. }
  12622. /// Create a copy of the selected lines. Keep the selection in the top copy.
  12623. const copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, false);
  12624. /// Create a copy of the selected lines. Keep the selection in the bottom copy.
  12625. const copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, true);
  12626. /// Delete selected lines.
  12627. const deleteLine = view => {
  12628. let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => {
  12629. if (from > 0)
  12630. from--;
  12631. else if (to < state.doc.length)
  12632. to++;
  12633. return { from, to };
  12634. }));
  12635. let selection = updateSel(state.selection, range => view.moveVertically(range, true)).map(changes);
  12636. view.dispatch({ changes, selection, scrollIntoView: true });
  12637. return true;
  12638. };
  12639. function isBetweenBrackets(state, pos) {
  12640. if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1)))
  12641. return { from: pos, to: pos };
  12642. let context = syntaxTree(state).resolve(pos);
  12643. let before = context.childBefore(pos), after = context.childAfter(pos), closedBy;
  12644. if (before && after && before.to <= pos && after.from >= pos &&
  12645. (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1)
  12646. return { from: before.to, to: after.from };
  12647. return null;
  12648. }
  12649. /// Replace the selection with a newline and indent the newly created
  12650. /// line(s). If the current line consists only of whitespace, this
  12651. /// will also delete that whitespace. When the cursor is between
  12652. /// matching brackets, an additional newline will be inserted after
  12653. /// the cursor.
  12654. const insertNewlineAndIndent = ({ state, dispatch }) => {
  12655. let changes = state.changeByRange(({ from, to }) => {
  12656. let explode = from == to && isBetweenBrackets(state, from);
  12657. let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode });
  12658. let indent = getIndentation(cx, from);
  12659. if (indent == null)
  12660. indent = /^\s*/.exec(state.doc.lineAt(from).text)[0].length;
  12661. let line = state.doc.lineAt(from);
  12662. while (to < line.to && /\s/.test(line.text.slice(to - line.from, to + 1 - line.from)))
  12663. to++;
  12664. if (explode)
  12665. ({ from, to } = explode);
  12666. else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)))
  12667. from = line.from;
  12668. let insert = ["", indentString(state, indent)];
  12669. if (explode)
  12670. insert.push(indentString(state, cx.lineIndent(line)));
  12671. return { changes: { from, to, insert: Text.of(insert) },
  12672. range: EditorSelection.cursor(from + 1 + insert[1].length) };
  12673. });
  12674. dispatch(state.update(changes, { scrollIntoView: true }));
  12675. return true;
  12676. };
  12677. function changeBySelectedLine(state, f) {
  12678. let atLine = -1;
  12679. return state.changeByRange(range => {
  12680. let changes = [];
  12681. for (let line = state.doc.lineAt(range.from);;) {
  12682. if (line.number > atLine) {
  12683. f(line, changes, range);
  12684. atLine = line.number;
  12685. }
  12686. if (range.to <= line.to)
  12687. break;
  12688. line = state.doc.lineAt(line.to + 1);
  12689. }
  12690. let changeSet = state.changes(changes);
  12691. return { changes,
  12692. range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) };
  12693. });
  12694. }
  12695. /// Auto-indent the selected lines. This uses the [indentation service
  12696. /// facet](#language.indentService) as source for auto-indent
  12697. /// information.
  12698. const indentSelection = ({ state, dispatch }) => {
  12699. let updated = Object.create(null);
  12700. let context = new IndentContext(state, { overrideIndentation: start => {
  12701. let found = updated[start];
  12702. return found == null ? -1 : found;
  12703. } });
  12704. let changes = changeBySelectedLine(state, (line, changes, range) => {
  12705. let indent = getIndentation(context, line.from);
  12706. if (indent == null)
  12707. return;
  12708. let cur = /^\s*/.exec(line.text)[0];
  12709. let norm = indentString(state, indent);
  12710. if (cur != norm || range.from < line.from + cur.length) {
  12711. updated[line.from] = indent;
  12712. changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
  12713. }
  12714. });
  12715. if (!changes.changes.empty)
  12716. dispatch(state.update(changes));
  12717. return true;
  12718. };
  12719. /// Add a [unit](#language.indentUnit) of indentation to all selected
  12720. /// lines.
  12721. const indentMore = ({ state, dispatch }) => {
  12722. dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
  12723. changes.push({ from: line.from, insert: state.facet(indentUnit) });
  12724. })));
  12725. return true;
  12726. };
  12727. /// Remove a [unit](#language.indentUnit) of indentation from all
  12728. /// selected lines.
  12729. const indentLess = ({ state, dispatch }) => {
  12730. dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
  12731. let space = /^\s*/.exec(line.text)[0];
  12732. if (!space)
  12733. return;
  12734. let col = countColumn(space, 0, state.tabSize), keep = 0;
  12735. let insert = indentString(state, Math.max(0, col - getIndentUnit(state)));
  12736. while (keep < space.length && keep < insert.length && space.charCodeAt(keep) == insert.charCodeAt(keep))
  12737. keep++;
  12738. changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert.slice(keep) });
  12739. })));
  12740. return true;
  12741. };
  12742. /// Array of key bindings containing the Emacs-style bindings that are
  12743. /// available on macOS by default.
  12744. ///
  12745. /// - Ctrl-b: [`cursorCharLeft`](#commands.cursorCharLeft) ([`selectCharLeft`](#commands.selectCharLeft) with Shift)
  12746. /// - Ctrl-f: [`cursorCharRight`](#commands.cursorCharRight) ([`selectCharRight`](#commands.selectCharRight) with Shift)
  12747. /// - Ctrl-p: [`cursorLineUp`](#commands.cursorLineUp) ([`selectLineUp`](#commands.selectLineUp) with Shift)
  12748. /// - Ctrl-n: [`cursorLineDown`](#commands.cursorLineDown) ([`selectLineDown`](#commands.selectLineDown) with Shift)
  12749. /// - Ctrl-a: [`cursorLineStart`](#commands.cursorLineStart) ([`selectLineStart`](#commands.selectLineStart) with Shift)
  12750. /// - Ctrl-e: [`cursorLineEnd`](#commands.cursorLineEnd) ([`selectLineEnd`](#commands.selectLineEnd) with Shift)
  12751. /// - Ctrl-d: [`deleteCharForward`](#commands.deleteCharForward)
  12752. /// - Ctrl-h: [`deleteCharBackward`](#commands.deleteCharBackward)
  12753. /// - Ctrl-k: [`deleteToLineEnd`](#commands.deleteToLineEnd)
  12754. /// - Alt-d: [`deleteGroupForward`](#commands.deleteGroupForward)
  12755. /// - Ctrl-Alt-h: [`deleteGroupBackward`](#commands.deleteGroupBackward)
  12756. /// - Ctrl-o: [`splitLine`](#commands.splitLine)
  12757. /// - Ctrl-t: [`transposeChars`](#commands.transposeChars)
  12758. /// - Alt-f: [`cursorGroupForward`](#commands.cursorGroupForward) ([`selectGroupForward`](#commands.selectGroupForward) with Shift)
  12759. /// - Alt-b: [`cursorGroupBackward`](#commands.cursorGroupBackward) ([`selectGroupBackward`](#commands.selectGroupBackward) with Shift)
  12760. /// - Alt-<: [`cursorDocStart`](#commands.cursorDocStart)
  12761. /// - Alt->: [`cursorDocEnd`](#commands.cursorDocEnd)
  12762. /// - Ctrl-v: [`cursorPageDown`](#commands.cursorPageDown)
  12763. /// - Alt-v: [`cursorPageUp`](#commands.cursorPageUp)
  12764. const emacsStyleKeymap = [
  12765. { key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft },
  12766. { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight },
  12767. { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp },
  12768. { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown },
  12769. { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart },
  12770. { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd },
  12771. { key: "Ctrl-d", run: deleteCharForward },
  12772. { key: "Ctrl-h", run: deleteCharBackward },
  12773. { key: "Ctrl-k", run: deleteToLineEnd },
  12774. { key: "Alt-d", run: deleteGroupForward },
  12775. { key: "Ctrl-Alt-h", run: deleteGroupBackward },
  12776. { key: "Ctrl-o", run: splitLine },
  12777. { key: "Ctrl-t", run: transposeChars },
  12778. { key: "Alt-f", run: cursorGroupForward, shift: selectGroupForward },
  12779. { key: "Alt-b", run: cursorGroupBackward, shift: selectGroupBackward },
  12780. { key: "Alt-<", run: cursorDocStart },
  12781. { key: "Alt->", run: cursorDocEnd },
  12782. { key: "Ctrl-v", run: cursorPageDown },
  12783. { key: "Alt-v", run: cursorPageUp },
  12784. ];
  12785. /// An array of key bindings closely sticking to platform-standard or
  12786. /// widely used bindings. (This includes the bindings from
  12787. /// [`emacsStyleKeymap`](#commands.emacsStyleKeymap), with their `key`
  12788. /// property changed to `mac`.)
  12789. ///
  12790. /// - ArrowLeft: [`cursorCharLeft`](#commands.cursorCharLeft) ([`selectCharLeft`](#commands.selectCharLeft) with Shift)
  12791. /// - ArrowRight: [`cursorCharRight`](#commands.cursorCharRight) ([`selectCharRight`](#commands.selectCharRight) with Shift)
  12792. /// - Ctrl-ArrowLeft (Alt-ArrowLeft on macOS): [`cursorGroupLeft`](#commands.cursorGroupLeft) ([`selectGroupLeft`](#commands.selectGroupLeft) with Shift)
  12793. /// - Ctrl-ArrowRight (Alt-ArrowRight on macOS): [`cursorGroupRight`](#commands.cursorGroupRight) ([`selectGroupRight`](#commands.selectGroupRight) with Shift)
  12794. /// - Cmd-ArrowLeft (on macOS): [`cursorLineStart`](#commands.cursorLineStart) ([`selectLineStart`](#commands.selectLineStart) with Shift)
  12795. /// - Cmd-ArrowRight (on macOS): [`cursorLineEnd`](#commands.cursorLineEnd) ([`selectLineEnd`](#commands.selectLineEnd) with Shift)
  12796. /// - ArrowUp: [`cursorLineUp`](#commands.cursorLineUp) ([`selectLineUp`](#commands.selectLineUp) with Shift)
  12797. /// - ArrowDown: [`cursorLineDown`](#commands.cursorLineDown) ([`selectLineDown`](#commands.selectLineDown) with Shift)
  12798. /// - Cmd-ArrowUp (on macOS): [`cursorDocStart`](#commands.cursorDocStart) ([`selectDocStart`](#commands.selectDocStart) with Shift)
  12799. /// - Cmd-ArrowDown (on macOS): [`cursorDocEnd`](#commands.cursorDocEnd) ([`selectDocEnd`](#commands.selectDocEnd) with Shift)
  12800. /// - Ctrl-ArrowUp (on macOS): [`cursorPageUp`](#commands.cursorPageUp) ([`selectPageUp`](#commands.selectPageUp) with Shift)
  12801. /// - Ctrl-ArrowDown (on macOS): [`cursorPageDown`](#commands.cursorPageDown) ([`selectPageDown`](#commands.selectPageDown) with Shift)
  12802. /// - PageUp: [`cursorPageUp`](#commands.cursorPageUp) ([`selectPageUp`](#commands.selectPageUp) with Shift)
  12803. /// - PageDown: [`cursorPageDown`](#commands.cursorPageDown) ([`selectPageDown`](#commands.selectPageDown) with Shift)
  12804. /// - Home: [`cursorLineBoundaryBackward`](#commands.cursorLineBoundaryBackward) ([`selectLineBoundaryBackward`](#commands.selectLineBoundaryBackward) with Shift)
  12805. /// - End: [`cursorLineBoundaryForward`](#commands.cursorLineBoundaryForward) ([`selectLineBoundaryForward`](#commands.selectLineBoundaryForward) with Shift)
  12806. /// - Ctrl-Home (Cmd-Home on macOS): [`cursorDocStart`](#commands.cursorDocStart) ([`selectDocStart`](#commands.selectDocStart) with Shift)
  12807. /// - Ctrl-End (Cmd-Home on macOS): [`cursorDocEnd`](#commands.cursorDocEnd) ([`selectDocEnd`](#commands.selectDocEnd) with Shift)
  12808. /// - Enter: [`insertNewlineAndIndent`](#commands.insertNewlineAndIndent)
  12809. /// - Ctrl-a (Cmd-a on macOS): [`selectAll`](#commands.selectAll)
  12810. /// - Backspace: [`deleteCodePointBackward`](#commands.deleteCodePointBackward)
  12811. /// - Delete: [`deleteCharForward`](#commands.deleteCharForward)
  12812. /// - Ctrl-Backspace (Alt-Backspace on macOS): [`deleteGroupBackward`](#commands.deleteGroupBackward)
  12813. /// - Ctrl-Delete (Alt-Delete on macOS): [`deleteGroupForward`](#commands.deleteGroupForward)
  12814. const standardKeymap = [
  12815. { key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft },
  12816. { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft },
  12817. { mac: "Cmd-ArrowLeft", run: cursorLineStart, shift: selectLineStart },
  12818. { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight },
  12819. { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight },
  12820. { mac: "Cmd-ArrowRight", run: cursorLineEnd, shift: selectLineEnd },
  12821. { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp },
  12822. { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart },
  12823. { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp },
  12824. { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown },
  12825. { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd },
  12826. { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown },
  12827. { key: "PageUp", run: cursorPageUp, shift: selectPageUp },
  12828. { key: "PageDown", run: cursorPageDown, shift: selectPageDown },
  12829. { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward },
  12830. { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart },
  12831. { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward },
  12832. { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd },
  12833. { key: "Enter", run: insertNewlineAndIndent },
  12834. { key: "Mod-a", run: selectAll },
  12835. { key: "Backspace", run: deleteCodePointBackward },
  12836. { key: "Delete", run: deleteCharForward },
  12837. { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward },
  12838. { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward },
  12839. ].concat(emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift })));
  12840. /// The default keymap. Includes all bindings from
  12841. /// [`standardKeymap`](#commands.standardKeymap) plus the following:
  12842. ///
  12843. /// - Alt-ArrowLeft (Ctrl-ArrowLeft on macOS): [`cursorSyntaxLeft`](#commands.cursorSyntaxLeft) ([`selectSyntaxLeft`](#commands.selectSyntaxLeft) with Shift)
  12844. /// - Alt-ArrowRight (Ctrl-ArrowRight on macOS): [`cursorSyntaxRight`](#commands.cursorSyntaxRight) ([`selectSyntaxRight`](#commands.selectSyntaxRight) with Shift)
  12845. /// - Alt-ArrowUp: [`moveLineUp`](#commands.moveLineUp)
  12846. /// - Alt-ArrowDown: [`moveLineDown`](#commands.moveLineDown)
  12847. /// - Shift-Alt-ArrowUp: [`copyLineUp`](#commands.copyLineUp)
  12848. /// - Shift-Alt-ArrowDown: [`copyLineDown`](#commands.copyLineDown)
  12849. /// - Escape: [`simplifySelection`](#commands.simplifySelection)
  12850. /// - Ctrl-l (Cmd-l on macOS): [`selectLine`](#commands.selectLine)
  12851. /// - Ctrl-i (Cmd-i on macOS): [`selectParentSyntax`](#commands.selectParentSyntax)
  12852. /// - Ctrl-[ (Cmd-[ on macOS): [`indentLess`](#commands.indentLess)
  12853. /// - Ctrl-] (Cmd-] on macOS): [`indentMore`](#commands.indentMore)
  12854. /// - Ctrl-Alt-\\ (Cmd-Alt-\\ on macOS): [`indentSelection`](#commands.indentSelection)
  12855. /// - Shift-Ctrl-k (Shift-Cmd-k on macOS): [`deleteLine`](#commands.deleteLine)
  12856. /// - Shift-Ctrl-\\ (Shift-Cmd-\\ on macOS): [`cursorMatchingBracket`](#commands.cursorMatchingBracket)
  12857. const defaultKeymap = [
  12858. { key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft },
  12859. { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight },
  12860. { key: "Alt-ArrowUp", run: moveLineUp },
  12861. { key: "Shift-Alt-ArrowUp", run: copyLineUp },
  12862. { key: "Alt-ArrowDown", run: moveLineDown },
  12863. { key: "Shift-Alt-ArrowDown", run: copyLineDown },
  12864. { key: "Escape", run: simplifySelection },
  12865. { key: "Mod-l", run: selectLine },
  12866. { key: "Mod-i", run: selectParentSyntax },
  12867. { key: "Mod-[", run: indentLess },
  12868. { key: "Mod-]", run: indentMore },
  12869. { key: "Mod-Alt-\\", run: indentSelection },
  12870. { key: "Shift-Mod-k", run: deleteLine },
  12871. { key: "Shift-Mod-\\", run: cursorMatchingBracket }
  12872. ].concat(standardKeymap);
  12873. const defaults$1 = {
  12874. brackets: ["(", "[", "{", "'", '"'],
  12875. before: ")]}'\":;>"
  12876. };
  12877. const closeBracketEffect = StateEffect.define({
  12878. map(value, mapping) {
  12879. let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
  12880. return mapped == null ? undefined : mapped;
  12881. }
  12882. });
  12883. const skipBracketEffect = StateEffect.define({
  12884. map(value, mapping) { return mapping.mapPos(value); }
  12885. });
  12886. const closedBracket = new class extends RangeValue {
  12887. };
  12888. closedBracket.startSide = 1;
  12889. closedBracket.endSide = -1;
  12890. const bracketState = StateField.define({
  12891. create() { return RangeSet.empty; },
  12892. update(value, tr) {
  12893. if (tr.selection) {
  12894. let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from;
  12895. let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from;
  12896. if (lineStart != tr.changes.mapPos(prevLineStart, -1))
  12897. value = RangeSet.empty;
  12898. }
  12899. value = value.map(tr.changes);
  12900. for (let effect of tr.effects) {
  12901. if (effect.is(closeBracketEffect))
  12902. value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
  12903. else if (effect.is(skipBracketEffect))
  12904. value = value.update({ filter: from => from != effect.value });
  12905. }
  12906. return value;
  12907. }
  12908. });
  12909. /// Extension to enable bracket-closing behavior. When a closeable
  12910. /// bracket is typed, its closing bracket is immediately inserted
  12911. /// after the cursor. When closing a bracket directly in front of a
  12912. /// closing bracket inserted by the extension, the cursor moves over
  12913. /// that bracket.
  12914. function closeBrackets() {
  12915. return [EditorView.inputHandler.of(handleInput), bracketState];
  12916. }
  12917. const definedClosing = "()[]{}<>";
  12918. function closing(ch) {
  12919. for (let i = 0; i < definedClosing.length; i += 2)
  12920. if (definedClosing.charCodeAt(i) == ch)
  12921. return definedClosing.charAt(i + 1);
  12922. return fromCodePoint(ch < 128 ? ch : ch + 1);
  12923. }
  12924. function config(state, pos) {
  12925. return state.languageDataAt("closeBrackets", pos)[0] || defaults$1;
  12926. }
  12927. function handleInput(view, from, to, insert) {
  12928. if (view.composing)
  12929. return false;
  12930. let sel = view.state.selection.main;
  12931. if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||
  12932. from != sel.from || to != sel.to)
  12933. return false;
  12934. let tr = insertBracket(view.state, insert);
  12935. if (!tr)
  12936. return false;
  12937. view.dispatch(tr);
  12938. return true;
  12939. }
  12940. /// Command that implements deleting a pair of matching brackets when
  12941. /// the cursor is between them.
  12942. const deleteBracketPair = ({ state, dispatch }) => {
  12943. let conf = config(state, state.selection.main.head);
  12944. let tokens = conf.brackets || defaults$1.brackets;
  12945. let dont = null, changes = state.changeByRange(range => {
  12946. if (range.empty) {
  12947. let before = prevChar(state.doc, range.head);
  12948. for (let token of tokens) {
  12949. if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0)))
  12950. return { changes: { from: range.head - token.length, to: range.head + token.length },
  12951. range: EditorSelection.cursor(range.head - token.length),
  12952. annotations: Transaction.userEvent.of("delete") };
  12953. }
  12954. }
  12955. return { range: dont = range };
  12956. });
  12957. if (!dont)
  12958. dispatch(state.update(changes, { scrollIntoView: true }));
  12959. return !dont;
  12960. };
  12961. /// Close-brackets related key bindings. Binds Backspace to
  12962. /// [`deleteBracketPair`](#closebrackets.deleteBracketPair).
  12963. const closeBracketsKeymap = [
  12964. { key: "Backspace", run: deleteBracketPair }
  12965. ];
  12966. /// Implements the extension's behavior on text insertion. If the
  12967. /// given string counts as a bracket in the language around the
  12968. /// selection, and replacing the selection with it requires custom
  12969. /// behavior (inserting a closing version or skipping past a
  12970. /// previously-closed bracket), this function returns a transaction
  12971. /// representing that custom behavior. (You only need this if you want
  12972. /// to programmatically insert brackets—the
  12973. /// [`closeBrackets`](#closebrackets.closeBrackets) extension will
  12974. /// take care of running this for user input.)
  12975. function insertBracket(state, bracket) {
  12976. let conf = config(state, state.selection.main.head);
  12977. let tokens = conf.brackets || defaults$1.brackets;
  12978. for (let tok of tokens) {
  12979. let closed = closing(codePointAt(tok, 0));
  12980. if (bracket == tok)
  12981. return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1)
  12982. : handleOpen(state, tok, closed, conf.before || defaults$1.before);
  12983. if (bracket == closed && closedBracketAt(state, state.selection.main.from))
  12984. return handleClose(state, tok, closed);
  12985. }
  12986. return null;
  12987. }
  12988. function closedBracketAt(state, pos) {
  12989. let found = false;
  12990. state.field(bracketState).between(0, state.doc.length, from => {
  12991. if (from == pos)
  12992. found = true;
  12993. });
  12994. return found;
  12995. }
  12996. function nextChar(doc, pos) {
  12997. let next = doc.sliceString(pos, pos + 2);
  12998. return next.slice(0, codePointSize(codePointAt(next, 0)));
  12999. }
  13000. function prevChar(doc, pos) {
  13001. let prev = doc.sliceString(pos - 2, pos);
  13002. return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
  13003. }
  13004. function handleOpen(state, open, close, closeBefore) {
  13005. let dont = null, changes = state.changeByRange(range => {
  13006. if (!range.empty)
  13007. return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
  13008. effects: closeBracketEffect.of(range.to + open.length),
  13009. range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
  13010. let next = nextChar(state.doc, range.head);
  13011. if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
  13012. return { changes: { insert: open + close, from: range.head },
  13013. effects: closeBracketEffect.of(range.head + open.length),
  13014. range: EditorSelection.cursor(range.head + open.length) };
  13015. return { range: dont = range };
  13016. });
  13017. return dont ? null : state.update(changes, {
  13018. scrollIntoView: true,
  13019. annotations: Transaction.userEvent.of("input")
  13020. });
  13021. }
  13022. function handleClose(state, _open, close) {
  13023. let dont = null, moved = state.selection.ranges.map(range => {
  13024. if (range.empty && nextChar(state.doc, range.head) == close)
  13025. return EditorSelection.cursor(range.head + close.length);
  13026. return dont = range;
  13027. });
  13028. return dont ? null : state.update({
  13029. selection: EditorSelection.create(moved, state.selection.mainIndex),
  13030. scrollIntoView: true,
  13031. effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from))
  13032. });
  13033. }
  13034. // Handles cases where the open and close token are the same, and
  13035. // possibly triple quotes (as in `"""abc"""`-style quoting).
  13036. function handleSame(state, token, allowTriple) {
  13037. let dont = null, changes = state.changeByRange(range => {
  13038. if (!range.empty)
  13039. return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
  13040. effects: closeBracketEffect.of(range.to + token.length),
  13041. range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
  13042. let pos = range.head, next = nextChar(state.doc, pos);
  13043. if (next == token) {
  13044. if (nodeStart(state, pos)) {
  13045. return { changes: { insert: token + token, from: pos },
  13046. effects: closeBracketEffect.of(pos + token.length),
  13047. range: EditorSelection.cursor(pos + token.length) };
  13048. }
  13049. else if (closedBracketAt(state, pos)) {
  13050. let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
  13051. return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)),
  13052. effects: skipBracketEffect.of(pos) };
  13053. }
  13054. }
  13055. else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
  13056. nodeStart(state, pos - 2 * token.length)) {
  13057. return { changes: { insert: token + token + token + token, from: pos },
  13058. effects: closeBracketEffect.of(pos + token.length),
  13059. range: EditorSelection.cursor(pos + token.length) };
  13060. }
  13061. else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
  13062. let prev = state.sliceDoc(pos - 1, pos);
  13063. if (prev != token && state.charCategorizer(pos)(prev) != CharCategory.Word)
  13064. return { changes: { insert: token + token, from: pos },
  13065. effects: closeBracketEffect.of(pos + token.length),
  13066. range: EditorSelection.cursor(pos + token.length) };
  13067. }
  13068. return { range: dont = range };
  13069. });
  13070. return dont ? null : state.update(changes, {
  13071. scrollIntoView: true,
  13072. annotations: Transaction.userEvent.of("input")
  13073. });
  13074. }
  13075. function nodeStart(state, pos) {
  13076. let tree = syntaxTree(state).resolve(pos + 1);
  13077. return tree.parent && tree.from == pos;
  13078. }
  13079. const panelConfig = Facet.define({
  13080. combine(configs) {
  13081. let topContainer, bottomContainer;
  13082. for (let c of configs) {
  13083. topContainer = topContainer || c.topContainer;
  13084. bottomContainer = bottomContainer || c.bottomContainer;
  13085. }
  13086. return { topContainer, bottomContainer };
  13087. }
  13088. });
  13089. /// Enables the panel-managing extension.
  13090. function panels(config) {
  13091. let ext = [panelPlugin, baseTheme$4];
  13092. if (config)
  13093. ext.push(panelConfig.of(config));
  13094. return ext;
  13095. }
  13096. /// Opening a panel is done by providing a constructor function for
  13097. /// the panel through this facet. (The panel is closed again when its
  13098. /// constructor is no longer provided.)
  13099. const showPanel = Facet.define();
  13100. /// Get the active panel created by the given constructor, if any.
  13101. /// This can be useful when you need access to your panels' DOM
  13102. /// structure.
  13103. function getPanel(view, panel) {
  13104. let plugin = view.plugin(panelPlugin);
  13105. let index = view.state.facet(showPanel).indexOf(panel);
  13106. return plugin && index > -1 ? plugin.panels[index] : null;
  13107. }
  13108. const panelPlugin = ViewPlugin.fromClass(class {
  13109. constructor(view) {
  13110. this.specs = view.state.facet(showPanel);
  13111. this.panels = this.specs.map(spec => spec(view));
  13112. let conf = view.state.facet(panelConfig);
  13113. this.top = new PanelGroup(view, true, conf.topContainer);
  13114. this.bottom = new PanelGroup(view, false, conf.bottomContainer);
  13115. this.top.sync(this.panels.filter(p => p.top));
  13116. this.bottom.sync(this.panels.filter(p => !p.top));
  13117. for (let p of this.panels) {
  13118. p.dom.className += " " + panelClass(p);
  13119. if (p.mount)
  13120. p.mount();
  13121. }
  13122. }
  13123. update(update) {
  13124. let conf = update.state.facet(panelConfig);
  13125. if (this.top.container != conf.topContainer) {
  13126. this.top.sync([]);
  13127. this.top = new PanelGroup(update.view, true, conf.topContainer);
  13128. }
  13129. if (this.bottom.container != conf.bottomContainer) {
  13130. this.bottom.sync([]);
  13131. this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
  13132. }
  13133. this.top.syncClasses();
  13134. this.bottom.syncClasses();
  13135. let specs = update.state.facet(showPanel);
  13136. if (specs != this.specs) {
  13137. let panels = [], top = [], bottom = [], mount = [];
  13138. for (let spec of specs) {
  13139. let known = this.specs.indexOf(spec), panel;
  13140. if (known < 0) {
  13141. panel = spec(update.view);
  13142. mount.push(panel);
  13143. }
  13144. else {
  13145. panel = this.panels[known];
  13146. if (panel.update)
  13147. panel.update(update);
  13148. }
  13149. panels.push(panel);
  13150. (panel.top ? top : bottom).push(panel);
  13151. }
  13152. this.specs = specs;
  13153. this.panels = panels;
  13154. this.top.sync(top);
  13155. this.bottom.sync(bottom);
  13156. for (let p of mount) {
  13157. p.dom.className += " " + panelClass(p);
  13158. if (p.mount)
  13159. p.mount();
  13160. }
  13161. }
  13162. else {
  13163. for (let p of this.panels)
  13164. if (p.update)
  13165. p.update(update);
  13166. }
  13167. }
  13168. destroy() {
  13169. this.top.sync([]);
  13170. this.bottom.sync([]);
  13171. }
  13172. }, {
  13173. provide: PluginField.scrollMargins.from(value => ({ top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() }))
  13174. });
  13175. function panelClass(panel) {
  13176. return themeClass(panel.style ? `panel.${panel.style}` : "panel");
  13177. }
  13178. class PanelGroup {
  13179. constructor(view, top, container) {
  13180. this.view = view;
  13181. this.top = top;
  13182. this.container = container;
  13183. this.dom = undefined;
  13184. this.classes = "";
  13185. this.panels = [];
  13186. this.syncClasses();
  13187. }
  13188. sync(panels) {
  13189. this.panels = panels;
  13190. this.syncDOM();
  13191. }
  13192. syncDOM() {
  13193. if (this.panels.length == 0) {
  13194. if (this.dom) {
  13195. this.dom.remove();
  13196. this.dom = undefined;
  13197. }
  13198. return;
  13199. }
  13200. if (!this.dom) {
  13201. this.dom = document.createElement("div");
  13202. this.dom.className = themeClass(this.top ? "panels.top" : "panels.bottom");
  13203. this.dom.style[this.top ? "top" : "bottom"] = "0";
  13204. let parent = this.container || this.view.dom;
  13205. parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
  13206. }
  13207. let curDOM = this.dom.firstChild;
  13208. for (let panel of this.panels) {
  13209. if (panel.dom.parentNode == this.dom) {
  13210. while (curDOM != panel.dom)
  13211. curDOM = rm$1(curDOM);
  13212. curDOM = curDOM.nextSibling;
  13213. }
  13214. else {
  13215. this.dom.insertBefore(panel.dom, curDOM);
  13216. }
  13217. }
  13218. while (curDOM)
  13219. curDOM = rm$1(curDOM);
  13220. }
  13221. scrollMargin() {
  13222. return !this.dom || this.container ? 0
  13223. : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - this.view.scrollDOM.getBoundingClientRect().top
  13224. : this.view.scrollDOM.getBoundingClientRect().bottom - this.dom.getBoundingClientRect().top);
  13225. }
  13226. syncClasses() {
  13227. if (!this.container || this.classes == this.view.themeClasses)
  13228. return;
  13229. for (let cls of this.classes.split(" "))
  13230. if (cls)
  13231. this.container.classList.remove(cls);
  13232. for (let cls of (this.classes = this.view.themeClasses).split(" "))
  13233. if (cls)
  13234. this.container.classList.add(cls);
  13235. }
  13236. }
  13237. function rm$1(node) {
  13238. let next = node.nextSibling;
  13239. node.remove();
  13240. return next;
  13241. }
  13242. const baseTheme$4 = EditorView.baseTheme({
  13243. $panels: {
  13244. boxSizing: "border-box",
  13245. position: "sticky",
  13246. left: 0,
  13247. right: 0
  13248. },
  13249. "$$light $panels": {
  13250. backgroundColor: "#f5f5f5",
  13251. color: "black"
  13252. },
  13253. "$$light $panels.top": {
  13254. borderBottom: "1px solid #ddd"
  13255. },
  13256. "$$light $panels.bottom": {
  13257. borderTop: "1px solid #ddd"
  13258. },
  13259. "$$dark $panels": {
  13260. backgroundColor: "#333338",
  13261. color: "white"
  13262. }
  13263. });
  13264. function crelt() {
  13265. var elt = arguments[0];
  13266. if (typeof elt == "string") elt = document.createElement(elt);
  13267. var i = 1, next = arguments[1];
  13268. if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
  13269. for (var name in next) if (Object.prototype.hasOwnProperty.call(next, name)) {
  13270. var value = next[name];
  13271. if (typeof value == "string") elt.setAttribute(name, value);
  13272. else if (value != null) elt[name] = value;
  13273. }
  13274. i++;
  13275. }
  13276. for (; i < arguments.length; i++) add(elt, arguments[i]);
  13277. return elt
  13278. }
  13279. function add(elt, child) {
  13280. if (typeof child == "string") {
  13281. elt.appendChild(document.createTextNode(child));
  13282. } else if (child == null) ; else if (child.nodeType != null) {
  13283. elt.appendChild(child);
  13284. } else if (Array.isArray(child)) {
  13285. for (var i = 0; i < child.length; i++) add(elt, child[i]);
  13286. } else {
  13287. throw new RangeError("Unsupported child node: " + child)
  13288. }
  13289. }
  13290. const basicNormalize = typeof String.prototype.normalize == "function" ? x => x.normalize("NFKD") : x => x;
  13291. /// A search cursor provides an iterator over text matches in a
  13292. /// document.
  13293. class SearchCursor {
  13294. /// Create a text cursor. The query is the search string, `from` to
  13295. /// `to` provides the region to search.
  13296. ///
  13297. /// When `normalize` is given, it will be called, on both the query
  13298. /// string and the content it is matched against, before comparing.
  13299. /// You can, for example, create a case-insensitive search by
  13300. /// passing `s => s.toLowerCase()`.
  13301. ///
  13302. /// Text is always normalized with
  13303. /// [`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
  13304. /// (when supported).
  13305. constructor(text, query, from = 0, to = text.length, normalize) {
  13306. /// The current match (only holds a meaningful value after
  13307. /// [`next`](#search.SearchCursor.next) has been called and when
  13308. /// `done` is false).
  13309. this.value = { from: 0, to: 0 };
  13310. /// Whether the end of the iterated region has been reached.
  13311. this.done = false;
  13312. this.matches = [];
  13313. this.buffer = "";
  13314. this.bufferPos = 0;
  13315. this.iter = text.iterRange(from, to);
  13316. this.bufferStart = from;
  13317. this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
  13318. this.query = this.normalize(query);
  13319. }
  13320. peek() {
  13321. if (this.bufferPos == this.buffer.length) {
  13322. this.bufferStart += this.buffer.length;
  13323. this.iter.next();
  13324. if (this.iter.done)
  13325. return -1;
  13326. this.bufferPos = 0;
  13327. this.buffer = this.iter.value;
  13328. }
  13329. return this.buffer.charCodeAt(this.bufferPos);
  13330. }
  13331. /// Look for the next match. Updates the iterator's
  13332. /// [`value`](#search.SearchCursor.value) and
  13333. /// [`done`](#search.SearchCursor.done) properties. Should be called
  13334. /// at least once before using the cursor.
  13335. next() {
  13336. for (;;) {
  13337. let next = this.peek();
  13338. if (next < 0) {
  13339. this.done = true;
  13340. return this;
  13341. }
  13342. let str = String.fromCharCode(next), start = this.bufferStart + this.bufferPos;
  13343. this.bufferPos++;
  13344. for (;;) {
  13345. let peek = this.peek();
  13346. if (peek < 0xDC00 || peek >= 0xE000)
  13347. break;
  13348. this.bufferPos++;
  13349. str += String.fromCharCode(peek);
  13350. }
  13351. let norm = this.normalize(str);
  13352. for (let i = 0, pos = start;; i++) {
  13353. let code = norm.charCodeAt(i);
  13354. let match = this.match(code, pos);
  13355. if (match) {
  13356. this.value = match;
  13357. return this;
  13358. }
  13359. if (i == norm.length - 1)
  13360. break;
  13361. if (pos == start && i < str.length && str.charCodeAt(i) == code)
  13362. pos++;
  13363. }
  13364. }
  13365. }
  13366. match(code, pos) {
  13367. let match = null;
  13368. for (let i = 0; i < this.matches.length; i += 2) {
  13369. let index = this.matches[i], keep = false;
  13370. if (this.query.charCodeAt(index) == code) {
  13371. if (index == this.query.length - 1) {
  13372. match = { from: this.matches[i + 1], to: pos + 1 };
  13373. }
  13374. else {
  13375. this.matches[i]++;
  13376. keep = true;
  13377. }
  13378. }
  13379. if (!keep) {
  13380. this.matches.splice(i, 2);
  13381. i -= 2;
  13382. }
  13383. }
  13384. if (this.query.charCodeAt(0) == code) {
  13385. if (this.query.length == 1)
  13386. match = { from: pos, to: pos + 1 };
  13387. else
  13388. this.matches.push(1, pos);
  13389. }
  13390. return match;
  13391. }
  13392. }
  13393. function createLineDialog(view) {
  13394. let dom = document.createElement("form");
  13395. dom.innerHTML = `<label>${view.state.phrase("Go to line:")} <input class=${themeClass("textfield")} name=line></label>
  13396. <button class=${themeClass("button")} type=submit>${view.state.phrase("go")}</button>`;
  13397. let input = dom.querySelector("input");
  13398. function go() {
  13399. let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
  13400. if (!match)
  13401. return;
  13402. let { state } = view, startLine = state.doc.lineAt(state.selection.main.head);
  13403. let [, sign, ln, cl, percent] = match;
  13404. let col = cl ? +cl.slice(1) : 0;
  13405. let line = ln ? +ln : startLine.number;
  13406. if (ln && percent) {
  13407. let pc = line / 100;
  13408. if (sign)
  13409. pc = pc * (sign == "-" ? -1 : 1) + (startLine.number / state.doc.lines);
  13410. line = Math.round(state.doc.lines * pc);
  13411. }
  13412. else if (ln && sign) {
  13413. line = line * (sign == "-" ? -1 : 1) + startLine.number;
  13414. }
  13415. let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
  13416. view.dispatch({
  13417. effects: dialogEffect.of(false),
  13418. selection: EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))),
  13419. scrollIntoView: true
  13420. });
  13421. view.focus();
  13422. }
  13423. dom.addEventListener("keydown", event => {
  13424. if (event.keyCode == 27) { // Escape
  13425. event.preventDefault();
  13426. view.dispatch({ effects: dialogEffect.of(false) });
  13427. view.focus();
  13428. }
  13429. else if (event.keyCode == 13) { // Enter
  13430. event.preventDefault();
  13431. go();
  13432. }
  13433. });
  13434. dom.addEventListener("submit", go);
  13435. return { dom, style: "gotoLine", pos: -10 };
  13436. }
  13437. const dialogEffect = StateEffect.define();
  13438. const dialogField = StateField.define({
  13439. create() { return true; },
  13440. update(value, tr) {
  13441. for (let e of tr.effects)
  13442. if (e.is(dialogEffect))
  13443. value = e.value;
  13444. return value;
  13445. },
  13446. provide: f => showPanel.computeN([f], s => s.field(f) ? [createLineDialog] : [])
  13447. });
  13448. /// Command that shows a dialog asking the user for a line number, and
  13449. /// when a valid position is provided, moves the cursor to that line.
  13450. ///
  13451. /// Supports line numbers, relative line offsets prefixed with `+` or
  13452. /// `-`, document percentages suffixed with `%`, and an optional
  13453. /// column position by adding `:` and a second number after the line
  13454. /// number.
  13455. ///
  13456. /// The dialog can be styled with the `panel.gotoLine` theme
  13457. /// selector.
  13458. const gotoLine = view => {
  13459. let panel = getPanel(view, createLineDialog);
  13460. if (!panel) {
  13461. view.dispatch({
  13462. reconfigure: view.state.field(dialogField, false) == null ? { append: [panels(), dialogField, baseTheme$5] } : undefined,
  13463. effects: dialogEffect.of(true)
  13464. });
  13465. panel = getPanel(view, createLineDialog);
  13466. }
  13467. if (panel)
  13468. panel.dom.querySelector("input").focus();
  13469. return true;
  13470. };
  13471. const baseTheme$5 = EditorView.baseTheme({
  13472. "$panel.gotoLine": {
  13473. padding: "2px 6px 4px",
  13474. "& label": { fontSize: "80%" }
  13475. }
  13476. });
  13477. const defaultHighlightOptions = {
  13478. highlightWordAroundCursor: false,
  13479. minSelectionLength: 1,
  13480. maxMatches: 100
  13481. };
  13482. const highlightConfig = Facet.define({
  13483. combine(options) {
  13484. return combineConfig(options, defaultHighlightOptions, {
  13485. highlightWordAroundCursor: (a, b) => a || b,
  13486. minSelectionLength: Math.min,
  13487. maxMatches: Math.min
  13488. });
  13489. }
  13490. });
  13491. /// This extension highlights text that matches the selection. It uses
  13492. /// the `$selectionMatch` theme class for the highlighting. When
  13493. /// `highlightWordAroundCursor` is enabled, the word at the cursor
  13494. /// itself will be highlighted with `selectionMatch.main`.
  13495. function highlightSelectionMatches(options) {
  13496. let ext = [defaultTheme, matchHighlighter];
  13497. if (options)
  13498. ext.push(highlightConfig.of(options));
  13499. return ext;
  13500. }
  13501. function wordAt(doc, pos, check) {
  13502. let line = doc.lineAt(pos);
  13503. let from = pos - line.from, to = pos - line.from;
  13504. while (from > 0) {
  13505. let prev = findClusterBreak(line.text, from, false);
  13506. if (check(line.text.slice(prev, from)) != CharCategory.Word)
  13507. break;
  13508. from = prev;
  13509. }
  13510. while (to < line.length) {
  13511. let next = findClusterBreak(line.text, to);
  13512. if (check(line.text.slice(to, next)) != CharCategory.Word)
  13513. break;
  13514. to = next;
  13515. }
  13516. return from == to ? null : line.text.slice(from, to);
  13517. }
  13518. const matchDeco = Decoration.mark({ class: themeClass("selectionMatch") });
  13519. const mainMatchDeco = Decoration.mark({ class: themeClass("selectionMatch.main") });
  13520. const matchHighlighter = ViewPlugin.fromClass(class {
  13521. constructor(view) {
  13522. this.decorations = this.getDeco(view);
  13523. }
  13524. update(update) {
  13525. if (update.selectionSet || update.docChanged || update.viewportChanged)
  13526. this.decorations = this.getDeco(update.view);
  13527. }
  13528. getDeco(view) {
  13529. let conf = view.state.facet(highlightConfig);
  13530. let { state } = view, sel = state.selection;
  13531. if (sel.ranges.length > 1)
  13532. return Decoration.none;
  13533. let range = sel.main, query, check = null;
  13534. if (range.empty) {
  13535. if (!conf.highlightWordAroundCursor)
  13536. return Decoration.none;
  13537. check = state.charCategorizer(range.head);
  13538. query = wordAt(state.doc, range.head, check);
  13539. if (!query)
  13540. return Decoration.none;
  13541. }
  13542. else {
  13543. let len = range.to - range.from;
  13544. if (len < conf.minSelectionLength || len > 200)
  13545. return Decoration.none;
  13546. query = state.sliceDoc(range.from, range.to).trim();
  13547. if (!query)
  13548. return Decoration.none;
  13549. }
  13550. let deco = [];
  13551. for (let part of view.visibleRanges) {
  13552. let cursor = new SearchCursor(state.doc, query, part.from, part.to);
  13553. while (!cursor.next().done) {
  13554. let { from, to } = cursor.value;
  13555. if (!check || ((from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) &&
  13556. (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word))) {
  13557. if (check && from <= range.from && to >= range.to)
  13558. deco.push(mainMatchDeco.range(from, to));
  13559. else if (from >= range.to || to <= range.from)
  13560. deco.push(matchDeco.range(from, to));
  13561. if (deco.length > conf.maxMatches)
  13562. return Decoration.none;
  13563. }
  13564. }
  13565. }
  13566. return Decoration.set(deco);
  13567. }
  13568. }, {
  13569. decorations: v => v.decorations
  13570. });
  13571. const defaultTheme = EditorView.baseTheme({
  13572. "$selectionMatch": { backgroundColor: "#99ff7780" },
  13573. "$searchMatch $selectionMatch": { backgroundColor: "transparent" }
  13574. });
  13575. class Query {
  13576. constructor(search, replace, caseInsensitive) {
  13577. this.search = search;
  13578. this.replace = replace;
  13579. this.caseInsensitive = caseInsensitive;
  13580. }
  13581. eq(other) {
  13582. return this.search == other.search && this.replace == other.replace && this.caseInsensitive == other.caseInsensitive;
  13583. }
  13584. cursor(doc, from = 0, to = doc.length) {
  13585. return new SearchCursor(doc, this.search, from, to, this.caseInsensitive ? x => x.toLowerCase() : undefined);
  13586. }
  13587. get valid() { return !!this.search; }
  13588. }
  13589. const setQuery = StateEffect.define();
  13590. const togglePanel = StateEffect.define();
  13591. const searchState = StateField.define({
  13592. create() {
  13593. return new SearchState(new Query("", "", false), []);
  13594. },
  13595. update(value, tr) {
  13596. for (let effect of tr.effects) {
  13597. if (effect.is(setQuery))
  13598. value = new SearchState(effect.value, value.panel);
  13599. else if (effect.is(togglePanel))
  13600. value = new SearchState(value.query, effect.value ? [createSearchPanel] : []);
  13601. }
  13602. return value;
  13603. },
  13604. provide: f => showPanel.computeN([f], s => s.field(f).panel)
  13605. });
  13606. class SearchState {
  13607. constructor(query, panel) {
  13608. this.query = query;
  13609. this.panel = panel;
  13610. }
  13611. }
  13612. const matchMark = Decoration.mark({ class: themeClass("searchMatch") }), selectedMatchMark = Decoration.mark({ class: themeClass("searchMatch.selected") });
  13613. const searchHighlighter = ViewPlugin.fromClass(class {
  13614. constructor(view) {
  13615. this.view = view;
  13616. this.decorations = this.highlight(view.state.field(searchState));
  13617. }
  13618. update(update) {
  13619. let state = update.state.field(searchState);
  13620. if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet)
  13621. this.decorations = this.highlight(state);
  13622. }
  13623. highlight({ query, panel }) {
  13624. if (!panel.length || !query.valid)
  13625. return Decoration.none;
  13626. let state = this.view.state, viewport = this.view.viewport;
  13627. let cursor = query.cursor(state.doc, Math.max(0, viewport.from - query.search.length), Math.min(viewport.to + query.search.length, state.doc.length));
  13628. let builder = new RangeSetBuilder();
  13629. while (!cursor.next().done) {
  13630. let { from, to } = cursor.value;
  13631. let selected = state.selection.ranges.some(r => r.from == from && r.to == to);
  13632. builder.add(from, to, selected ? selectedMatchMark : matchMark);
  13633. }
  13634. return builder.finish();
  13635. }
  13636. }, {
  13637. decorations: v => v.decorations
  13638. });
  13639. function searchCommand(f) {
  13640. return view => {
  13641. let state = view.state.field(searchState, false);
  13642. return state && state.query.valid ? f(view, state) : openSearchPanel(view);
  13643. };
  13644. }
  13645. function findNextMatch(doc, from, query) {
  13646. let cursor = query.cursor(doc, from).next();
  13647. if (cursor.done) {
  13648. cursor = query.cursor(doc, 0, from + query.search.length - 1).next();
  13649. if (cursor.done)
  13650. return null;
  13651. }
  13652. return cursor.value;
  13653. }
  13654. /// Open the search panel if it isn't already open, and move the
  13655. /// selection to the first match after the current main selection.
  13656. /// Will wrap around to the start of the document when it reaches the
  13657. /// end.
  13658. const findNext = searchCommand((view, state) => {
  13659. let { from, to } = view.state.selection.main;
  13660. let next = findNextMatch(view.state.doc, view.state.selection.main.from + 1, state.query);
  13661. if (!next || next.from == from && next.to == to)
  13662. return false;
  13663. view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
  13664. maybeAnnounceMatch(view);
  13665. return true;
  13666. });
  13667. const FindPrevChunkSize = 10000;
  13668. // Searching in reverse is, rather than implementing inverted search
  13669. // cursor, done by scanning chunk after chunk forward.
  13670. function findPrevInRange(query, doc, from, to) {
  13671. for (let pos = to;;) {
  13672. let start = Math.max(from, pos - FindPrevChunkSize - query.search.length);
  13673. let cursor = query.cursor(doc, start, pos), range = null;
  13674. while (!cursor.next().done)
  13675. range = cursor.value;
  13676. if (range)
  13677. return range;
  13678. if (start == from)
  13679. return null;
  13680. pos -= FindPrevChunkSize;
  13681. }
  13682. }
  13683. /// Move the selection to the previous instance of the search query,
  13684. /// before the current main selection. Will wrap past the start
  13685. /// of the document to start searching at the end again.
  13686. const findPrevious = searchCommand((view, { query }) => {
  13687. let { state } = view;
  13688. let range = findPrevInRange(query, state.doc, 0, state.selection.main.to - 1) ||
  13689. findPrevInRange(query, state.doc, state.selection.main.from + 1, state.doc.length);
  13690. if (!range)
  13691. return false;
  13692. view.dispatch({ selection: { anchor: range.from, head: range.to }, scrollIntoView: true });
  13693. maybeAnnounceMatch(view);
  13694. return true;
  13695. });
  13696. /// Select all instances of the search query.
  13697. const selectMatches = searchCommand((view, { query }) => {
  13698. let cursor = query.cursor(view.state.doc), ranges = [];
  13699. while (!cursor.next().done)
  13700. ranges.push(EditorSelection.range(cursor.value.from, cursor.value.to));
  13701. if (!ranges.length)
  13702. return false;
  13703. view.dispatch({ selection: EditorSelection.create(ranges) });
  13704. return true;
  13705. });
  13706. /// Select all instances of the currently selected text.
  13707. const selectSelectionMatches = ({ state, dispatch }) => {
  13708. let sel = state.selection;
  13709. if (sel.ranges.length > 1 || sel.main.empty)
  13710. return false;
  13711. let { from, to } = sel.main;
  13712. let ranges = [], main = 0;
  13713. for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) {
  13714. if (ranges.length > 1000)
  13715. return false;
  13716. if (cur.value.from == from)
  13717. main = ranges.length;
  13718. ranges.push(EditorSelection.range(cur.value.from, cur.value.to));
  13719. }
  13720. dispatch(state.update({ selection: EditorSelection.create(ranges, main) }));
  13721. return true;
  13722. };
  13723. /// Replace the current match of the search query.
  13724. const replaceNext = searchCommand((view, { query }) => {
  13725. let { state } = view, next = findNextMatch(state.doc, state.selection.main.from, query);
  13726. if (!next)
  13727. return false;
  13728. let { from, to } = state.selection.main, changes = [], selection;
  13729. if (next.from == from && next.to == to) {
  13730. changes.push({ from: next.from, to: next.to, insert: query.replace });
  13731. next = findNextMatch(state.doc, next.to, query);
  13732. }
  13733. if (next) {
  13734. let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - query.replace.length;
  13735. selection = { anchor: next.from - off, head: next.to - off };
  13736. }
  13737. view.dispatch({ changes, selection, scrollIntoView: !!selection });
  13738. if (next)
  13739. maybeAnnounceMatch(view);
  13740. return true;
  13741. });
  13742. /// Replace all instances of the search query with the given
  13743. /// replacement.
  13744. const replaceAll = searchCommand((view, { query }) => {
  13745. let cursor = query.cursor(view.state.doc), changes = [];
  13746. while (!cursor.next().done) {
  13747. let { from, to } = cursor.value;
  13748. changes.push({ from, to, insert: query.replace });
  13749. }
  13750. if (!changes.length)
  13751. return false;
  13752. view.dispatch({ changes });
  13753. return true;
  13754. });
  13755. function createSearchPanel(view) {
  13756. let { query } = view.state.field(searchState);
  13757. return {
  13758. dom: buildPanel({
  13759. view,
  13760. query,
  13761. updateQuery(q) {
  13762. if (!query.eq(q)) {
  13763. query = q;
  13764. view.dispatch({ effects: setQuery.of(query) });
  13765. }
  13766. }
  13767. }),
  13768. mount() {
  13769. this.dom.querySelector("[name=search]").select();
  13770. },
  13771. pos: 80,
  13772. style: "search"
  13773. };
  13774. }
  13775. /// Make sure the search panel is open and focused.
  13776. const openSearchPanel = view => {
  13777. let state = view.state.field(searchState, false);
  13778. if (state && state.panel.length) {
  13779. let panel = getPanel(view, createSearchPanel);
  13780. if (!panel)
  13781. return false;
  13782. panel.dom.querySelector("[name=search]").focus();
  13783. }
  13784. else {
  13785. view.dispatch({ effects: togglePanel.of(true),
  13786. reconfigure: state ? undefined : { append: searchExtensions } });
  13787. }
  13788. return true;
  13789. };
  13790. /// Close the search panel.
  13791. const closeSearchPanel = view => {
  13792. let state = view.state.field(searchState, false);
  13793. if (!state || !state.panel.length)
  13794. return false;
  13795. let panel = getPanel(view, createSearchPanel);
  13796. if (panel && panel.dom.contains(view.root.activeElement))
  13797. view.focus();
  13798. view.dispatch({ effects: togglePanel.of(false) });
  13799. return true;
  13800. };
  13801. /// Default search-related key bindings.
  13802. ///
  13803. /// - Mod-f: [`openSearchPanel`](#search.openSearchPanel)
  13804. /// - F3, Mod-g: [`findNext`](#search.findNext)
  13805. /// - Shift-F3, Shift-Mod-g: [`findPrevious`](#search.findPrevious)
  13806. /// - Alt-g: [`gotoLine`](#search.gotoLine)
  13807. const searchKeymap = [
  13808. { key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" },
  13809. { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel" },
  13810. { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel" },
  13811. { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" },
  13812. { key: "Mod-Shift-l", run: selectSelectionMatches },
  13813. { key: "Alt-g", run: gotoLine }
  13814. ];
  13815. function buildPanel(conf) {
  13816. function p(phrase) { return conf.view.state.phrase(phrase); }
  13817. let searchField = crelt("input", {
  13818. value: conf.query.search,
  13819. placeholder: p("Find"),
  13820. "aria-label": p("Find"),
  13821. class: themeClass("textfield"),
  13822. name: "search",
  13823. onchange: update,
  13824. onkeyup: update
  13825. });
  13826. let replaceField = crelt("input", {
  13827. value: conf.query.replace,
  13828. placeholder: p("Replace"),
  13829. "aria-label": p("Replace"),
  13830. class: themeClass("textfield"),
  13831. name: "replace",
  13832. onchange: update,
  13833. onkeyup: update
  13834. });
  13835. let caseField = crelt("input", {
  13836. type: "checkbox",
  13837. name: "case",
  13838. checked: !conf.query.caseInsensitive,
  13839. onchange: update
  13840. });
  13841. function update() {
  13842. conf.updateQuery(new Query(searchField.value, replaceField.value, !caseField.checked));
  13843. }
  13844. function keydown(e) {
  13845. if (runScopeHandlers(conf.view, e, "search-panel")) {
  13846. e.preventDefault();
  13847. }
  13848. else if (e.keyCode == 13 && e.target == searchField) {
  13849. e.preventDefault();
  13850. (e.shiftKey ? findPrevious : findNext)(conf.view);
  13851. }
  13852. else if (e.keyCode == 13 && e.target == replaceField) {
  13853. e.preventDefault();
  13854. replaceNext(conf.view);
  13855. }
  13856. }
  13857. function button(name, onclick, content) {
  13858. return crelt("button", { class: themeClass("button"), name, onclick }, content);
  13859. }
  13860. let panel = crelt("div", { onkeydown: keydown }, [
  13861. searchField,
  13862. button("next", () => findNext(conf.view), [p("next")]),
  13863. button("prev", () => findPrevious(conf.view), [p("previous")]),
  13864. button("select", () => selectMatches(conf.view), [p("all")]),
  13865. crelt("label", null, [caseField, "match case"]),
  13866. crelt("br"),
  13867. replaceField,
  13868. button("replace", () => replaceNext(conf.view), [p("replace")]),
  13869. button("replaceAll", () => replaceAll(conf.view), [p("replace all")]),
  13870. crelt("button", { name: "close", onclick: () => closeSearchPanel(conf.view), "aria-label": p("close") }, ["×"]),
  13871. crelt("div", { style: "position: absolute; top: -10000px", "aria-live": "polite" })
  13872. ]);
  13873. return panel;
  13874. }
  13875. const AnnounceMargin = 30;
  13876. const Break = /[\s\.,:;?!]/;
  13877. // FIXME this is a kludge
  13878. function maybeAnnounceMatch(view) {
  13879. let { from, to } = view.state.selection.main;
  13880. let lineStart = view.state.doc.lineAt(from).from, lineEnd = view.state.doc.lineAt(to).to;
  13881. let start = Math.max(lineStart, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin);
  13882. let text = view.state.sliceDoc(start, end);
  13883. if (start != lineStart) {
  13884. for (let i = 0; i < AnnounceMargin; i++)
  13885. if (!Break.test(text[i + 1]) && Break.test(text[i])) {
  13886. text = text.slice(i);
  13887. break;
  13888. }
  13889. }
  13890. if (end != lineEnd) {
  13891. for (let i = text.length - 1; i > text.length - AnnounceMargin; i--)
  13892. if (!Break.test(text[i - 1]) && Break.test(text[i])) {
  13893. text = text.slice(0, i);
  13894. break;
  13895. }
  13896. }
  13897. let panel = getPanel(view, createSearchPanel);
  13898. if (!panel || !panel.dom.contains(view.root.activeElement))
  13899. return;
  13900. let live = panel.dom.querySelector("div[aria-live]");
  13901. live.textContent = view.state.phrase("current match") + ". " + text;
  13902. }
  13903. const baseTheme$1$1 = EditorView.baseTheme({
  13904. "$panel.search": {
  13905. padding: "2px 6px 4px",
  13906. position: "relative",
  13907. "& [name=close]": {
  13908. position: "absolute",
  13909. top: "0",
  13910. right: "4px",
  13911. backgroundColor: "inherit",
  13912. border: "none",
  13913. font: "inherit",
  13914. padding: 0,
  13915. margin: 0
  13916. },
  13917. "& input, & button": {
  13918. margin: ".2em .5em .2em 0"
  13919. },
  13920. "& label": {
  13921. fontSize: "80%"
  13922. }
  13923. },
  13924. "$$light $searchMatch": { backgroundColor: "#ffff0054" },
  13925. "$$dark $searchMatch": { backgroundColor: "#00ffff8a" },
  13926. "$$light $searchMatch.selected": { backgroundColor: "#ff6a0054" },
  13927. "$$dark $searchMatch.selected": { backgroundColor: "#ff00ff8a" }
  13928. });
  13929. const searchExtensions = [
  13930. searchState,
  13931. Prec.override(searchHighlighter),
  13932. panels(),
  13933. baseTheme$1$1
  13934. ];
  13935. const ios = typeof navigator != "undefined" &&
  13936. !/Edge\/(\d+)/.exec(navigator.userAgent) && /Apple Computer/.test(navigator.vendor) &&
  13937. (/Mobile\/\w+/.test(navigator.userAgent) || navigator.maxTouchPoints > 2);
  13938. const Outside = "-10000px";
  13939. const tooltipPlugin = ViewPlugin.fromClass(class {
  13940. constructor(view) {
  13941. this.view = view;
  13942. this.inView = true;
  13943. this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this };
  13944. this.tooltips = view.state.facet(showTooltip);
  13945. this.tooltipViews = this.tooltips.map(tp => this.createTooltip(tp));
  13946. }
  13947. update(update) {
  13948. let tooltips = update.state.facet(showTooltip);
  13949. if (tooltips == this.tooltips) {
  13950. for (let t of this.tooltipViews)
  13951. if (t.update)
  13952. t.update(update);
  13953. }
  13954. else {
  13955. let views = [];
  13956. for (let i = 0; i < tooltips.length; i++) {
  13957. let tip = tooltips[i], known = -1;
  13958. for (let i = 0; i < this.tooltips.length; i++)
  13959. if (this.tooltips[i].create == tip.create)
  13960. known = i;
  13961. if (known < 0) {
  13962. views[i] = this.createTooltip(tip);
  13963. }
  13964. else {
  13965. let tooltipView = views[i] = this.tooltipViews[known];
  13966. if (tooltipView.update)
  13967. tooltipView.update(update);
  13968. }
  13969. }
  13970. for (let t of this.tooltipViews)
  13971. if (views.indexOf(t) < 0)
  13972. t.dom.remove();
  13973. this.tooltips = tooltips;
  13974. this.tooltipViews = views;
  13975. this.maybeMeasure();
  13976. }
  13977. }
  13978. createTooltip(tooltip) {
  13979. let tooltipView = tooltip.create(this.view);
  13980. tooltipView.dom.className = themeClass("tooltip" + (tooltip.style ? "." + tooltip.style : ""));
  13981. this.view.dom.appendChild(tooltipView.dom);
  13982. if (tooltipView.mount)
  13983. tooltipView.mount(this.view);
  13984. return tooltipView;
  13985. }
  13986. destroy() {
  13987. for (let { dom } of this.tooltipViews)
  13988. dom.remove();
  13989. }
  13990. readMeasure() {
  13991. return {
  13992. editor: this.view.dom.getBoundingClientRect(),
  13993. pos: this.tooltips.map(t => this.view.coordsAtPos(t.pos)),
  13994. size: this.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()),
  13995. innerWidth: window.innerWidth,
  13996. innerHeight: window.innerHeight
  13997. };
  13998. }
  13999. writeMeasure(measured) {
  14000. let { editor } = measured;
  14001. for (let i = 0; i < this.tooltipViews.length; i++) {
  14002. let tooltip = this.tooltips[i], tView = this.tooltipViews[i], { dom } = tView;
  14003. let pos = measured.pos[i], size = measured.size[i];
  14004. // Hide tooltips that are outside of the editor.
  14005. if (!pos || pos.bottom <= editor.top || pos.top >= editor.bottom || pos.right <= editor.left || pos.left >= editor.right) {
  14006. dom.style.top = Outside;
  14007. continue;
  14008. }
  14009. let width = size.right - size.left, height = size.bottom - size.top;
  14010. let left = this.view.textDirection == Direction.LTR ? Math.min(pos.left, measured.innerWidth - width)
  14011. : Math.max(0, pos.left - width);
  14012. let above = !!tooltip.above;
  14013. if (!tooltip.strictSide &&
  14014. (above ? pos.top - (size.bottom - size.top) < 0 : pos.bottom + (size.bottom - size.top) > measured.innerHeight))
  14015. above = !above;
  14016. if (ios) {
  14017. dom.style.top = ((above ? pos.top - height : pos.bottom) - editor.top) + "px";
  14018. dom.style.left = (left - editor.left) + "px";
  14019. dom.style.position = "absolute";
  14020. }
  14021. else {
  14022. dom.style.top = (above ? pos.top - height : pos.bottom) + "px";
  14023. dom.style.left = left + "px";
  14024. }
  14025. dom.classList.toggle("cm-tooltip-above", above);
  14026. dom.classList.toggle("cm-tooltip-below", !above);
  14027. if (tView.positioned)
  14028. tView.positioned();
  14029. }
  14030. }
  14031. maybeMeasure() {
  14032. if (this.tooltips.length) {
  14033. if (this.view.inView || this.inView)
  14034. this.view.requestMeasure(this.measureReq);
  14035. this.inView = this.view.inView;
  14036. }
  14037. }
  14038. }, {
  14039. eventHandlers: {
  14040. scroll() { this.maybeMeasure(); }
  14041. }
  14042. });
  14043. const baseTheme$6 = EditorView.baseTheme({
  14044. $tooltip: {
  14045. position: "fixed",
  14046. border: "1px solid #ddd",
  14047. backgroundColor: "#f5f5f5",
  14048. zIndex: 100
  14049. }
  14050. });
  14051. /// Supporting extension for displaying tooltips. Allows
  14052. /// [`showTooltip`](#tooltip.showTooltip) to be used to create
  14053. /// tooltips.
  14054. function tooltips() {
  14055. return [tooltipPlugin, baseTheme$6];
  14056. }
  14057. /// Behavior by which an extension can provide a tooltip to be shown.
  14058. const showTooltip = Facet.define();
  14059. const HoverTime = 750, HoverMaxDist = 10;
  14060. class HoverPlugin {
  14061. constructor(view, source, field, setHover) {
  14062. this.view = view;
  14063. this.source = source;
  14064. this.field = field;
  14065. this.setHover = setHover;
  14066. this.lastMouseMove = null;
  14067. this.hoverTimeout = -1;
  14068. this.checkHover = this.checkHover.bind(this);
  14069. view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
  14070. view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
  14071. }
  14072. get active() {
  14073. return this.view.state.field(this.field);
  14074. }
  14075. checkHover() {
  14076. this.hoverTimeout = -1;
  14077. if (this.active)
  14078. return;
  14079. let now = Date.now(), lastMove = this.lastMouseMove;
  14080. if (now - lastMove.timeStamp < HoverTime) {
  14081. this.hoverTimeout = setTimeout(this.checkHover, HoverTime - (now - lastMove.timeStamp));
  14082. return;
  14083. }
  14084. let coords = { x: lastMove.clientX, y: lastMove.clientY };
  14085. let pos = this.view.contentDOM.contains(lastMove.target)
  14086. ? this.view.posAtCoords(coords) : null;
  14087. if (pos == null)
  14088. return;
  14089. let posCoords = this.view.coordsAtPos(pos);
  14090. if (posCoords == null || coords.y < posCoords.top || coords.y > posCoords.bottom ||
  14091. coords.x < posCoords.left - this.view.defaultCharacterWidth ||
  14092. coords.x > posCoords.right + this.view.defaultCharacterWidth)
  14093. return;
  14094. let bidi = this.view.bidiSpans(this.view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
  14095. let rtl = bidi && bidi.dir == Direction.RTL ? -1 : 1;
  14096. let open = this.source(this.view, pos, (coords.x < posCoords.left ? -rtl : rtl));
  14097. if (open)
  14098. this.view.dispatch({ effects: this.setHover.of(open) });
  14099. }
  14100. mousemove(event) {
  14101. var _a;
  14102. this.lastMouseMove = event;
  14103. if (this.hoverTimeout < 0)
  14104. this.hoverTimeout = setTimeout(this.checkHover, HoverTime);
  14105. let tooltip = this.active;
  14106. if (tooltip && !isInTooltip(event.target)) {
  14107. let { pos } = tooltip, end = (_a = tooltip.end) !== null && _a !== void 0 ? _a : pos;
  14108. if ((pos == end ? this.view.posAtCoords({ x: event.clientX, y: event.clientY }) != pos
  14109. : !isOverRange(this.view, pos, end, event.clientX, event.clientY, HoverMaxDist)))
  14110. this.view.dispatch({ effects: this.setHover.of(null) });
  14111. }
  14112. }
  14113. mouseleave() {
  14114. clearTimeout(this.hoverTimeout);
  14115. this.hoverTimeout = -1;
  14116. if (this.active)
  14117. this.view.dispatch({ effects: this.setHover.of(null) });
  14118. }
  14119. destroy() {
  14120. clearTimeout(this.hoverTimeout);
  14121. this.view.dom.removeEventListener("mouseleave", this.mouseleave);
  14122. this.view.dom.removeEventListener("mousemove", this.mousemove);
  14123. }
  14124. }
  14125. function isInTooltip(elt) {
  14126. for (let cur = elt; cur; cur = cur.parentNode)
  14127. if (cur.nodeType == 1 && cur.classList.contains("cm-tooltip"))
  14128. return true;
  14129. return false;
  14130. }
  14131. function isOverRange(view, from, to, x, y, margin) {
  14132. let range = document.createRange();
  14133. let fromDOM = view.domAtPos(from), toDOM = view.domAtPos(to);
  14134. range.setEnd(toDOM.node, toDOM.offset);
  14135. range.setStart(fromDOM.node, fromDOM.offset);
  14136. let rects = range.getClientRects();
  14137. range.detach();
  14138. for (let i = 0; i < rects.length; i++) {
  14139. let rect = rects[i];
  14140. let dist = Math.max(rect.top - y, y - rect.bottom, rect.left - x, x - rect.right);
  14141. if (dist <= margin)
  14142. return true;
  14143. }
  14144. return false;
  14145. }
  14146. /// Enable a hover tooltip, which shows up when the pointer hovers
  14147. /// over ranges of text. The callback is called when the mouse overs
  14148. /// over the document text. It should, if there is a tooltip
  14149. /// associated with position `pos` return the tooltip description. The
  14150. /// `side` argument indicates on which side of the position the
  14151. /// pointer is—it will be -1 if the pointer is before
  14152. /// the position, 1 if after the position.
  14153. function hoverTooltip(source, options = {}) {
  14154. const setHover = StateEffect.define();
  14155. const hoverState = StateField.define({
  14156. create() { return null; },
  14157. update(value, tr) {
  14158. if (value && (options.hideOnChange && (tr.docChanged || tr.selection)))
  14159. return null;
  14160. for (let effect of tr.effects)
  14161. if (effect.is(setHover))
  14162. return effect.value;
  14163. if (value && tr.docChanged) {
  14164. let newPos = tr.changes.mapPos(value.pos, -1, MapMode.TrackDel);
  14165. if (newPos == null)
  14166. return null;
  14167. let copy = Object.assign(Object.create(null), value);
  14168. copy.pos = newPos;
  14169. if (value.end != null)
  14170. copy.end = tr.changes.mapPos(value.end);
  14171. return copy;
  14172. }
  14173. return value;
  14174. },
  14175. provide: f => showTooltip.computeN([f], s => { let val = s.field(f); return val ? [val] : []; })
  14176. });
  14177. return [
  14178. hoverState,
  14179. ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover)),
  14180. tooltips()
  14181. ];
  14182. }
  14183. /// An instance of this is passed to completion source functions.
  14184. class CompletionContext {
  14185. /// Create a new completion context. (Mostly useful for testing
  14186. /// completion sources—in the editor, the extension will create
  14187. /// these for you.)
  14188. constructor(
  14189. /// The editor state that the completion happens in.
  14190. state,
  14191. /// The position at which the completion is happening.
  14192. pos,
  14193. /// Indicates whether completion was activated explicitly, or
  14194. /// implicitly by typing. The usual way to respond to this is to
  14195. /// only return completions when either there is part of a
  14196. /// completable entity before the cursor, or `explicit` is true.
  14197. explicit) {
  14198. this.state = state;
  14199. this.pos = pos;
  14200. this.explicit = explicit;
  14201. /// @internal
  14202. this.abortListeners = [];
  14203. }
  14204. /// Get the extent, content, and (if there is a token) type of the
  14205. /// token before `this.pos`.
  14206. tokenBefore(types) {
  14207. let token = syntaxTree(this.state).resolve(this.pos, -1);
  14208. while (token && types.indexOf(token.name) < 0)
  14209. token = token.parent;
  14210. return token ? { from: token.from, to: this.pos,
  14211. text: this.state.sliceDoc(token.from, this.pos),
  14212. type: token.type } : null;
  14213. }
  14214. /// Get the match of the given expression directly before the
  14215. /// cursor.
  14216. matchBefore(expr) {
  14217. let line = this.state.doc.lineAt(this.pos);
  14218. let start = Math.max(line.from, this.pos - 250);
  14219. let str = line.text.slice(start - line.from, this.pos - line.from);
  14220. let found = str.search(ensureAnchor(expr, false));
  14221. return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
  14222. }
  14223. /// Yields true when the query has been aborted. Can be useful in
  14224. /// asynchronous queries to avoid doing work that will be ignored.
  14225. get aborted() { return this.abortListeners == null; }
  14226. /// Allows you to register abort handlers, which will be called when
  14227. /// the query is
  14228. /// [aborted](#autocomplete.CompletionContext.aborted).
  14229. addEventListener(type, listener) {
  14230. if (type == "abort" && this.abortListeners)
  14231. this.abortListeners.push(listener);
  14232. }
  14233. }
  14234. function toSet(chars) {
  14235. let flat = Object.keys(chars).join("");
  14236. let words = /\w/.test(flat);
  14237. if (words)
  14238. flat = flat.replace(/\w/g, "");
  14239. return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
  14240. }
  14241. function prefixMatch(options) {
  14242. let first = Object.create(null), rest = Object.create(null);
  14243. for (let { label } of options) {
  14244. first[label[0]] = true;
  14245. for (let i = 1; i < label.length; i++)
  14246. rest[label[i]] = true;
  14247. }
  14248. let source = toSet(first) + toSet(rest) + "*$";
  14249. return [new RegExp("^" + source), new RegExp(source)];
  14250. }
  14251. /// Given a a fixed array of options, return an autocompleter that
  14252. /// completes them.
  14253. function completeFromList(list) {
  14254. let options = list.map(o => typeof o == "string" ? { label: o } : o);
  14255. let [span, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
  14256. return (context) => {
  14257. let token = context.matchBefore(match);
  14258. return token || context.explicit ? { from: token ? token.from : context.pos, options, span } : null;
  14259. };
  14260. }
  14261. class Option {
  14262. constructor(completion, source, match) {
  14263. this.completion = completion;
  14264. this.source = source;
  14265. this.match = match;
  14266. }
  14267. }
  14268. function cur(state) { return state.selection.main.head; }
  14269. // Make sure the given regexp has a $ at its end and, if `start` is
  14270. // true, a ^ at its start.
  14271. function ensureAnchor(expr, start) {
  14272. var _a;
  14273. let { source } = expr;
  14274. let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
  14275. if (!addStart && !addEnd)
  14276. return expr;
  14277. return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : ""));
  14278. }
  14279. function applyCompletion(view, option) {
  14280. let apply = option.completion.apply || option.completion.label;
  14281. let result = option.source;
  14282. if (typeof apply == "string") {
  14283. view.dispatch({
  14284. changes: { from: result.from, to: result.to, insert: apply },
  14285. selection: { anchor: result.from + apply.length }
  14286. });
  14287. }
  14288. else {
  14289. apply(view, option.completion, result.from, result.to);
  14290. }
  14291. }
  14292. const SourceCache = new WeakMap();
  14293. function asSource(source) {
  14294. if (!Array.isArray(source))
  14295. return source;
  14296. let known = SourceCache.get(source);
  14297. if (!known)
  14298. SourceCache.set(source, known = completeFromList(source));
  14299. return known;
  14300. }
  14301. // A pattern matcher for fuzzy completion matching. Create an instance
  14302. // once for a pattern, and then use that to match any number of
  14303. // completions.
  14304. class FuzzyMatcher {
  14305. constructor(pattern) {
  14306. this.pattern = pattern;
  14307. this.chars = [];
  14308. this.folded = [];
  14309. // Buffers reused by calls to `match` to track matched character
  14310. // positions.
  14311. this.any = [];
  14312. this.precise = [];
  14313. this.byWord = [];
  14314. for (let p = 0; p < pattern.length;) {
  14315. let char = codePointAt(pattern, p), size = codePointSize(char);
  14316. this.chars.push(char);
  14317. let part = pattern.slice(p, p + size), upper = part.toUpperCase();
  14318. this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
  14319. p += size;
  14320. }
  14321. this.astral = pattern.length != this.chars.length;
  14322. }
  14323. // Matches a given word (completion) against the pattern (input).
  14324. // Will return null for no match, and otherwise an array that starts
  14325. // with the match score, followed by any number of `from, to` pairs
  14326. // indicating the matched parts of `word`.
  14327. //
  14328. // The score is a number that is more negative the worse the match
  14329. // is. See `Penalty` above.
  14330. match(word) {
  14331. if (this.pattern.length == 0)
  14332. return [0];
  14333. if (word.length < this.pattern.length)
  14334. return null;
  14335. let { chars, folded, any, precise, byWord } = this;
  14336. // For single-character queries, only match when they occur right
  14337. // at the start
  14338. if (chars.length == 1) {
  14339. let first = codePointAt(word, 0);
  14340. return first == chars[0] ? [0, 0, codePointSize(first)]
  14341. : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;
  14342. }
  14343. let direct = word.indexOf(this.pattern);
  14344. if (direct == 0)
  14345. return [0, 0, this.pattern.length];
  14346. let len = chars.length, anyTo = 0;
  14347. if (direct < 0) {
  14348. for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
  14349. let next = codePointAt(word, i);
  14350. if (next == chars[anyTo] || next == folded[anyTo])
  14351. any[anyTo++] = i;
  14352. i += codePointSize(next);
  14353. }
  14354. // No match, exit immediately
  14355. if (anyTo < len)
  14356. return null;
  14357. }
  14358. let preciseTo = 0;
  14359. let byWordTo = 0, byWordFolded = false;
  14360. let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
  14361. for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {
  14362. let next = codePointAt(word, i);
  14363. if (direct < 0) {
  14364. if (preciseTo < len && next == chars[preciseTo])
  14365. precise[preciseTo++] = i;
  14366. if (adjacentTo < len) {
  14367. if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
  14368. if (adjacentTo == 0)
  14369. adjacentStart = i;
  14370. adjacentEnd = i;
  14371. adjacentTo++;
  14372. }
  14373. else {
  14374. adjacentTo = 0;
  14375. }
  14376. }
  14377. }
  14378. let ch, type = next < 0xff
  14379. ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)
  14380. : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);
  14381. if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&
  14382. (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))
  14383. byWord[byWordTo++] = i;
  14384. prevType = type;
  14385. i += codePointSize(next);
  14386. }
  14387. if (byWordTo == len && byWord[0] == 0)
  14388. return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);
  14389. if (adjacentTo == len && adjacentStart == 0)
  14390. return [-200 /* CaseFold */, 0, adjacentEnd];
  14391. if (direct > -1)
  14392. return [-700 /* NotStart */, direct, direct + this.pattern.length];
  14393. if (adjacentTo == len)
  14394. return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];
  14395. if (byWordTo == len)
  14396. return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);
  14397. return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);
  14398. }
  14399. result(score, positions, word) {
  14400. let result = [score], i = 1;
  14401. for (let pos of positions) {
  14402. let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
  14403. if (i > 1 && result[i - 1] == pos)
  14404. result[i - 1] = to;
  14405. else {
  14406. result[i++] = pos;
  14407. result[i++] = to;
  14408. }
  14409. }
  14410. return result;
  14411. }
  14412. }
  14413. const completionConfig = Facet.define({
  14414. combine(configs) {
  14415. return combineConfig(configs, {
  14416. activateOnTyping: true,
  14417. override: null,
  14418. maxRenderedOptions: 100,
  14419. defaultKeymap: true
  14420. }, {
  14421. defaultKeymap: (a, b) => a && b
  14422. });
  14423. }
  14424. });
  14425. const MaxInfoWidth = 300;
  14426. const baseTheme$7 = EditorView.baseTheme({
  14427. "$tooltip.autocomplete": {
  14428. "& > ul": {
  14429. fontFamily: "monospace",
  14430. overflowY: "auto",
  14431. whiteSpace: "nowrap",
  14432. maxHeight: "10em",
  14433. listStyle: "none",
  14434. margin: 0,
  14435. padding: 0,
  14436. "& > li": {
  14437. cursor: "pointer",
  14438. padding: "1px 1em 1px 3px",
  14439. lineHeight: 1.2
  14440. },
  14441. "& > li[aria-selected]": {
  14442. background_fallback: "#bdf",
  14443. backgroundColor: "Highlight",
  14444. color_fallback: "white",
  14445. color: "HighlightText"
  14446. }
  14447. }
  14448. },
  14449. "$completionListIncompleteTop:before, $completionListIncompleteBottom:after": {
  14450. content: '"···"',
  14451. opacity: 0.5,
  14452. display: "block",
  14453. textAlign: "center"
  14454. },
  14455. "$tooltip.completionInfo": {
  14456. position: "absolute",
  14457. padding: "3px 9px",
  14458. width: "max-content",
  14459. maxWidth: MaxInfoWidth + "px",
  14460. },
  14461. "$tooltip.completionInfo.left": { right: "100%" },
  14462. "$tooltip.completionInfo.right": { left: "100%" },
  14463. "$$light $snippetField": { backgroundColor: "#ddd" },
  14464. "$$dark $snippetField": { backgroundColor: "#333" },
  14465. "$snippetFieldPosition": {
  14466. verticalAlign: "text-top",
  14467. width: 0,
  14468. height: "1.15em",
  14469. margin: "0 -0.7px -.7em",
  14470. borderLeft: "1.4px dotted #888"
  14471. },
  14472. $completionMatchedText: {
  14473. textDecoration: "underline"
  14474. },
  14475. $completionDetail: {
  14476. marginLeft: "0.5em",
  14477. fontStyle: "italic"
  14478. },
  14479. $completionIcon: {
  14480. fontSize: "90%",
  14481. width: ".8em",
  14482. display: "inline-block",
  14483. textAlign: "center",
  14484. paddingRight: ".6em",
  14485. opacity: "0.6"
  14486. },
  14487. "$completionIcon.function, $completionIcon.method": {
  14488. "&:after": { content: "'ƒ'" }
  14489. },
  14490. "$completionIcon.class": {
  14491. "&:after": { content: "'○'" }
  14492. },
  14493. "$completionIcon.interface": {
  14494. "&:after": { content: "'◌'" }
  14495. },
  14496. "$completionIcon.variable": {
  14497. "&:after": { content: "'𝑥'" }
  14498. },
  14499. "$completionIcon.constant": {
  14500. "&:after": { content: "'𝐶'" }
  14501. },
  14502. "$completionIcon.type": {
  14503. "&:after": { content: "'𝑡'" }
  14504. },
  14505. "$completionIcon.enum": {
  14506. "&:after": { content: "'∪'" }
  14507. },
  14508. "$completionIcon.property": {
  14509. "&:after": { content: "'□'" }
  14510. },
  14511. "$completionIcon.keyword": {
  14512. "&:after": { content: "'🔑\uFE0E'" } // Disable emoji rendering
  14513. },
  14514. "$completionIcon.namespace": {
  14515. "&:after": { content: "'▢'" }
  14516. },
  14517. "$completionIcon.text": {
  14518. "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
  14519. }
  14520. });
  14521. function createListBox(options, id, range) {
  14522. const ul = document.createElement("ul");
  14523. ul.id = id;
  14524. ul.setAttribute("role", "listbox");
  14525. ul.setAttribute("aria-expanded", "true");
  14526. for (let i = range.from; i < range.to; i++) {
  14527. let { completion, match } = options[i];
  14528. const li = ul.appendChild(document.createElement("li"));
  14529. li.id = id + "-" + i;
  14530. let icon = li.appendChild(document.createElement("div"));
  14531. icon.className = themeClass("completionIcon" + (completion.type ? "." + completion.type : ""));
  14532. icon.setAttribute("aria-hidden", "true");
  14533. let labelElt = li.appendChild(document.createElement("span"));
  14534. labelElt.className = themeClass("completionLabel");
  14535. let { label, detail } = completion, off = 0;
  14536. for (let j = 1; j < match.length;) {
  14537. let from = match[j++], to = match[j++];
  14538. if (from > off)
  14539. labelElt.appendChild(document.createTextNode(label.slice(off, from)));
  14540. let span = labelElt.appendChild(document.createElement("span"));
  14541. span.appendChild(document.createTextNode(label.slice(from, to)));
  14542. span.className = themeClass("completionMatchedText");
  14543. off = to;
  14544. }
  14545. if (off < label.length)
  14546. labelElt.appendChild(document.createTextNode(label.slice(off)));
  14547. if (detail) {
  14548. let detailElt = li.appendChild(document.createElement("span"));
  14549. detailElt.className = themeClass("completionDetail");
  14550. detailElt.textContent = detail;
  14551. }
  14552. li.setAttribute("role", "option");
  14553. }
  14554. if (range.from)
  14555. ul.classList.add(themeClass("completionListIncompleteTop"));
  14556. if (range.to < options.length)
  14557. ul.classList.add(themeClass("completionListIncompleteBottom"));
  14558. return ul;
  14559. }
  14560. function createInfoDialog(option) {
  14561. let dom = document.createElement("div");
  14562. dom.className = themeClass("tooltip.completionInfo");
  14563. let { info } = option.completion;
  14564. if (typeof info == "string")
  14565. dom.textContent = info;
  14566. else
  14567. dom.appendChild(info(option.completion));
  14568. return dom;
  14569. }
  14570. function rangeAroundSelected(total, selected, max) {
  14571. if (total <= max)
  14572. return { from: 0, to: total };
  14573. if (selected <= (total >> 1)) {
  14574. let off = Math.floor(selected / max);
  14575. return { from: off * max, to: (off + 1) * max };
  14576. }
  14577. let off = Math.floor((total - selected) / max);
  14578. return { from: total - (off + 1) * max, to: total - off * max };
  14579. }
  14580. class CompletionTooltip {
  14581. constructor(view, stateField) {
  14582. this.view = view;
  14583. this.stateField = stateField;
  14584. this.info = null;
  14585. this.placeInfo = {
  14586. read: () => this.measureInfo(),
  14587. write: (pos) => this.positionInfo(pos),
  14588. key: this
  14589. };
  14590. let cState = view.state.field(stateField);
  14591. let { options, selected } = cState.open;
  14592. let config = view.state.facet(completionConfig);
  14593. this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
  14594. this.dom = document.createElement("div");
  14595. this.dom.addEventListener("mousedown", (e) => {
  14596. for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
  14597. if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
  14598. applyCompletion(view, options[+match[1]]);
  14599. e.preventDefault();
  14600. return;
  14601. }
  14602. }
  14603. });
  14604. this.list = this.dom.appendChild(createListBox(options, cState.id, this.range));
  14605. this.list.addEventListener("scroll", () => {
  14606. if (this.info)
  14607. this.view.requestMeasure(this.placeInfo);
  14608. });
  14609. }
  14610. mount() { this.updateSel(); }
  14611. update(update) {
  14612. if (update.state.field(this.stateField) != update.startState.field(this.stateField))
  14613. this.updateSel();
  14614. }
  14615. positioned() {
  14616. if (this.info)
  14617. this.view.requestMeasure(this.placeInfo);
  14618. }
  14619. updateSel() {
  14620. let cState = this.view.state.field(this.stateField), open = cState.open;
  14621. if (open.selected < this.range.from || open.selected >= this.range.to) {
  14622. this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
  14623. this.list.remove();
  14624. this.list = this.dom.appendChild(createListBox(open.options, cState.id, this.range));
  14625. this.list.addEventListener("scroll", () => {
  14626. if (this.info)
  14627. this.view.requestMeasure(this.placeInfo);
  14628. });
  14629. }
  14630. if (this.updateSelectedOption(open.selected)) {
  14631. if (this.info) {
  14632. this.info.remove();
  14633. this.info = null;
  14634. }
  14635. let option = open.options[open.selected];
  14636. if (option.completion.info) {
  14637. this.info = this.dom.appendChild(createInfoDialog(option));
  14638. this.view.requestMeasure(this.placeInfo);
  14639. }
  14640. }
  14641. }
  14642. updateSelectedOption(selected) {
  14643. let set = null;
  14644. for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
  14645. if (i == selected) {
  14646. if (!opt.hasAttribute("aria-selected")) {
  14647. opt.setAttribute("aria-selected", "true");
  14648. set = opt;
  14649. }
  14650. }
  14651. else {
  14652. if (opt.hasAttribute("aria-selected"))
  14653. opt.removeAttribute("aria-selected");
  14654. }
  14655. }
  14656. if (set)
  14657. scrollIntoView(this.list, set);
  14658. return set;
  14659. }
  14660. measureInfo() {
  14661. let sel = this.dom.querySelector("[aria-selected]");
  14662. if (!sel)
  14663. return null;
  14664. let rect = this.dom.getBoundingClientRect();
  14665. let top = sel.getBoundingClientRect().top - rect.top;
  14666. if (top < 0 || top > this.list.clientHeight - 10)
  14667. return null;
  14668. let left = this.view.textDirection == Direction.RTL;
  14669. let spaceLeft = rect.left, spaceRight = innerWidth - rect.right;
  14670. if (left && spaceLeft < Math.min(MaxInfoWidth, spaceRight))
  14671. left = false;
  14672. else if (!left && spaceRight < Math.min(MaxInfoWidth, spaceLeft))
  14673. left = true;
  14674. return { top, left };
  14675. }
  14676. positionInfo(pos) {
  14677. if (this.info && pos) {
  14678. this.info.style.top = pos.top + "px";
  14679. this.info.classList.toggle("cm-tooltip-completionInfo-left", pos.left);
  14680. this.info.classList.toggle("cm-tooltip-completionInfo-right", !pos.left);
  14681. }
  14682. }
  14683. }
  14684. // We allocate a new function instance every time the completion
  14685. // changes to force redrawing/repositioning of the tooltip
  14686. function completionTooltip(stateField) {
  14687. return (view) => new CompletionTooltip(view, stateField);
  14688. }
  14689. function scrollIntoView(container, element) {
  14690. let parent = container.getBoundingClientRect();
  14691. let self = element.getBoundingClientRect();
  14692. if (self.top < parent.top)
  14693. container.scrollTop -= parent.top - self.top;
  14694. else if (self.bottom > parent.bottom)
  14695. container.scrollTop += self.bottom - parent.bottom;
  14696. }
  14697. const MaxOptions = 300;
  14698. // Used to pick a preferred option when two options with the same
  14699. // label occur in the result.
  14700. function score(option) {
  14701. return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +
  14702. (option.type ? 1 : 0);
  14703. }
  14704. function sortOptions(active, state) {
  14705. let options = [];
  14706. for (let a of active)
  14707. if (a.hasResult()) {
  14708. let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match;
  14709. for (let option of a.result.options)
  14710. if (match = matcher.match(option.label)) {
  14711. if (option.boost != null)
  14712. match[0] += option.boost;
  14713. options.push(new Option(option, a, match));
  14714. }
  14715. }
  14716. options.sort(cmpOption);
  14717. let result = [], prev = null;
  14718. for (let opt of options.sort(cmpOption)) {
  14719. if (result.length == MaxOptions)
  14720. break;
  14721. if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail)
  14722. result.push(opt);
  14723. else if (score(opt.completion) > score(prev))
  14724. result[result.length - 1] = opt;
  14725. prev = opt.completion;
  14726. }
  14727. return result;
  14728. }
  14729. class CompletionDialog {
  14730. constructor(options, attrs, tooltip, timestamp, selected) {
  14731. this.options = options;
  14732. this.attrs = attrs;
  14733. this.tooltip = tooltip;
  14734. this.timestamp = timestamp;
  14735. this.selected = selected;
  14736. }
  14737. setSelected(selected, id) {
  14738. return selected == this.selected || selected >= this.options.length ? this
  14739. : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected);
  14740. }
  14741. static build(active, state, id, prev) {
  14742. let options = sortOptions(active, state);
  14743. if (!options.length)
  14744. return null;
  14745. let selected = 0;
  14746. if (prev) {
  14747. let selectedValue = prev.options[prev.selected].completion;
  14748. for (let i = 0; i < options.length && !selected; i++) {
  14749. if (options[i].completion == selectedValue)
  14750. selected = i;
  14751. }
  14752. }
  14753. return new CompletionDialog(options, makeAttrs(id, selected), [{
  14754. pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
  14755. style: "autocomplete",
  14756. create: completionTooltip(completionState)
  14757. }], prev ? prev.timestamp : Date.now(), selected);
  14758. }
  14759. map(changes) {
  14760. return new CompletionDialog(this.options, this.attrs, [Object.assign(Object.assign({}, this.tooltip[0]), { pos: changes.mapPos(this.tooltip[0].pos) })], this.timestamp, this.selected);
  14761. }
  14762. }
  14763. class CompletionState {
  14764. constructor(active, id, open) {
  14765. this.active = active;
  14766. this.id = id;
  14767. this.open = open;
  14768. }
  14769. static start() {
  14770. return new CompletionState(none$6, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  14771. }
  14772. update(tr) {
  14773. let { state } = tr, conf = state.facet(completionConfig);
  14774. let sources = conf.override ||
  14775. state.languageDataAt("autocomplete", cur(state)).map(asSource);
  14776. let active = sources.map(source => {
  14777. let value = this.active.find(s => s.source == source) || new ActiveSource(source, 0 /* Inactive */, false);
  14778. return value.update(tr, conf);
  14779. });
  14780. if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
  14781. active = this.active;
  14782. let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||
  14783. !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open)
  14784. : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open;
  14785. for (let effect of tr.effects)
  14786. if (effect.is(setSelectedEffect))
  14787. open = open && open.setSelected(effect.value, this.id);
  14788. return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
  14789. }
  14790. get tooltip() { return this.open ? this.open.tooltip : none$6; }
  14791. get attrs() { return this.open ? this.open.attrs : baseAttrs; }
  14792. }
  14793. function sameResults(a, b) {
  14794. if (a == b)
  14795. return true;
  14796. for (let iA = 0, iB = 0;;) {
  14797. while (iA < a.length && !a[iA].hasResult)
  14798. iA++;
  14799. while (iB < b.length && !b[iB].hasResult)
  14800. iB++;
  14801. let endA = iA == a.length, endB = iB == b.length;
  14802. if (endA || endB)
  14803. return endA == endB;
  14804. if (a[iA++].result != b[iB++].result)
  14805. return false;
  14806. }
  14807. }
  14808. function makeAttrs(id, selected) {
  14809. return {
  14810. "aria-autocomplete": "list",
  14811. "aria-activedescendant": id + "-" + selected,
  14812. "aria-owns": id
  14813. };
  14814. }
  14815. const baseAttrs = { "aria-autocomplete": "list" }, none$6 = [];
  14816. function cmpOption(a, b) {
  14817. let dScore = b.match[0] - a.match[0];
  14818. if (dScore)
  14819. return dScore;
  14820. let lA = a.completion.label, lB = b.completion.label;
  14821. return lA < lB ? -1 : lA == lB ? 0 : 1;
  14822. }
  14823. class ActiveSource {
  14824. constructor(source, state, explicit) {
  14825. this.source = source;
  14826. this.state = state;
  14827. this.explicit = explicit;
  14828. }
  14829. hasResult() { return false; }
  14830. update(tr, conf) {
  14831. let event = tr.annotation(Transaction.userEvent), value = this;
  14832. if (event == "input" || event == "delete")
  14833. value = value.handleUserEvent(tr, event, conf);
  14834. else if (tr.docChanged)
  14835. value = value.handleChange(tr);
  14836. else if (tr.selection && value.state != 0 /* Inactive */)
  14837. value = new ActiveSource(value.source, 0 /* Inactive */, false);
  14838. for (let effect of tr.effects) {
  14839. if (effect.is(startCompletionEffect))
  14840. value = new ActiveSource(value.source, 1 /* Pending */, effect.value);
  14841. else if (effect.is(closeCompletionEffect))
  14842. value = new ActiveSource(value.source, 0 /* Inactive */, false);
  14843. else if (effect.is(setActiveEffect))
  14844. for (let active of effect.value)
  14845. if (active.source == value.source)
  14846. value = active;
  14847. }
  14848. return value;
  14849. }
  14850. handleUserEvent(_tr, type, conf) {
  14851. return type == "delete" || !conf.activateOnTyping ? this : new ActiveSource(this.source, 1 /* Pending */, false);
  14852. }
  14853. handleChange(tr) {
  14854. return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* Inactive */, false) : this;
  14855. }
  14856. }
  14857. class ActiveResult extends ActiveSource {
  14858. constructor(source, explicit, result, from, to, span) {
  14859. super(source, 2 /* Result */, explicit);
  14860. this.result = result;
  14861. this.from = from;
  14862. this.to = to;
  14863. this.span = span;
  14864. }
  14865. hasResult() { return true; }
  14866. handleUserEvent(tr, type, conf) {
  14867. let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
  14868. let pos = cur(tr.state);
  14869. if ((this.explicit ? pos < from : pos <= from) || pos > to)
  14870. return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* Pending */ : 0 /* Inactive */, false);
  14871. if (this.span && (from == to || this.span.test(tr.state.sliceDoc(from, to))))
  14872. return new ActiveResult(this.source, this.explicit, this.result, from, to, this.span);
  14873. return new ActiveSource(this.source, 1 /* Pending */, this.explicit);
  14874. }
  14875. handleChange(tr) {
  14876. return tr.changes.touchesRange(this.from, this.to)
  14877. ? new ActiveSource(this.source, 0 /* Inactive */, false)
  14878. : new ActiveResult(this.source, this.explicit, this.result, tr.changes.mapPos(this.from), tr.changes.mapPos(this.to, 1), this.span);
  14879. }
  14880. map(mapping) {
  14881. return new ActiveResult(this.source, this.explicit, this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1), this.span);
  14882. }
  14883. }
  14884. const startCompletionEffect = StateEffect.define();
  14885. const closeCompletionEffect = StateEffect.define();
  14886. const setActiveEffect = StateEffect.define({
  14887. map(sources, mapping) { return sources.map(s => s.hasResult() && !mapping.empty ? s.map(mapping) : s); }
  14888. });
  14889. const setSelectedEffect = StateEffect.define();
  14890. const completionState = StateField.define({
  14891. create() { return CompletionState.start(); },
  14892. update(value, tr) { return value.update(tr); },
  14893. provide: f => [
  14894. showTooltip.computeN([f], state => state.field(f).tooltip),
  14895. EditorView.contentAttributes.from(f, state => state.attrs)
  14896. ]
  14897. });
  14898. const CompletionInteractMargin = 75;
  14899. /// Returns a command that moves the completion selection forward or
  14900. /// backward by the given amount.
  14901. function moveCompletionSelection(forward, by = "option") {
  14902. return (view) => {
  14903. let cState = view.state.field(completionState, false);
  14904. if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin)
  14905. return false;
  14906. let step = 1, tooltip;
  14907. if (by == "page" && (tooltip = view.dom.querySelector(".cm-tooltip-autocomplete")))
  14908. step = Math.max(2, Math.floor(tooltip.offsetHeight / tooltip.firstChild.offsetHeight));
  14909. let selected = cState.open.selected + step * (forward ? 1 : -1), { length } = cState.open.options;
  14910. if (selected < 0)
  14911. selected = by == "page" ? 0 : length - 1;
  14912. else if (selected >= length)
  14913. selected = by == "page" ? length - 1 : 0;
  14914. view.dispatch({ effects: setSelectedEffect.of(selected) });
  14915. return true;
  14916. };
  14917. }
  14918. /// Accept the current completion.
  14919. const acceptCompletion = (view) => {
  14920. let cState = view.state.field(completionState, false);
  14921. if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin)
  14922. return false;
  14923. applyCompletion(view, cState.open.options[cState.open.selected]);
  14924. return true;
  14925. };
  14926. /// Explicitly start autocompletion.
  14927. const startCompletion = (view) => {
  14928. let cState = view.state.field(completionState, false);
  14929. if (!cState)
  14930. return false;
  14931. view.dispatch({ effects: startCompletionEffect.of(true) });
  14932. return true;
  14933. };
  14934. /// Close the currently active completion.
  14935. const closeCompletion = (view) => {
  14936. let cState = view.state.field(completionState, false);
  14937. if (!cState || !cState.active.some(a => a.state != 0 /* Inactive */))
  14938. return false;
  14939. view.dispatch({ effects: closeCompletionEffect.of(null) });
  14940. return true;
  14941. };
  14942. class RunningQuery {
  14943. constructor(source, context) {
  14944. this.source = source;
  14945. this.context = context;
  14946. this.time = Date.now();
  14947. this.updates = [];
  14948. // Note that 'undefined' means 'not done yet', whereas 'null' means
  14949. // 'query returned null'.
  14950. this.done = undefined;
  14951. }
  14952. }
  14953. const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000;
  14954. const completionPlugin = ViewPlugin.fromClass(class {
  14955. constructor(view) {
  14956. this.view = view;
  14957. this.debounceUpdate = -1;
  14958. this.running = [];
  14959. this.debounceAccept = -1;
  14960. this.composing = 0 /* None */;
  14961. for (let active of view.state.field(completionState).active)
  14962. if (active.state == 1 /* Pending */)
  14963. this.startQuery(active);
  14964. }
  14965. update(update) {
  14966. let cState = update.state.field(completionState);
  14967. if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
  14968. return;
  14969. let doesReset = update.transactions.some(tr => {
  14970. let event = tr.annotation(Transaction.userEvent);
  14971. return (tr.selection || tr.docChanged) && event != "input" && event != "delete";
  14972. });
  14973. for (let i = 0; i < this.running.length; i++) {
  14974. let query = this.running[i];
  14975. if (doesReset ||
  14976. query.updates.length + update.transactions.length > MaxUpdateCount && query.time - Date.now() > MinAbortTime) {
  14977. for (let handler of query.context.abortListeners) {
  14978. try {
  14979. handler();
  14980. }
  14981. catch (e) {
  14982. logException(this.view.state, e);
  14983. }
  14984. }
  14985. query.context.abortListeners = null;
  14986. this.running.splice(i--, 1);
  14987. }
  14988. else {
  14989. query.updates.push(...update.transactions);
  14990. }
  14991. }
  14992. if (this.debounceUpdate > -1)
  14993. clearTimeout(this.debounceUpdate);
  14994. this.debounceUpdate = cState.active.some(a => a.state == 1 /* Pending */ && !this.running.some(q => q.source == a.source))
  14995. ? setTimeout(() => this.startUpdate(), DebounceTime) : -1;
  14996. if (this.composing != 0 /* None */)
  14997. for (let tr of update.transactions) {
  14998. if (tr.annotation(Transaction.userEvent) == "input")
  14999. this.composing = 2 /* Changed */;
  15000. else if (this.composing == 2 /* Changed */ && tr.selection)
  15001. this.composing = 3 /* ChangedAndMoved */;
  15002. }
  15003. }
  15004. startUpdate() {
  15005. this.debounceUpdate = -1;
  15006. let { state } = this.view, cState = state.field(completionState);
  15007. for (let active of cState.active) {
  15008. if (active.state == 1 /* Pending */ && !this.running.some(r => r.source == active.source))
  15009. this.startQuery(active);
  15010. }
  15011. }
  15012. startQuery(active) {
  15013. let { state } = this.view, pos = cur(state);
  15014. let context = new CompletionContext(state, pos, active.explicit);
  15015. let pending = new RunningQuery(active.source, context);
  15016. this.running.push(pending);
  15017. Promise.resolve(active.source(context)).then(result => {
  15018. if (!pending.context.aborted) {
  15019. pending.done = result || null;
  15020. this.scheduleAccept();
  15021. }
  15022. }, err => {
  15023. this.view.dispatch({ effects: closeCompletionEffect.of(null) });
  15024. logException(this.view.state, err);
  15025. });
  15026. }
  15027. scheduleAccept() {
  15028. if (this.running.every(q => q.done !== undefined))
  15029. this.accept();
  15030. else if (this.debounceAccept < 0)
  15031. this.debounceAccept = setTimeout(() => this.accept(), DebounceTime);
  15032. }
  15033. // For each finished query in this.running, try to create a result
  15034. // or, if appropriate, restart the query.
  15035. accept() {
  15036. var _a;
  15037. if (this.debounceAccept > -1)
  15038. clearTimeout(this.debounceAccept);
  15039. this.debounceAccept = -1;
  15040. let updated = [];
  15041. let conf = this.view.state.facet(completionConfig);
  15042. for (let i = 0; i < this.running.length; i++) {
  15043. let query = this.running[i];
  15044. if (query.done === undefined)
  15045. continue;
  15046. this.running.splice(i--, 1);
  15047. if (query.done) {
  15048. let active = new ActiveResult(query.source, query.context.explicit, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state), query.done.span ? ensureAnchor(query.done.span, true) : null);
  15049. // Replay the transactions that happened since the start of
  15050. // the request and see if that preserves the result
  15051. for (let tr of query.updates)
  15052. active = active.update(tr, conf);
  15053. if (active.hasResult()) {
  15054. updated.push(active);
  15055. continue;
  15056. }
  15057. }
  15058. let current = this.view.state.field(completionState).active.find(a => a.source == query.source);
  15059. if (current && current.state == 1 /* Pending */) {
  15060. if (query.done == null) {
  15061. // Explicitly failed. Should clear the pending status if it
  15062. // hasn't been re-set in the meantime.
  15063. let active = new ActiveSource(query.source, 0 /* Inactive */, false);
  15064. for (let tr of query.updates)
  15065. active = active.update(tr, conf);
  15066. if (active.state != 1 /* Pending */)
  15067. updated.push(active);
  15068. }
  15069. else {
  15070. // Cleared by subsequent transactions. Restart.
  15071. this.startQuery(current);
  15072. }
  15073. }
  15074. }
  15075. if (updated.length)
  15076. this.view.dispatch({ effects: setActiveEffect.of(updated) });
  15077. }
  15078. }, {
  15079. eventHandlers: {
  15080. compositionstart() {
  15081. this.composing = 1 /* Started */;
  15082. },
  15083. compositionend() {
  15084. if (this.composing == 3 /* ChangedAndMoved */)
  15085. this.view.dispatch({ effects: startCompletionEffect.of(false) });
  15086. this.composing = 0 /* None */;
  15087. }
  15088. }
  15089. });
  15090. class FieldPos {
  15091. constructor(field, line, from, to) {
  15092. this.field = field;
  15093. this.line = line;
  15094. this.from = from;
  15095. this.to = to;
  15096. }
  15097. }
  15098. class FieldRange {
  15099. constructor(field, from, to) {
  15100. this.field = field;
  15101. this.from = from;
  15102. this.to = to;
  15103. }
  15104. map(changes) {
  15105. return new FieldRange(this.field, changes.mapPos(this.from, -1), changes.mapPos(this.to, 1));
  15106. }
  15107. }
  15108. class Snippet {
  15109. constructor(lines, fieldPositions) {
  15110. this.lines = lines;
  15111. this.fieldPositions = fieldPositions;
  15112. }
  15113. instantiate(state, pos) {
  15114. let text = [], lineStart = [pos];
  15115. let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
  15116. for (let line of this.lines) {
  15117. if (text.length) {
  15118. let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
  15119. for (let i = 0; i < tabs; i++)
  15120. indent += state.facet(indentUnit);
  15121. lineStart.push(pos + indent.length - tabs);
  15122. line = indent + line.slice(tabs);
  15123. }
  15124. text.push(line);
  15125. pos += line.length + 1;
  15126. }
  15127. let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
  15128. return { text, ranges };
  15129. }
  15130. static parse(template) {
  15131. let fields = [];
  15132. let lines = [], positions = [], m;
  15133. for (let line of template.split(/\r\n?|\n/)) {
  15134. while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
  15135. let seq = m[1] ? +m[1] : null, name = m[2] || m[3], found = -1;
  15136. for (let i = 0; i < fields.length; i++) {
  15137. if (name ? fields[i].name == name : seq != null && fields[i].seq == seq)
  15138. found = i;
  15139. }
  15140. if (found < 0) {
  15141. let i = 0;
  15142. while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))
  15143. i++;
  15144. fields.splice(i, 0, { seq, name: name || null });
  15145. found = i;
  15146. }
  15147. positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
  15148. line = line.slice(0, m.index) + name + line.slice(m.index + m[0].length);
  15149. }
  15150. lines.push(line);
  15151. }
  15152. return new Snippet(lines, positions);
  15153. }
  15154. }
  15155. let fieldMarker = Decoration.widget({ widget: new class extends WidgetType {
  15156. toDOM() {
  15157. let span = document.createElement("span");
  15158. span.className = themeClass("snippetFieldPosition");
  15159. return span;
  15160. }
  15161. ignoreEvent() { return false; }
  15162. } });
  15163. let fieldRange = Decoration.mark({ class: themeClass("snippetField") });
  15164. class ActiveSnippet {
  15165. constructor(ranges, active) {
  15166. this.ranges = ranges;
  15167. this.active = active;
  15168. this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
  15169. }
  15170. map(changes) {
  15171. return new ActiveSnippet(this.ranges.map(r => r.map(changes)), this.active);
  15172. }
  15173. selectionInsideField(sel) {
  15174. return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
  15175. }
  15176. }
  15177. const setActive = StateEffect.define({
  15178. map(value, changes) { return value && value.map(changes); }
  15179. });
  15180. const moveToField = StateEffect.define();
  15181. const snippetState = StateField.define({
  15182. create() { return null; },
  15183. update(value, tr) {
  15184. for (let effect of tr.effects) {
  15185. if (effect.is(setActive))
  15186. return effect.value;
  15187. if (effect.is(moveToField) && value)
  15188. return new ActiveSnippet(value.ranges, effect.value);
  15189. }
  15190. if (value && tr.docChanged)
  15191. value = value.map(tr.changes);
  15192. if (value && tr.selection && !value.selectionInsideField(tr.selection))
  15193. value = null;
  15194. return value;
  15195. },
  15196. provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)
  15197. });
  15198. function fieldSelection(ranges, field) {
  15199. return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
  15200. }
  15201. /// Convert a snippet template to a function that can apply it.
  15202. /// Snippets are written using syntax like this:
  15203. ///
  15204. /// "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
  15205. ///
  15206. /// Each `${}` placeholder (you may also use `#{}`) indicates a field
  15207. /// that the user can fill in. Its name, if any, will be the default
  15208. /// content for the field.
  15209. ///
  15210. /// When the snippet is activated by calling the returned function,
  15211. /// the code is inserted at the given position. Newlines in the
  15212. /// template are indented by the indentation of the start line, plus
  15213. /// one [indent unit](#language.indentUnit) per tab character after
  15214. /// the newline.
  15215. ///
  15216. /// On activation, (all instances of) the first field are selected.
  15217. /// The user can move between fields with Tab and Shift-Tab as long as
  15218. /// the fields are active. Moving to the last field or moving the
  15219. /// cursor out of the current field deactivates the fields.
  15220. ///
  15221. /// The order of fields defaults to textual order, but you can add
  15222. /// numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
  15223. /// a custom order.
  15224. function snippet(template) {
  15225. let snippet = Snippet.parse(template);
  15226. return (editor, _completion, from, to) => {
  15227. let { text, ranges } = snippet.instantiate(editor.state, from);
  15228. let spec = { changes: { from, to, insert: Text.of(text) } };
  15229. if (ranges.length)
  15230. spec.selection = fieldSelection(ranges, 0);
  15231. if (ranges.length > 1) {
  15232. spec.effects = setActive.of(new ActiveSnippet(ranges, 0));
  15233. if (editor.state.field(snippetState, false) === undefined)
  15234. spec.reconfigure = { append: [snippetState, addSnippetKeymap, baseTheme$7] };
  15235. }
  15236. editor.dispatch(editor.state.update(spec));
  15237. };
  15238. }
  15239. function moveField(dir) {
  15240. return ({ state, dispatch }) => {
  15241. let active = state.field(snippetState, false);
  15242. if (!active || dir < 0 && active.active == 0)
  15243. return false;
  15244. let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
  15245. dispatch(state.update({
  15246. selection: fieldSelection(active.ranges, next),
  15247. effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next))
  15248. }));
  15249. return true;
  15250. };
  15251. }
  15252. /// A command that clears the active snippet, if any.
  15253. const clearSnippet = ({ state, dispatch }) => {
  15254. let active = state.field(snippetState, false);
  15255. if (!active)
  15256. return false;
  15257. dispatch(state.update({ effects: setActive.of(null) }));
  15258. return true;
  15259. };
  15260. /// Move to the next snippet field, if available.
  15261. const nextSnippetField = moveField(1);
  15262. /// Move to the previous snippet field, if available.
  15263. const prevSnippetField = moveField(-1);
  15264. const defaultSnippetKeymap = [
  15265. { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
  15266. { key: "Escape", run: clearSnippet }
  15267. ];
  15268. /// A facet that can be used to configure the key bindings used by
  15269. /// snippets. The default binds Tab to
  15270. /// [`nextSnippetField`](#autocomplete.nextSnippetField), Shift-Tab to
  15271. /// [`prevSnippetField`](#autocomplete.prevSnippetField), and Escape
  15272. /// to [`clearSnippet`](#autocomplete.clearSnippet).
  15273. const snippetKeymap = Facet.define({
  15274. combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }
  15275. });
  15276. const addSnippetKeymap = Prec.override(keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
  15277. /// Create a completion from a snippet. Returns an object with the
  15278. /// properties from `completion`, plus an `apply` function that
  15279. /// applies the snippet.
  15280. function snippetCompletion(template, completion) {
  15281. return Object.assign(Object.assign({}, completion), { apply: snippet(template) });
  15282. }
  15283. /// Returns an extension that enables autocompletion.
  15284. function autocompletion(config = {}) {
  15285. return [
  15286. completionState,
  15287. completionConfig.of(config),
  15288. completionPlugin,
  15289. completionKeymapExt,
  15290. baseTheme$7,
  15291. tooltips()
  15292. ];
  15293. }
  15294. /// Basic keybindings for autocompletion.
  15295. ///
  15296. /// - Ctrl-Space: [`startCompletion`](#autocomplete.startCompletion)
  15297. /// - Escape: [`closeCompletion`](#autocomplete.closeCompletion)
  15298. /// - ArrowDown: [`moveCompletionSelection`](#autocomplete.moveCompletionSelection)`(true)`
  15299. /// - ArrowUp: [`moveCompletionSelection`](#autocomplete.moveCompletionSelection)`(false)`
  15300. /// - PageDown: [`moveCompletionSelection`](#autocomplete.moveCompletionSelection)`(true, "page")`
  15301. /// - PageDown: [`moveCompletionSelection`](#autocomplete.moveCompletionSelection)`(true, "page")`
  15302. /// - Enter: [`acceptCompletion`](#autocomplete.acceptCompletion)
  15303. const completionKeymap = [
  15304. { key: "Ctrl-Space", run: startCompletion },
  15305. { key: "Escape", run: closeCompletion },
  15306. { key: "ArrowDown", run: moveCompletionSelection(true) },
  15307. { key: "ArrowUp", run: moveCompletionSelection(false) },
  15308. { key: "PageDown", run: moveCompletionSelection(true, "page") },
  15309. { key: "PageUp", run: moveCompletionSelection(false, "page") },
  15310. { key: "Enter", run: acceptCompletion }
  15311. ];
  15312. const completionKeymapExt = Prec.override(keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
  15313. /// Comment or uncomment the current selection. Will use line comments
  15314. /// if available, otherwise falling back to block comments.
  15315. const toggleComment = target => {
  15316. let config = getConfig(target.state);
  15317. return config.line ? toggleLineComment(target) : config.block ? toggleBlockComment(target) : false;
  15318. };
  15319. function command(f, option) {
  15320. return ({ state, dispatch }) => {
  15321. let tr = f(option, state.selection.ranges, state);
  15322. if (!tr)
  15323. return false;
  15324. dispatch(state.update(tr));
  15325. return true;
  15326. };
  15327. }
  15328. /// Comment or uncomment the current selection using line comments.
  15329. /// The line comment syntax is taken from the
  15330. /// [`commentTokens`](#comment.CommentTokens) [language
  15331. /// data](#state.EditorState.languageDataAt).
  15332. const toggleLineComment = command(changeLineComment, 0 /* Toggle */);
  15333. /// Comment or uncomment the current selection using block comments.
  15334. /// The block comment syntax is taken from the
  15335. /// [`commentTokens`](#comment.CommentTokens) [language
  15336. /// data](#state.EditorState.languageDataAt).
  15337. const toggleBlockComment = command(changeBlockComment, 0 /* Toggle */);
  15338. /// Default key bindings for this package.
  15339. ///
  15340. /// - Ctrl-/ (Cmd-/ on macOS): [`toggleComment`](#comment.toggleComment).
  15341. /// - Shift-Alt-a: [`toggleBlockComment`](#comment.toggleBlockComment).
  15342. const commentKeymap = [
  15343. { key: "Mod-/", run: toggleComment },
  15344. { key: "Alt-A", run: toggleBlockComment }
  15345. ];
  15346. function getConfig(state, pos = state.selection.main.head) {
  15347. let data = state.languageDataAt("commentTokens", pos);
  15348. return data.length ? data[0] : {};
  15349. }
  15350. const SearchMargin = 50;
  15351. /// Determines if the given range is block-commented in the given
  15352. /// state.
  15353. function findBlockComment(state, { open, close }, from, to) {
  15354. let textBefore = state.sliceDoc(from - SearchMargin, from);
  15355. let textAfter = state.sliceDoc(to, to + SearchMargin);
  15356. let spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length;
  15357. let beforeOff = textBefore.length - spaceBefore;
  15358. if (textBefore.slice(beforeOff - open.length, beforeOff) == open &&
  15359. textAfter.slice(spaceAfter, spaceAfter + close.length) == close) {
  15360. return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 },
  15361. close: { pos: to + spaceAfter, margin: spaceAfter && 1 } };
  15362. }
  15363. let startText, endText;
  15364. if (to - from <= 2 * SearchMargin) {
  15365. startText = endText = state.sliceDoc(from, to);
  15366. }
  15367. else {
  15368. startText = state.sliceDoc(from, from + SearchMargin);
  15369. endText = state.sliceDoc(to - SearchMargin, to);
  15370. }
  15371. let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length;
  15372. let endOff = endText.length - endSpace - close.length;
  15373. if (startText.slice(startSpace, startSpace + open.length) == open &&
  15374. endText.slice(endOff, endOff + close.length) == close) {
  15375. return { open: { pos: from + startSpace + open.length,
  15376. margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 },
  15377. close: { pos: to - endSpace - close.length,
  15378. margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };
  15379. }
  15380. return null;
  15381. }
  15382. // Performs toggle, comment and uncomment of block comments in
  15383. // languages that support them.
  15384. function changeBlockComment(option, ranges, state) {
  15385. let tokens = ranges.map(r => getConfig(state, r.from).block);
  15386. if (!tokens.every(c => c))
  15387. return null;
  15388. let comments = ranges.map((r, i) => findBlockComment(state, tokens[i], r.from, r.to));
  15389. if (option != 2 /* Uncomment */ && !comments.every(c => c)) {
  15390. let index = 0;
  15391. return state.changeByRange(range => {
  15392. let { open, close } = tokens[index++];
  15393. if (comments[index])
  15394. return { range };
  15395. let shift = open.length + 1;
  15396. return {
  15397. changes: [{ from: range.from, insert: open + " " }, { from: range.to, insert: " " + close }],
  15398. range: EditorSelection.range(range.anchor + shift, range.head + shift)
  15399. };
  15400. });
  15401. }
  15402. else if (option != 1 /* Comment */ && comments.some(c => c)) {
  15403. let changes = [];
  15404. for (let i = 0, comment; i < comments.length; i++)
  15405. if (comment = comments[i]) {
  15406. let token = tokens[i], { open, close } = comment;
  15407. changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length });
  15408. }
  15409. return { changes };
  15410. }
  15411. return null;
  15412. }
  15413. function findLineComment(token, lines) {
  15414. let minCol = 1e9, commented = null, skipped = [];
  15415. for (let i = 0; i < lines.length; i++) {
  15416. let line = lines[i], col = /^\s*/.exec(line.text)[0].length;
  15417. let empty = skipped[line.number] = col == line.length;
  15418. if (col < minCol && (!empty || minCol == 1e9 && i == lines.length - 1))
  15419. minCol = col;
  15420. if (commented != false && (!empty || commented == null && i == lines.length - 1))
  15421. commented = line.text.slice(col, col + token.length) == token;
  15422. }
  15423. return { minCol, commented: commented, skipped };
  15424. }
  15425. // Performs toggle, comment and uncomment of line comments.
  15426. function changeLineComment(option, ranges, state) {
  15427. let lines = [], tokens = [], lineRanges = [];
  15428. for (let { from, to } of ranges) {
  15429. let token = getConfig(state, from).line;
  15430. if (!token)
  15431. return null;
  15432. tokens.push(token);
  15433. let lns = getLinesInRange(state.doc, from, to);
  15434. lines.push(lns);
  15435. lineRanges.push(findLineComment(token, lns));
  15436. }
  15437. if (option != 2 /* Uncomment */ && lineRanges.some(c => !c.commented)) {
  15438. let changes = [];
  15439. for (let i = 0, lineRange; i < ranges.length; i++)
  15440. if (!(lineRange = lineRanges[i]).commented) {
  15441. for (let line of lines[i]) {
  15442. if (!lineRange.skipped[line.number] || lines[i].length == 1)
  15443. changes.push({ from: line.from + lineRange.minCol, insert: tokens[i] + " " });
  15444. }
  15445. }
  15446. return { changes };
  15447. }
  15448. else if (option != 1 /* Comment */ && lineRanges.some(c => c.commented)) {
  15449. let changes = [];
  15450. for (let i = 0, lineRange; i < ranges.length; i++)
  15451. if ((lineRange = lineRanges[i]).commented) {
  15452. let token = tokens[i];
  15453. for (let line of lines[i]) {
  15454. if (lineRange.skipped[line.number] && lines[i].length > 1)
  15455. continue;
  15456. let pos = line.from + lineRange.minCol;
  15457. let posAfter = lineRange.minCol + token.length;
  15458. let marginLen = line.text.slice(posAfter, posAfter + 1) == " " ? 1 : 0;
  15459. changes.push({ from: pos, to: pos + token.length + marginLen });
  15460. }
  15461. }
  15462. return { changes };
  15463. }
  15464. return null;
  15465. }
  15466. function getLinesInRange(doc, from, to) {
  15467. let line = doc.lineAt(from), lines = [];
  15468. while (line.to < to || (line.from <= to && to <= line.to)) {
  15469. lines.push(line);
  15470. if (line.number == doc.lines)
  15471. break;
  15472. line = doc.line(line.number + 1);
  15473. }
  15474. return lines;
  15475. }
  15476. // Don't compute precise column positions for line offsets above this
  15477. // (since it could get expensive). Assume offset==column for them.
  15478. const MaxOff = 2000;
  15479. function rectangleFor(state, a, b) {
  15480. let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line);
  15481. let ranges = [];
  15482. if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) {
  15483. let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off);
  15484. for (let i = startLine; i <= endLine; i++) {
  15485. let line = state.doc.line(i);
  15486. if (line.length <= endOff)
  15487. ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff));
  15488. }
  15489. }
  15490. else {
  15491. let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col);
  15492. for (let i = startLine; i <= endLine; i++) {
  15493. let line = state.doc.line(i), str = line.length > MaxOff ? line.text.slice(0, 2 * endCol) : line.text;
  15494. let start = findColumn(str, 0, startCol, state.tabSize), end = findColumn(str, 0, endCol, state.tabSize);
  15495. if (!start.leftOver)
  15496. ranges.push(EditorSelection.range(line.from + start.offset, line.from + end.offset));
  15497. }
  15498. }
  15499. return ranges;
  15500. }
  15501. function absoluteColumn(view, x) {
  15502. let ref = view.coordsAtPos(view.viewport.from);
  15503. return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1;
  15504. }
  15505. function getPos(view, event) {
  15506. let offset = view.posAtCoords({ x: event.clientX, y: event.clientY });
  15507. if (offset == null)
  15508. return null;
  15509. let line = view.state.doc.lineAt(offset), off = offset - line.from;
  15510. let col = off > MaxOff ? -1
  15511. : off == line.length ? absoluteColumn(view, event.clientX)
  15512. : countColumn(line.text.slice(0, offset - line.from), 0, view.state.tabSize);
  15513. return { line: line.number, col, off };
  15514. }
  15515. function rectangleSelectionStyle(view, event) {
  15516. let start = getPos(view, event), startSel = view.state.selection;
  15517. if (!start)
  15518. return null;
  15519. return {
  15520. update(update) {
  15521. if (update.docChanged) {
  15522. let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from);
  15523. let newLine = update.state.doc.lineAt(newStart);
  15524. start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) };
  15525. startSel = startSel.map(update.changes);
  15526. }
  15527. },
  15528. get(event, _extend, multiple) {
  15529. let cur = getPos(view, event);
  15530. if (!cur)
  15531. return startSel;
  15532. let ranges = rectangleFor(view.state, start, cur);
  15533. if (!ranges.length)
  15534. return startSel;
  15535. if (multiple)
  15536. return EditorSelection.create(ranges.concat(startSel.ranges));
  15537. else
  15538. return EditorSelection.create(ranges);
  15539. }
  15540. };
  15541. }
  15542. /// Create an extension that enables rectangular selections. By
  15543. /// default, it will react to left mouse drag with the Alt key held
  15544. /// down. When such a selection occurs, the text within the rectangle
  15545. /// that was dragged over will be selected, as one selection
  15546. /// [range](#state.SelectionRange) per line.
  15547. function rectangularSelection(options) {
  15548. let filter = (options === null || options === void 0 ? void 0 : options.eventFilter) || (e => e.altKey && e.button == 0);
  15549. return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null);
  15550. }
  15551. let nextTagID = 0;
  15552. /// Highlighting tags are markers that denote a highlighting category.
  15553. /// They are [associated](#highlight.styleTags) with parts of a syntax
  15554. /// tree by a language mode, and then mapped to an actual CSS style by
  15555. /// a [highlight style](#highlight.HighlightStyle).
  15556. ///
  15557. /// Because syntax tree node types and highlight styles have to be
  15558. /// able to talk the same language, CodeMirror uses a mostly _closed_
  15559. /// [vocabulary](#highlight.tags) of syntax tags (as opposed to
  15560. /// traditional open string-based systems, which make it hard for
  15561. /// highlighting themes to cover all the tokens produced by the
  15562. /// various languages).
  15563. ///
  15564. /// It _is_ possible to [define](#highlight.Tag^define) your own
  15565. /// highlighting tags for system-internal use (where you control both
  15566. /// the language package and the highlighter), but such tags will not
  15567. /// be picked up by regular highlighters (though you can derive them
  15568. /// from standard tags to allow highlighters to fall back to those).
  15569. class Tag {
  15570. /// @internal
  15571. constructor(
  15572. /// The set of tags that match this tag, starting with this one
  15573. /// itself, sorted in order of decreasing specificity. @internal
  15574. set,
  15575. /// The base unmodified tag that this one is based on, if it's
  15576. /// modified @internal
  15577. base,
  15578. /// The modifiers applied to this.base @internal
  15579. modified) {
  15580. this.set = set;
  15581. this.base = base;
  15582. this.modified = modified;
  15583. /// @internal
  15584. this.id = nextTagID++;
  15585. }
  15586. /// Define a new tag. If `parent` is given, the tag is treated as a
  15587. /// sub-tag of that parent, and [highlight
  15588. /// styles](#highlight.HighlightStyle) that don't mention this tag
  15589. /// will try to fall back to the parent tag (or grandparent tag,
  15590. /// etc).
  15591. static define(parent) {
  15592. if (parent === null || parent === void 0 ? void 0 : parent.base)
  15593. throw new Error("Can not derive from a modified tag");
  15594. let tag = new Tag([], null, []);
  15595. tag.set.push(tag);
  15596. if (parent)
  15597. for (let t of parent.set)
  15598. tag.set.push(t);
  15599. return tag;
  15600. }
  15601. /// Define a tag _modifier_, which is a function that, given a tag,
  15602. /// will return a tag that is a subtag of the original. Applying the
  15603. /// same modifier to a twice tag will return the same value (`m1(t1)
  15604. /// == m1(t1)`) and applying multiple modifiers will, regardless or
  15605. /// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
  15606. ///
  15607. /// When multiple modifiers are applied to a given base tag, each
  15608. /// smaller set of modifiers is registered as a parent, so that for
  15609. /// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
  15610. /// `m1(m3(t1)`, and so on.
  15611. static defineModifier() {
  15612. let mod = new Modifier;
  15613. return (tag) => {
  15614. if (tag.modified.indexOf(mod) > -1)
  15615. return tag;
  15616. return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
  15617. };
  15618. }
  15619. }
  15620. let nextModifierID = 0;
  15621. class Modifier {
  15622. constructor() {
  15623. this.instances = [];
  15624. this.id = nextModifierID++;
  15625. }
  15626. static get(base, mods) {
  15627. if (!mods.length)
  15628. return base;
  15629. let exists = mods[0].instances.find(t => t.base == base && sameArray$1(mods, t.modified));
  15630. if (exists)
  15631. return exists;
  15632. let set = [], tag = new Tag(set, base, mods);
  15633. for (let m of mods)
  15634. m.instances.push(tag);
  15635. let configs = permute(mods);
  15636. for (let parent of base.set)
  15637. for (let config of configs)
  15638. set.push(Modifier.get(parent, config));
  15639. return tag;
  15640. }
  15641. }
  15642. function sameArray$1(a, b) {
  15643. return a.length == b.length && a.every((x, i) => x == b[i]);
  15644. }
  15645. function permute(array) {
  15646. let result = [array];
  15647. for (let i = 0; i < array.length; i++) {
  15648. for (let a of permute(array.slice(0, i).concat(array.slice(i + 1))))
  15649. result.push(a);
  15650. }
  15651. return result;
  15652. }
  15653. /// This function is used to add a set of tags to a language syntax
  15654. /// via
  15655. /// [`Parser.configure`](https://lezer.codemirror.net/docs/ref#lezer.Parser.configure).
  15656. ///
  15657. /// The argument object maps node selectors to [highlighting
  15658. /// tags](#highlight.Tag) or arrays of tags.
  15659. ///
  15660. /// Node selectors may hold one or more (space-separated) node paths.
  15661. /// Such a path can be a [node
  15662. /// name](https://lezer.codemirror.net/docs/ref#tree.NodeType.name),
  15663. /// or multiple node names (or `*` wildcards) separated by slash
  15664. /// characters, as in `"Block/Declaration/VariableName"`. Such a path
  15665. /// matches the final node but only if its direct parent nodes are the
  15666. /// other nodes mentioned. A `*` in such a path matches any parent,
  15667. /// but only a single level—wildcards that match multiple parents
  15668. /// aren't supported, both for efficiency reasons and because Lezer
  15669. /// trees make it rather hard to reason about what they would match.)
  15670. ///
  15671. /// A path can be ended with `/...` to indicate that the tag assigned
  15672. /// to the node should also apply to all child nodes, even if they
  15673. /// match their own style (by default, only the innermost style is
  15674. /// used).
  15675. ///
  15676. /// When a path ends in `!`, as in `Attribute!`, no further matching
  15677. /// happens for the node's child nodes, and the entire node gets the
  15678. /// given style.
  15679. ///
  15680. /// In this notation, node names that contain `/`, `!`, `*`, or `...`
  15681. /// must be quoted as JSON strings.
  15682. ///
  15683. /// For example:
  15684. ///
  15685. /// ```javascript
  15686. /// parser.withProps(
  15687. /// styleTags({
  15688. /// // Style Number and BigNumber nodes
  15689. /// "Number BigNumber": tags.number,
  15690. /// // Style Escape nodes whose parent is String
  15691. /// "String/Escape": tags.escape,
  15692. /// // Style anything inside Attributes nodes
  15693. /// "Attributes!": tags.meta,
  15694. /// // Add a style to all content inside Italic nodes
  15695. /// "Italic/...": tags.emphasis,
  15696. /// // Style InvalidString nodes as both `string` and `invalid`
  15697. /// "InvalidString": [tags.string, tags.invalid],
  15698. /// // Style the node named "/" as punctuation
  15699. /// '"/"': tags.punctuation
  15700. /// })
  15701. /// )
  15702. /// ```
  15703. function styleTags(spec) {
  15704. let byName = Object.create(null);
  15705. for (let prop in spec) {
  15706. let tags = spec[prop];
  15707. if (!Array.isArray(tags))
  15708. tags = [tags];
  15709. for (let part of prop.split(" "))
  15710. if (part) {
  15711. let pieces = [], mode = 2 /* Normal */, rest = part;
  15712. for (let pos = 0;;) {
  15713. if (rest == "..." && pos > 0 && pos + 3 == part.length) {
  15714. mode = 1 /* Inherit */;
  15715. break;
  15716. }
  15717. let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
  15718. if (!m)
  15719. throw new RangeError("Invalid path: " + part);
  15720. pieces.push(m[0] == "*" ? null : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
  15721. pos += m[0].length;
  15722. if (pos == part.length)
  15723. break;
  15724. let next = part[pos++];
  15725. if (pos == part.length && next == "!") {
  15726. mode = 0 /* Opaque */;
  15727. break;
  15728. }
  15729. if (next != "/")
  15730. throw new RangeError("Invalid path: " + part);
  15731. rest = part.slice(pos);
  15732. }
  15733. let last = pieces.length - 1, inner = pieces[last];
  15734. if (!inner)
  15735. throw new RangeError("Invalid path: " + part);
  15736. let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
  15737. byName[inner] = rule.sort(byName[inner]);
  15738. }
  15739. }
  15740. return ruleNodeProp.add(byName);
  15741. }
  15742. const ruleNodeProp = new NodeProp();
  15743. const highlightStyleProp = Facet.define({
  15744. combine(stylings) { return stylings.length ? stylings[0] : null; }
  15745. });
  15746. class Rule {
  15747. constructor(tags, mode, context, next) {
  15748. this.tags = tags;
  15749. this.mode = mode;
  15750. this.context = context;
  15751. this.next = next;
  15752. }
  15753. sort(other) {
  15754. if (!other || other.depth < this.depth) {
  15755. this.next = other;
  15756. return this;
  15757. }
  15758. other.next = this.sort(other.next);
  15759. return other;
  15760. }
  15761. get depth() { return this.context ? this.context.length : 0; }
  15762. }
  15763. /// A highlight style associates CSS styles with higlighting
  15764. /// [tags](#highlight.Tag).
  15765. class HighlightStyle {
  15766. constructor(spec) {
  15767. this.map = Object.create(null);
  15768. let modSpec = Object.create(null);
  15769. for (let style of spec) {
  15770. let cls = StyleModule.newName();
  15771. modSpec["." + cls] = Object.assign({}, style, { tag: null });
  15772. let tags = style.tag;
  15773. if (!Array.isArray(tags))
  15774. tags = [tags];
  15775. for (let tag of tags)
  15776. this.map[tag.id] = cls;
  15777. }
  15778. this.module = new StyleModule(modSpec);
  15779. this.match = this.match.bind(this);
  15780. this.extension = [
  15781. treeHighlighter,
  15782. highlightStyleProp.of(this),
  15783. EditorView.styleModule.of(this.module)
  15784. ];
  15785. }
  15786. /// Returns the CSS class associated with the given tag, if any.
  15787. /// This method is bound to the instance by the constructor.
  15788. match(tag) {
  15789. for (let t of tag.set) {
  15790. let match = this.map[t.id];
  15791. if (match) {
  15792. if (t != tag)
  15793. this.map[tag.id] = match;
  15794. return match;
  15795. }
  15796. }
  15797. return this.map[tag.id] = null;
  15798. }
  15799. /// Create a highlighter style that associates the given styles to
  15800. /// the given tags. The spec must be objects that hold a style tag
  15801. /// or array of tags in their `tag` property, and
  15802. /// [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
  15803. /// CSS properties in further properties (which define the styling
  15804. /// for those tags).
  15805. ///
  15806. /// The CSS rules created for a highlighter will be emitted in the
  15807. /// order of the spec's properties. That means that for elements that
  15808. /// have multiple tags associated with them, styles defined further
  15809. /// down in the list will have a higher CSS precedence than styles
  15810. /// defined earlier.
  15811. static define(...specs) {
  15812. return new HighlightStyle(specs);
  15813. }
  15814. }
  15815. // This extension installs a highlighter that highlights based on the
  15816. // syntax tree and highlight style.
  15817. const treeHighlighter = Prec.fallback(ViewPlugin.define(view => new TreeHighlighter(view), {
  15818. decorations: v => v.decorations
  15819. }));
  15820. class TreeHighlighter {
  15821. constructor(view) {
  15822. this.markCache = Object.create(null);
  15823. this.tree = syntaxTree(view.state);
  15824. this.decorations = this.buildDeco(view);
  15825. }
  15826. update(update) {
  15827. let tree = syntaxTree(update.state);
  15828. if (tree.length < update.view.viewport.to) {
  15829. this.decorations = this.decorations.map(update.changes);
  15830. }
  15831. else if (tree != this.tree || update.viewportChanged) {
  15832. this.tree = tree;
  15833. this.decorations = this.buildDeco(update.view);
  15834. }
  15835. }
  15836. buildDeco(view) {
  15837. const style = view.state.facet(highlightStyleProp);
  15838. if (!style || !this.tree.length)
  15839. return Decoration.none;
  15840. let builder = new RangeSetBuilder();
  15841. for (let { from, to } of view.visibleRanges) {
  15842. highlightTreeRange(this.tree, from, to, style.match, (from, to, style) => {
  15843. builder.add(from, to, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style })));
  15844. });
  15845. }
  15846. return builder.finish();
  15847. }
  15848. }
  15849. // Reused stacks for highlightTreeRange
  15850. const nodeStack = [""], classStack = [""], inheritStack = [""];
  15851. function highlightTreeRange(tree, from, to, style, span) {
  15852. let spanStart = from, spanClass = "", depth = 0;
  15853. tree.iterate({
  15854. from, to,
  15855. enter: (type, start) => {
  15856. depth++;
  15857. let inheritedClass = inheritStack[depth - 1];
  15858. let cls = inheritedClass;
  15859. let rule = type.prop(ruleNodeProp), opaque = false;
  15860. while (rule) {
  15861. if (!rule.context || matchContext(rule.context, nodeStack, depth)) {
  15862. for (let tag of rule.tags) {
  15863. let st = style(tag);
  15864. if (st) {
  15865. if (cls)
  15866. cls += " ";
  15867. cls += st;
  15868. if (rule.mode == 1 /* Inherit */)
  15869. inheritedClass = cls;
  15870. else if (rule.mode == 0 /* Opaque */)
  15871. opaque = true;
  15872. }
  15873. }
  15874. break;
  15875. }
  15876. rule = rule.next;
  15877. }
  15878. if (cls != spanClass) {
  15879. if (start > spanStart && spanClass)
  15880. span(spanStart, start, spanClass);
  15881. spanStart = start;
  15882. spanClass = cls;
  15883. }
  15884. if (opaque) {
  15885. depth--;
  15886. return false;
  15887. }
  15888. classStack[depth] = cls;
  15889. inheritStack[depth] = inheritedClass;
  15890. nodeStack[depth] = type.name;
  15891. return undefined;
  15892. },
  15893. leave: (_t, _s, end) => {
  15894. depth--;
  15895. let backTo = classStack[depth];
  15896. if (backTo != spanClass) {
  15897. let pos = Math.min(to, end);
  15898. if (pos > spanStart && spanClass)
  15899. span(spanStart, pos, spanClass);
  15900. spanStart = pos;
  15901. spanClass = backTo;
  15902. }
  15903. }
  15904. });
  15905. }
  15906. function matchContext(context, stack, depth) {
  15907. if (context.length > depth - 1)
  15908. return false;
  15909. for (let d = depth - 1, i = context.length - 1; i >= 0; i--, d--) {
  15910. let check = context[i];
  15911. if (check && check != stack[d])
  15912. return false;
  15913. }
  15914. return true;
  15915. }
  15916. const t = Tag.define;
  15917. const comment = t(), name = t(), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
  15918. /// The default set of highlighting [tags](#highlight.Tag^define) used
  15919. /// by regular language packages and themes.
  15920. ///
  15921. /// This collection is heavily biased towards programming languages,
  15922. /// and necessarily incomplete. A full ontology of syntactic
  15923. /// constructs would fill a stack of books, and be impractical to
  15924. /// write themes for. So try to make do with this set. If all else
  15925. /// fails, [open an
  15926. /// issue](https://github.com/codemirror/codemirror.next) to propose a
  15927. /// new tag, or [define](#highlight.Tag^define) a local custom tag for
  15928. /// your use case.
  15929. ///
  15930. /// Note that it is not obligatory to always attach the most specific
  15931. /// tag possible to an element—if your grammar can't easily
  15932. /// distinguish a certain type of element (such as a local variable),
  15933. /// it is okay to style it as its more general variant (a variable).
  15934. ///
  15935. /// For tags that extend some parent tag, the documentation links to
  15936. /// the parent.
  15937. const tags = {
  15938. /// A comment.
  15939. comment,
  15940. /// A line [comment](#highlight.tags.comment).
  15941. lineComment: t(comment),
  15942. /// A block [comment](#highlight.tags.comment).
  15943. blockComment: t(comment),
  15944. /// A documentation [comment](#highlight.tags.comment).
  15945. docComment: t(comment),
  15946. /// Any kind of identifier.
  15947. name,
  15948. /// The [name](#highlight.tags.name) of a variable.
  15949. variableName: t(name),
  15950. /// A type or tag [name](#highlight.tags.name).
  15951. typeName: t(name),
  15952. /// A property, field, or attribute [name](#highlight.tags.name).
  15953. propertyName: t(name),
  15954. /// The [name](#highlight.tags.name) of a class.
  15955. className: t(name),
  15956. /// A label [name](#highlight.tags.name).
  15957. labelName: t(name),
  15958. /// A namespace [name](#highlight.tags.name).
  15959. namespace: t(name),
  15960. /// The [name](#highlight.tags.name) of a macro.
  15961. macroName: t(name),
  15962. /// A literal value.
  15963. literal,
  15964. /// A string [literal](#highlight.tags.literal).
  15965. string,
  15966. /// A documentation [string](#highlight.tags.string).
  15967. docString: t(string),
  15968. /// A character literal (subtag of [string](#highlight.tags.string)).
  15969. character: t(string),
  15970. /// A number [literal](#highlight.tags.literal).
  15971. number,
  15972. /// An integer [number](#highlight.tags.number) literal.
  15973. integer: t(number),
  15974. /// A floating-point [number](#highlight.tags.number) literal.
  15975. float: t(number),
  15976. /// A boolean [literal](#highlight.tags.literal).
  15977. bool: t(literal),
  15978. /// Regular expression [literal](#highlight.tags.literal).
  15979. regexp: t(literal),
  15980. /// An escape [literal](#highlight.tags.literal), for example a
  15981. /// backslash escape in a string.
  15982. escape: t(literal),
  15983. /// A color [literal](#highlight.tags.literal).
  15984. color: t(literal),
  15985. /// A URL [literal](#highlight.tags.literal).
  15986. url: t(literal),
  15987. /// A language keyword.
  15988. keyword,
  15989. /// The [keyword](#highlight.tags.keyword) for the self or this
  15990. /// object.
  15991. self: t(keyword),
  15992. /// The [keyword](#highlight.tags.keyword) for null.
  15993. null: t(keyword),
  15994. /// A [keyword](#highlight.tags.keyword) denoting some atomic value.
  15995. atom: t(keyword),
  15996. /// A [keyword](#highlight.tags.keyword) that represents a unit.
  15997. unit: t(keyword),
  15998. /// A modifier [keyword](#highlight.tags.keyword).
  15999. modifier: t(keyword),
  16000. /// A [keyword](#highlight.tags.keyword) that acts as an operator.
  16001. operatorKeyword: t(keyword),
  16002. /// A control-flow related [keyword](#highlight.tags.keyword).
  16003. controlKeyword: t(keyword),
  16004. /// A [keyword](#highlight.tags.keyword) that defines something.
  16005. definitionKeyword: t(keyword),
  16006. /// An operator.
  16007. operator,
  16008. /// An [operator](#highlight.tags.operator) that defines something.
  16009. derefOperator: t(operator),
  16010. /// Arithmetic-related [operator](#highlight.tags.operator).
  16011. arithmeticOperator: t(operator),
  16012. /// Logical [operator](#highlight.tags.operator).
  16013. logicOperator: t(operator),
  16014. /// Bit [operator](#highlight.tags.operator).
  16015. bitwiseOperator: t(operator),
  16016. /// Comparison [operator](#highlight.tags.operator).
  16017. compareOperator: t(operator),
  16018. /// [Operator](#highlight.tags.operator) that updates its operand.
  16019. updateOperator: t(operator),
  16020. /// [Operator](#highlight.tags.operator) that defines something.
  16021. definitionOperator: t(operator),
  16022. /// Type-related [operator](#highlight.tags.operator).
  16023. typeOperator: t(operator),
  16024. /// Control-flow [operator](#highlight.tags.operator).
  16025. controlOperator: t(operator),
  16026. /// Program or markup punctuation.
  16027. punctuation,
  16028. /// [Punctuation](#highlight.tags.punctuation) that separates
  16029. /// things.
  16030. separator: t(punctuation),
  16031. /// Bracket-style [punctuation](#highlight.tags.punctuation).
  16032. bracket,
  16033. /// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
  16034. /// tokens).
  16035. angleBracket: t(bracket),
  16036. /// Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
  16037. /// tokens).
  16038. squareBracket: t(bracket),
  16039. /// Parentheses (usually `(` and `)` tokens). Subtag of
  16040. /// [bracket](#highlight.tags.bracket).
  16041. paren: t(bracket),
  16042. /// Braces (usually `{` and `}` tokens). Subtag of
  16043. /// [bracket](#highlight.tags.bracket).
  16044. brace: t(bracket),
  16045. /// Content, for example plain text in XML or markup documents.
  16046. content,
  16047. /// [Content](#highlight.tags.content) that represents a heading.
  16048. heading,
  16049. /// A level 1 [heading](#highlight.tags.heading).
  16050. heading1: t(heading),
  16051. /// A level 2 [heading](#highlight.tags.heading).
  16052. heading2: t(heading),
  16053. /// A level 3 [heading](#highlight.tags.heading).
  16054. heading3: t(heading),
  16055. /// A level 4 [heading](#highlight.tags.heading).
  16056. heading4: t(heading),
  16057. /// A level 5 [heading](#highlight.tags.heading).
  16058. heading5: t(heading),
  16059. /// A level 6 [heading](#highlight.tags.heading).
  16060. heading6: t(heading),
  16061. /// A prose separator (such as a horizontal rule).
  16062. contentSeparator: t(content),
  16063. /// [Content](#highlight.tags.content) that represents a list.
  16064. list: t(content),
  16065. /// [Content](#highlight.tags.content) that represents a quote.
  16066. quote: t(content),
  16067. /// [Content](#highlight.tags.content) that is emphasized.
  16068. emphasis: t(content),
  16069. /// [Content](#highlight.tags.content) that is styled strong.
  16070. strong: t(content),
  16071. /// [Content](#highlight.tags.content) that is part of a link.
  16072. link: t(content),
  16073. /// [Content](#highlight.tags.content) that is styled as code or
  16074. /// monospace.
  16075. monospace: t(content),
  16076. /// Inserted text in a change-tracking format.
  16077. inserted: t(),
  16078. /// Deleted text.
  16079. deleted: t(),
  16080. /// Changed text.
  16081. changed: t(),
  16082. /// An invalid or unsyntactic element.
  16083. invalid: t(),
  16084. /// Metadata or meta-instruction.
  16085. meta,
  16086. /// [Metadata](#highlight.tags.meta) that applies to the entire
  16087. /// document.
  16088. documentMeta: t(meta),
  16089. /// [Metadata](#highlight.tags.meta) that annotates or adds
  16090. /// attributes to a given syntactic element.
  16091. annotation: t(meta),
  16092. /// Processing instruction or preprocessor directive. Subtag of
  16093. /// [meta](#highlight.tags.meta).
  16094. processingInstruction: t(meta),
  16095. /// [Modifier](#highlight.Tag^defineModifier) that indicates that a
  16096. /// given element is being defined. Expected to be used with the
  16097. /// various [name](#highlight.tags.name) tags.
  16098. definition: Tag.defineModifier(),
  16099. /// [Modifier](#highlight.Tag^defineModifier) that indicates that
  16100. /// something is constant. Mostly expected to be used with
  16101. /// [variable names](#highlight.tags.variableName).
  16102. constant: Tag.defineModifier(),
  16103. /// [Modifier](#highlight.Tag^defineModifier) used to indicate that
  16104. /// a [variable](#highlight.tags.variableName) or [property
  16105. /// name](#highlight.tags.propertyName) is being called or defined
  16106. /// as a function.
  16107. function: Tag.defineModifier(),
  16108. /// [Modifier](#highlight.Tag^defineModifier) that can be applied to
  16109. /// [names](#highlight.tags.name) to indicate that they belong to
  16110. /// the language's standard environment.
  16111. standard: Tag.defineModifier(),
  16112. /// [Modifier](#highlight.Tag^defineModifier) that indicates a given
  16113. /// [names](#highlight.tags.name) is local to some scope.
  16114. local: Tag.defineModifier(),
  16115. /// A generic variant [modifier](#highlight.Tag^defineModifier) that
  16116. /// can be used to tag language-specific alternative variants of
  16117. /// some common tag. It is recommended for themes to define special
  16118. /// forms of at least the [string](#highlight.tags.string) and
  16119. /// [variable name](#highlight.tags.variableName) tags, since those
  16120. /// come up a lot.
  16121. special: Tag.defineModifier()
  16122. };
  16123. /// A default highlight style (works well with light themes).
  16124. const defaultHighlightStyle = HighlightStyle.define({ tag: tags.link,
  16125. textDecoration: "underline" }, { tag: tags.heading,
  16126. textDecoration: "underline",
  16127. fontWeight: "bold" }, { tag: tags.emphasis,
  16128. fontStyle: "italic" }, { tag: tags.strong,
  16129. fontWeight: "bold" }, { tag: tags.keyword,
  16130. color: "#708" }, { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
  16131. color: "#219" }, { tag: [tags.literal, tags.inserted],
  16132. color: "#164" }, { tag: [tags.string, tags.deleted],
  16133. color: "#a11" }, { tag: [tags.regexp, tags.escape, tags.special(tags.string)],
  16134. color: "#e40" }, { tag: tags.definition(tags.variableName),
  16135. color: "#00f" }, { tag: tags.local(tags.variableName),
  16136. color: "#30a" }, { tag: [tags.typeName, tags.namespace],
  16137. color: "#085" }, { tag: tags.className,
  16138. color: "#167" }, { tag: [tags.special(tags.variableName), tags.macroName, tags.local(tags.variableName)],
  16139. color: "#256" }, { tag: tags.definition(tags.propertyName),
  16140. color: "#00c" }, { tag: tags.comment,
  16141. color: "#940" }, { tag: tags.meta,
  16142. color: "#7a757a" }, { tag: tags.invalid,
  16143. color: "#f00" });
  16144. class SelectedDiagnostic {
  16145. constructor(from, to, diagnostic) {
  16146. this.from = from;
  16147. this.to = to;
  16148. this.diagnostic = diagnostic;
  16149. }
  16150. }
  16151. class LintState {
  16152. constructor(diagnostics, panel, selected) {
  16153. this.diagnostics = diagnostics;
  16154. this.panel = panel;
  16155. this.selected = selected;
  16156. }
  16157. }
  16158. function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
  16159. let found = null;
  16160. diagnostics.between(after, 1e9, (from, to, { spec }) => {
  16161. if (diagnostic && spec.diagnostic != diagnostic)
  16162. return;
  16163. found = new SelectedDiagnostic(from, to, spec.diagnostic);
  16164. return false;
  16165. });
  16166. return found;
  16167. }
  16168. function maybeEnableLint(state) {
  16169. return state.field(lintState, false) ? undefined : { append: [
  16170. lintState,
  16171. EditorView.decorations.compute([lintState], state => {
  16172. let { selected, panel } = state.field(lintState);
  16173. return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
  16174. activeMark.range(selected.from, selected.to)
  16175. ]);
  16176. }),
  16177. panels(),
  16178. hoverTooltip(lintTooltip),
  16179. baseTheme$8
  16180. ] };
  16181. }
  16182. const setDiagnosticsEffect = StateEffect.define();
  16183. const togglePanel$1 = StateEffect.define();
  16184. const movePanelSelection = StateEffect.define();
  16185. const lintState = StateField.define({
  16186. create() {
  16187. return new LintState(Decoration.none, null, null);
  16188. },
  16189. update(value, tr) {
  16190. if (tr.docChanged) {
  16191. let mapped = value.diagnostics.map(tr.changes), selected = null;
  16192. if (value.selected) {
  16193. let selPos = tr.changes.mapPos(value.selected.from, 1);
  16194. selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
  16195. }
  16196. value = new LintState(mapped, value.panel, selected);
  16197. }
  16198. for (let effect of tr.effects) {
  16199. if (effect.is(setDiagnosticsEffect)) {
  16200. let ranges = Decoration.set(effect.value.map((d) => {
  16201. return d.from < d.to
  16202. ? Decoration.mark({
  16203. attributes: { class: themeClass("lintRange." + d.severity) },
  16204. diagnostic: d
  16205. }).range(d.from, d.to)
  16206. : Decoration.widget({
  16207. widget: new DiagnosticWidget(d),
  16208. diagnostic: d
  16209. }).range(d.from);
  16210. }));
  16211. value = new LintState(ranges, value.panel, findDiagnostic(ranges));
  16212. }
  16213. else if (effect.is(togglePanel$1)) {
  16214. value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
  16215. }
  16216. else if (effect.is(movePanelSelection)) {
  16217. value = new LintState(value.diagnostics, value.panel, effect.value);
  16218. }
  16219. }
  16220. return value;
  16221. },
  16222. provide: f => [showPanel.computeN([f], s => { let { panel } = s.field(f); return panel ? [panel] : []; }),
  16223. EditorView.decorations.from(f, s => s.diagnostics)]
  16224. });
  16225. const activeMark = Decoration.mark({ class: themeClass("lintRange.active") });
  16226. function lintTooltip(view, pos, side) {
  16227. let { diagnostics } = view.state.field(lintState);
  16228. let found = [], stackStart = 2e8, stackEnd = 0;
  16229. diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
  16230. if (pos >= from && pos <= to &&
  16231. (from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) {
  16232. found.push(spec.diagnostic);
  16233. stackStart = Math.min(from, stackStart);
  16234. stackEnd = Math.max(to, stackEnd);
  16235. }
  16236. });
  16237. if (!found.length)
  16238. return null;
  16239. return {
  16240. pos: stackStart,
  16241. end: stackEnd,
  16242. above: view.state.doc.lineAt(stackStart).to < stackEnd,
  16243. style: "lint",
  16244. create() {
  16245. return { dom: crelt("ul", found.map(d => renderDiagnostic(view, d, false))) };
  16246. }
  16247. };
  16248. }
  16249. /// Command to open and focus the lint panel.
  16250. const openLintPanel = (view) => {
  16251. let field = view.state.field(lintState, false);
  16252. if (!field || !field.panel)
  16253. view.dispatch({ effects: togglePanel$1.of(true),
  16254. reconfigure: maybeEnableLint(view.state) });
  16255. let panel = getPanel(view, LintPanel.open);
  16256. if (panel)
  16257. panel.dom.querySelector(".cm-panel-lint ul").focus();
  16258. return true;
  16259. };
  16260. /// Command to close the lint panel, when open.
  16261. const closeLintPanel = (view) => {
  16262. let field = view.state.field(lintState, false);
  16263. if (!field || !field.panel)
  16264. return false;
  16265. view.dispatch({ effects: togglePanel$1.of(false) });
  16266. return true;
  16267. };
  16268. /// Move the selection to the next diagnostic.
  16269. const nextDiagnostic = (view) => {
  16270. let field = view.state.field(lintState, false);
  16271. if (!field)
  16272. return false;
  16273. let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
  16274. if (!next.value) {
  16275. next = field.diagnostics.iter(0);
  16276. if (!next.value || next.from == sel.from && next.to == sel.to)
  16277. return false;
  16278. }
  16279. view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
  16280. return true;
  16281. };
  16282. /// A set of default key bindings for the lint functionality.
  16283. ///
  16284. /// - Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](#lint.openLintPanel)
  16285. /// - F8: [`nextDiagnostic`](#lint.nextDiagnostic)
  16286. const lintKeymap = [
  16287. { key: "Mod-Shift-m", run: openLintPanel },
  16288. { key: "F8", run: nextDiagnostic }
  16289. ];
  16290. function assignKeys(actions) {
  16291. let assigned = [];
  16292. if (actions)
  16293. actions: for (let { name } of actions) {
  16294. for (let i = 0; i < name.length; i++) {
  16295. let ch = name[i];
  16296. if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
  16297. assigned.push(ch);
  16298. continue actions;
  16299. }
  16300. }
  16301. assigned.push("");
  16302. }
  16303. return assigned;
  16304. }
  16305. function renderDiagnostic(view, diagnostic, inPanel) {
  16306. var _a;
  16307. let keys = inPanel ? assignKeys(diagnostic.actions) : [];
  16308. return crelt("li", { class: themeClass("diagnostic." + diagnostic.severity) }, crelt("span", { class: themeClass("diagnosticText") }, diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => {
  16309. let click = (e) => {
  16310. e.preventDefault();
  16311. let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
  16312. if (found)
  16313. action.apply(view, found.from, found.to);
  16314. };
  16315. let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
  16316. let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex),
  16317. crelt("u", name.slice(keyIndex, keyIndex + 1)),
  16318. name.slice(keyIndex + 1)];
  16319. return crelt("button", {
  16320. class: themeClass("diagnosticAction"),
  16321. onclick: click,
  16322. onmousedown: click
  16323. }, nameElt);
  16324. }), diagnostic.source && crelt("div", { class: themeClass("diagnosticSource") }, diagnostic.source));
  16325. }
  16326. class DiagnosticWidget extends WidgetType {
  16327. constructor(diagnostic) {
  16328. super();
  16329. this.diagnostic = diagnostic;
  16330. }
  16331. eq(other) { return other.diagnostic == this.diagnostic; }
  16332. toDOM() {
  16333. return crelt("span", { class: themeClass("lintPoint." + this.diagnostic.severity) });
  16334. }
  16335. }
  16336. class PanelItem {
  16337. constructor(view, diagnostic) {
  16338. this.diagnostic = diagnostic;
  16339. this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16);
  16340. this.dom = renderDiagnostic(view, diagnostic, true);
  16341. this.dom.setAttribute("role", "option");
  16342. }
  16343. }
  16344. class LintPanel {
  16345. constructor(view) {
  16346. this.view = view;
  16347. this.items = [];
  16348. let onkeydown = (event) => {
  16349. if (event.keyCode == 27) { // Escape
  16350. closeLintPanel(this.view);
  16351. this.view.focus();
  16352. }
  16353. else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp
  16354. this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
  16355. }
  16356. else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown
  16357. this.moveSelection((this.selectedIndex + 1) % this.items.length);
  16358. }
  16359. else if (event.keyCode == 36) { // Home
  16360. this.moveSelection(0);
  16361. }
  16362. else if (event.keyCode == 35) { // End
  16363. this.moveSelection(this.items.length - 1);
  16364. }
  16365. else if (event.keyCode == 13) { // Enter
  16366. this.view.focus();
  16367. }
  16368. else if (event.keyCode >= 65 && event.keyCode <= 90 && this.items.length) { // A-Z
  16369. let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
  16370. for (let i = 0; i < keys.length; i++)
  16371. if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
  16372. let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
  16373. if (found)
  16374. diagnostic.actions[i].apply(view, found.from, found.to);
  16375. }
  16376. }
  16377. else {
  16378. return;
  16379. }
  16380. event.preventDefault();
  16381. };
  16382. let onclick = (event) => {
  16383. for (let i = 0; i < this.items.length; i++) {
  16384. if (this.items[i].dom.contains(event.target))
  16385. this.moveSelection(i);
  16386. }
  16387. };
  16388. this.list = crelt("ul", {
  16389. tabIndex: 0,
  16390. role: "listbox",
  16391. "aria-label": this.view.state.phrase("Diagnostics"),
  16392. onkeydown,
  16393. onclick
  16394. });
  16395. this.dom = crelt("div", this.list, crelt("button", {
  16396. name: "close",
  16397. "aria-label": this.view.state.phrase("close"),
  16398. onclick: () => closeLintPanel(this.view)
  16399. }, "×"));
  16400. this.update();
  16401. }
  16402. get selectedIndex() {
  16403. let selected = this.view.state.field(lintState).selected;
  16404. if (!selected)
  16405. return -1;
  16406. for (let i = 0; i < this.items.length; i++)
  16407. if (this.items[i].diagnostic == selected.diagnostic)
  16408. return i;
  16409. return -1;
  16410. }
  16411. update() {
  16412. let { diagnostics, selected } = this.view.state.field(lintState);
  16413. let i = 0, needsSync = false, newSelectedItem = null;
  16414. diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
  16415. let found = -1, item;
  16416. for (let j = i; j < this.items.length; j++)
  16417. if (this.items[j].diagnostic == spec.diagnostic) {
  16418. found = j;
  16419. break;
  16420. }
  16421. if (found < 0) {
  16422. item = new PanelItem(this.view, spec.diagnostic);
  16423. this.items.splice(i, 0, item);
  16424. needsSync = true;
  16425. }
  16426. else {
  16427. item = this.items[found];
  16428. if (found > i) {
  16429. this.items.splice(i, found - i);
  16430. needsSync = true;
  16431. }
  16432. }
  16433. if (selected && item.diagnostic == selected.diagnostic) {
  16434. if (!item.dom.hasAttribute("aria-selected")) {
  16435. item.dom.setAttribute("aria-selected", "true");
  16436. newSelectedItem = item;
  16437. }
  16438. }
  16439. else if (item.dom.hasAttribute("aria-selected")) {
  16440. item.dom.removeAttribute("aria-selected");
  16441. }
  16442. i++;
  16443. });
  16444. while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
  16445. needsSync = true;
  16446. this.items.pop();
  16447. }
  16448. if (this.items.length == 0) {
  16449. this.items.push(new PanelItem(this.view, {
  16450. from: -1, to: -1,
  16451. severity: "info",
  16452. message: this.view.state.phrase("No diagnostics")
  16453. }));
  16454. needsSync = true;
  16455. }
  16456. if (newSelectedItem) {
  16457. this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
  16458. this.view.requestMeasure({
  16459. key: this,
  16460. read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
  16461. write: ({ sel, panel }) => {
  16462. if (sel.top < panel.top)
  16463. this.list.scrollTop -= panel.top - sel.top;
  16464. else if (sel.bottom > panel.bottom)
  16465. this.list.scrollTop += sel.bottom - panel.bottom;
  16466. }
  16467. });
  16468. }
  16469. else if (!this.items.length) {
  16470. this.list.removeAttribute("aria-activedescendant");
  16471. }
  16472. if (needsSync)
  16473. this.sync();
  16474. }
  16475. sync() {
  16476. let domPos = this.list.firstChild;
  16477. function rm() {
  16478. let prev = domPos;
  16479. domPos = prev.nextSibling;
  16480. prev.remove();
  16481. }
  16482. for (let item of this.items) {
  16483. if (item.dom.parentNode == this.list) {
  16484. while (domPos != item.dom)
  16485. rm();
  16486. domPos = item.dom.nextSibling;
  16487. }
  16488. else {
  16489. this.list.insertBefore(item.dom, domPos);
  16490. }
  16491. }
  16492. while (domPos)
  16493. rm();
  16494. if (!this.list.firstChild)
  16495. this.list.appendChild(renderDiagnostic(this.view, {
  16496. severity: "info",
  16497. message: this.view.state.phrase("No diagnostics")
  16498. }, true));
  16499. }
  16500. moveSelection(selectedIndex) {
  16501. if (this.items.length == 0)
  16502. return;
  16503. let field = this.view.state.field(lintState);
  16504. let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
  16505. if (!selection)
  16506. return;
  16507. this.view.dispatch({
  16508. selection: { anchor: selection.from, head: selection.to },
  16509. scrollIntoView: true,
  16510. effects: movePanelSelection.of(selection)
  16511. });
  16512. }
  16513. get style() { return "lint"; }
  16514. static open(view) { return new LintPanel(view); }
  16515. }
  16516. function underline(color) {
  16517. if (typeof btoa != "function")
  16518. return "none";
  16519. let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="6" height="3">
  16520. <path d="m0 3 l2 -2 l1 0 l2 2 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>
  16521. </svg>`;
  16522. return `url('data:image/svg+xml;base64,${btoa(svg)}')`;
  16523. }
  16524. const baseTheme$8 = EditorView.baseTheme({
  16525. $diagnostic: {
  16526. padding: "3px 6px 3px 8px",
  16527. marginLeft: "-1px",
  16528. display: "block"
  16529. },
  16530. "$diagnostic.error": { borderLeft: "5px solid #d11" },
  16531. "$diagnostic.warning": { borderLeft: "5px solid orange" },
  16532. "$diagnostic.info": { borderLeft: "5px solid #999" },
  16533. $diagnosticAction: {
  16534. font: "inherit",
  16535. border: "none",
  16536. padding: "2px 4px",
  16537. backgroundColor: "#444",
  16538. color: "white",
  16539. borderRadius: "3px",
  16540. marginLeft: "8px"
  16541. },
  16542. $diagnosticSource: {
  16543. fontSize: "70%",
  16544. opacity: .7
  16545. },
  16546. $lintRange: {
  16547. backgroundPosition: "left bottom",
  16548. backgroundRepeat: "repeat-x"
  16549. },
  16550. "$lintRange.error": { backgroundImage: underline("#d11") },
  16551. "$lintRange.warning": { backgroundImage: underline("orange") },
  16552. "$lintRange.info": { backgroundImage: underline("#999") },
  16553. "$lintRange.active": { backgroundColor: "#ffdd9980" },
  16554. $lintPoint: {
  16555. position: "relative",
  16556. "&:after": {
  16557. content: '""',
  16558. position: "absolute",
  16559. bottom: 0,
  16560. left: "-2px",
  16561. borderLeft: "3px solid transparent",
  16562. borderRight: "3px solid transparent",
  16563. borderBottom: "4px solid #d11"
  16564. }
  16565. },
  16566. "$lintPoint.warning": {
  16567. "&:after": { borderBottomColor: "orange" }
  16568. },
  16569. "$lintPoint.info": {
  16570. "&:after": { borderBottomColor: "#999" }
  16571. },
  16572. "$panel.lint": {
  16573. position: "relative",
  16574. "& ul": {
  16575. maxHeight: "100px",
  16576. overflowY: "auto",
  16577. "& [aria-selected]": {
  16578. backgroundColor: "#ddd",
  16579. "& u": { textDecoration: "underline" }
  16580. },
  16581. "&:focus [aria-selected]": {
  16582. background_fallback: "#bdf",
  16583. backgroundColor: "Highlight",
  16584. color_fallback: "white",
  16585. color: "HighlightText"
  16586. },
  16587. "& u": { textDecoration: "none" },
  16588. padding: 0,
  16589. margin: 0
  16590. },
  16591. "& [name=close]": {
  16592. position: "absolute",
  16593. top: "0",
  16594. right: "2px",
  16595. background: "inherit",
  16596. border: "none",
  16597. font: "inherit",
  16598. padding: 0,
  16599. margin: 0
  16600. }
  16601. },
  16602. "$tooltip.lint": {
  16603. padding: 0,
  16604. margin: 0
  16605. }
  16606. });
  16607. /// This is an extension value that just pulls together a whole lot of
  16608. /// extensions that you might want in a basic editor. It is meant as a
  16609. /// convenient helper to quickly set up CodeMirror without installing
  16610. /// and importing a lot of packages.
  16611. ///
  16612. /// Specifically, it includes...
  16613. ///
  16614. /// - [the default command bindings](#commands.defaultKeymap)
  16615. /// - [line numbers](#gutter.lineNumbers)
  16616. /// - [special character highlighting](#view.highlightSpecialChars)
  16617. /// - [the undo history](#history.history)
  16618. /// - [a fold gutter](#fold.foldGutter)
  16619. /// - [custom selection drawing](#view.drawSelection)
  16620. /// - [multiple selections](#state.EditorState^allowMultipleSelections)
  16621. /// - [reindentation on input](#language.indentOnInput)
  16622. /// - [the default highlight style](#highlight.defaultHighlightStyle)
  16623. /// - [bracket matching](#matchbrackets.bracketMatching)
  16624. /// - [bracket closing](#closebrackets.closeBrackets)
  16625. /// - [autocompletion](#autocomplete.autocompletion)
  16626. /// - [rectangular selection](#rectangular-selection.rectangularSelection)
  16627. /// - [active line highlighting](#view.highlightActiveLine)
  16628. /// - [selection match highlighting](#search.highlightSelectionMatches)
  16629. /// - [search](#search.searchKeymap)
  16630. /// - [commenting](#comment.commentKeymap)
  16631. /// - [linting](#lint.lintKeymap)
  16632. ///
  16633. /// (You'll probably want to add some language package to your setup
  16634. /// too.)
  16635. ///
  16636. /// This package does not allow customization. The idea is that, once
  16637. /// you decide you want to configure your editor more precisely, you
  16638. /// take this package's source (which is just a bunch of imports and
  16639. /// an array literal), copy it into your own code, and adjust it as
  16640. /// desired.
  16641. const basicSetup = [
  16642. lineNumbers(),
  16643. highlightSpecialChars(),
  16644. history(),
  16645. foldGutter(),
  16646. drawSelection(),
  16647. EditorState.allowMultipleSelections.of(true),
  16648. indentOnInput(),
  16649. Prec.fallback(defaultHighlightStyle),
  16650. bracketMatching(),
  16651. closeBrackets(),
  16652. autocompletion(),
  16653. rectangularSelection(),
  16654. highlightActiveLine(),
  16655. highlightSelectionMatches(),
  16656. keymap.of([
  16657. ...closeBracketsKeymap,
  16658. ...defaultKeymap,
  16659. ...searchKeymap,
  16660. ...historyKeymap,
  16661. ...foldKeymap,
  16662. ...commentKeymap,
  16663. ...completionKeymap,
  16664. ...lintKeymap
  16665. ])
  16666. ];
  16667. class BlockContext {
  16668. constructor(type,
  16669. // Used for indentation in list items, markup character in lists
  16670. value, from, hash, end, children, positions) {
  16671. this.type = type;
  16672. this.value = value;
  16673. this.from = from;
  16674. this.hash = hash;
  16675. this.end = end;
  16676. this.children = children;
  16677. this.positions = positions;
  16678. }
  16679. static create(type, value, from, parentHash, end) {
  16680. let hash = (parentHash + (parentHash << 8) + type + (value << 4)) | 0;
  16681. return new BlockContext(type, value, from, hash, end, [], []);
  16682. }
  16683. toTree(nodeSet, end = this.end) {
  16684. let last = this.children.length - 1;
  16685. if (last >= 0)
  16686. end = Math.max(end, this.positions[last] + this.children[last].length + this.from);
  16687. let tree = new Tree(nodeSet.types[this.type], this.children, this.positions, end - this.from).balance(2048);
  16688. stampContext(tree.children, this.hash);
  16689. return tree;
  16690. }
  16691. copy() {
  16692. return new BlockContext(this.type, this.value, this.from, this.hash, this.end, this.children.slice(), this.positions.slice());
  16693. }
  16694. }
  16695. var Type;
  16696. (function (Type) {
  16697. Type[Type["Document"] = 1] = "Document";
  16698. Type[Type["CodeBlock"] = 2] = "CodeBlock";
  16699. Type[Type["FencedCode"] = 3] = "FencedCode";
  16700. Type[Type["Blockquote"] = 4] = "Blockquote";
  16701. Type[Type["HorizontalRule"] = 5] = "HorizontalRule";
  16702. Type[Type["BulletList"] = 6] = "BulletList";
  16703. Type[Type["OrderedList"] = 7] = "OrderedList";
  16704. Type[Type["ListItem"] = 8] = "ListItem";
  16705. Type[Type["ATXHeading"] = 9] = "ATXHeading";
  16706. Type[Type["SetextHeading"] = 10] = "SetextHeading";
  16707. Type[Type["HTMLBlock"] = 11] = "HTMLBlock";
  16708. Type[Type["LinkReference"] = 12] = "LinkReference";
  16709. Type[Type["Paragraph"] = 13] = "Paragraph";
  16710. Type[Type["CommentBlock"] = 14] = "CommentBlock";
  16711. Type[Type["ProcessingInstructionBlock"] = 15] = "ProcessingInstructionBlock";
  16712. // Inline
  16713. Type[Type["Escape"] = 16] = "Escape";
  16714. Type[Type["Entity"] = 17] = "Entity";
  16715. Type[Type["HardBreak"] = 18] = "HardBreak";
  16716. Type[Type["Emphasis"] = 19] = "Emphasis";
  16717. Type[Type["StrongEmphasis"] = 20] = "StrongEmphasis";
  16718. Type[Type["Link"] = 21] = "Link";
  16719. Type[Type["Image"] = 22] = "Image";
  16720. Type[Type["InlineCode"] = 23] = "InlineCode";
  16721. Type[Type["HTMLTag"] = 24] = "HTMLTag";
  16722. Type[Type["Comment"] = 25] = "Comment";
  16723. Type[Type["ProcessingInstruction"] = 26] = "ProcessingInstruction";
  16724. Type[Type["URL"] = 27] = "URL";
  16725. // Smaller tokens
  16726. Type[Type["HeaderMark"] = 28] = "HeaderMark";
  16727. Type[Type["QuoteMark"] = 29] = "QuoteMark";
  16728. Type[Type["ListMark"] = 30] = "ListMark";
  16729. Type[Type["LinkMark"] = 31] = "LinkMark";
  16730. Type[Type["EmphasisMark"] = 32] = "EmphasisMark";
  16731. Type[Type["CodeMark"] = 33] = "CodeMark";
  16732. Type[Type["CodeInfo"] = 34] = "CodeInfo";
  16733. Type[Type["LinkTitle"] = 35] = "LinkTitle";
  16734. Type[Type["LinkLabel"] = 36] = "LinkLabel";
  16735. })(Type || (Type = {}));
  16736. class Line$1 {
  16737. constructor() {
  16738. // The line's text
  16739. this.text = "";
  16740. // The next non-whitespace character
  16741. this.start = 0;
  16742. // The column of the next non-whitespace character
  16743. this.indent = 0;
  16744. // The base indent provided by the contexts (handled so far)
  16745. this.baseIndent = 0;
  16746. // The position corresponding to the base indent
  16747. this.basePos = 0;
  16748. // The number of contexts handled
  16749. this.depth = 0;
  16750. // Any markers (i.e. block quote markers) parsed for the contexts.
  16751. this.markers = [];
  16752. // The character code of the character after this.start
  16753. this.next = -1;
  16754. }
  16755. moveStart(pos) {
  16756. this.start = skipSpace(this.text, pos);
  16757. this.indent = countIndent(this.text, this.start);
  16758. this.next = this.start == this.text.length ? -1 : this.text.charCodeAt(this.start);
  16759. }
  16760. reset(text) {
  16761. this.text = text;
  16762. this.moveStart(0);
  16763. this.indent = countIndent(text, this.start);
  16764. this.baseIndent = this.basePos = 0;
  16765. this.depth = 1;
  16766. while (this.markers.length)
  16767. this.markers.pop();
  16768. }
  16769. }
  16770. function skipForList(cx, p, line) {
  16771. if (line.start == line.text.length ||
  16772. (cx != p.context && line.indent >= p.contextStack[line.depth + 1].value + line.baseIndent))
  16773. return true;
  16774. if (line.indent >= line.baseIndent + 4)
  16775. return false;
  16776. let size = (cx.type == Type.OrderedList ? isOrderedList : isBulletList)(line, p, false);
  16777. return size > 0 &&
  16778. (cx.type != Type.BulletList || isHorizontalRule(line) < 0) &&
  16779. line.text.charCodeAt(line.start + size - 1) == cx.value;
  16780. }
  16781. const SkipMarkup = {
  16782. [Type.Blockquote](cx, p, line) {
  16783. if (line.next != 62 /* '>' */)
  16784. return false;
  16785. line.markers.push(elt(Type.QuoteMark, p._pos + line.start, p._pos + line.start + 1));
  16786. line.basePos = line.start + 2;
  16787. line.baseIndent = line.indent + 2;
  16788. line.moveStart(line.start + 1);
  16789. cx.end = p._pos + line.text.length;
  16790. return true;
  16791. },
  16792. [Type.ListItem](cx, _p, line) {
  16793. if (line.indent < line.baseIndent + cx.value && line.next > -1)
  16794. return false;
  16795. line.baseIndent += cx.value;
  16796. line.basePos += cx.value;
  16797. return true;
  16798. },
  16799. [Type.OrderedList]: skipForList,
  16800. [Type.BulletList]: skipForList,
  16801. [Type.Document]() { return true; }
  16802. };
  16803. let nodeTypes = [NodeType.none];
  16804. for (let i = 1, name; name = Type[i]; i++) {
  16805. nodeTypes[i] = NodeType.define({
  16806. id: i,
  16807. name,
  16808. props: i >= Type.Escape ? [] : [[NodeProp.group, i in SkipMarkup ? ["Block", "BlockContext"] : ["Block", "LeafBlock"]]]
  16809. });
  16810. }
  16811. function space(ch) { return ch == 32 || ch == 9 || ch == 10 || ch == 13; }
  16812. // FIXME more incremental
  16813. function countIndent(line, to) {
  16814. let indent = 0;
  16815. for (let i = 0; i < to; i++)
  16816. indent += line.charCodeAt(i) == 9 ? 4 - indent % 4 : 1;
  16817. return indent;
  16818. }
  16819. function findIndent(line, goal) {
  16820. let i = 0;
  16821. for (let indent = 0; i < line.length && indent < goal; i++)
  16822. indent += line.charCodeAt(i) == 9 ? 4 - indent % 4 : 1;
  16823. return i;
  16824. }
  16825. function skipSpace(line, i = 0) {
  16826. while (i < line.length && space(line.charCodeAt(i)))
  16827. i++;
  16828. return i;
  16829. }
  16830. function skipSpaceBack(line, i, to) {
  16831. while (i > to && space(line.charCodeAt(i - 1)))
  16832. i--;
  16833. return i;
  16834. }
  16835. function isFencedCode(line) {
  16836. if (line.next != 96 && line.next != 126 /* '`~' */)
  16837. return -1;
  16838. let pos = line.start + 1;
  16839. while (pos < line.text.length && line.text.charCodeAt(pos) == line.next)
  16840. pos++;
  16841. if (pos < line.start + 3)
  16842. return -1;
  16843. if (line.next == 96)
  16844. for (let i = pos; i < line.text.length; i++)
  16845. if (line.text.charCodeAt(i) == 96)
  16846. return -1;
  16847. return pos;
  16848. }
  16849. function isBlockquote(line) {
  16850. return line.next != 62 /* '>' */ ? -1 : line.text.charCodeAt(line.start + 1) == 32 ? 2 : 1;
  16851. }
  16852. function isHorizontalRule(line) {
  16853. if (line.next != 42 && line.next != 45 && line.next != 95 /* '-_*' */)
  16854. return -1;
  16855. let count = 1;
  16856. for (let pos = line.start + 1; pos < line.text.length; pos++) {
  16857. let ch = line.text.charCodeAt(pos);
  16858. if (ch == line.next)
  16859. count++;
  16860. else if (!space(ch))
  16861. return -1;
  16862. }
  16863. return count < 3 ? -1 : 1;
  16864. }
  16865. function inList(p, type) {
  16866. return p.context.type == type ||
  16867. p.contextStack.length > 1 && p.contextStack[p.contextStack.length - 2].type == type;
  16868. }
  16869. function isBulletList(line, p, breaking) {
  16870. return (line.next == 45 || line.next == 43 || line.next == 42 /* '-+*' */) &&
  16871. (line.start == line.text.length - 1 || space(line.text.charCodeAt(line.start + 1))) &&
  16872. (!breaking || inList(p, Type.BulletList) || skipSpace(line.text, line.start + 2) < line.text.length) ? 1 : -1;
  16873. }
  16874. function isOrderedList(line, p, breaking) {
  16875. let pos = line.start, next = line.next;
  16876. for (;;) {
  16877. if (next >= 48 && next <= 57 /* '0-9' */)
  16878. pos++;
  16879. else
  16880. break;
  16881. if (pos == line.text.length)
  16882. return -1;
  16883. next = line.text.charCodeAt(pos);
  16884. }
  16885. if (pos == line.start || pos > line.start + 9 ||
  16886. (next != 46 && next != 41 /* '.)' */) ||
  16887. (pos < line.text.length - 1 && !space(line.text.charCodeAt(pos + 1))) ||
  16888. breaking && !inList(p, Type.OrderedList) &&
  16889. (skipSpace(line.text, pos + 1) == line.text.length || pos > line.start + 1 || line.next != 49 /* '1' */))
  16890. return -1;
  16891. return pos + 1 - line.start;
  16892. }
  16893. function isAtxHeading(line) {
  16894. if (line.next != 35 /* '#' */)
  16895. return -1;
  16896. let pos = line.start + 1;
  16897. while (pos < line.text.length && line.text.charCodeAt(pos) == 35)
  16898. pos++;
  16899. if (pos < line.text.length && line.text.charCodeAt(pos) != 32)
  16900. return -1;
  16901. let size = pos - line.start;
  16902. return size > 6 ? -1 : size + 1;
  16903. }
  16904. const EmptyLine = /^[ \t]*$/, CommentEnd = /-->/, ProcessingEnd = /\?>/;
  16905. const HTMLBlockStyle = [
  16906. [/^<(?:script|pre|style)(?:\s|>|$)/i, /<\/(?:script|pre|style)>/i],
  16907. [/^\s*<!--/, CommentEnd],
  16908. [/^\s*<\?/, ProcessingEnd],
  16909. [/^\s*<![A-Z]/, />/],
  16910. [/^\s*<!\[CDATA\[/, /\]\]>/],
  16911. [/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i, EmptyLine],
  16912. [/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i, EmptyLine]
  16913. ];
  16914. function isHTMLBlock(line, _p, breaking) {
  16915. if (line.next != 60 /* '<' */)
  16916. return -1;
  16917. let rest = line.text.slice(line.start);
  16918. for (let i = 0, e = HTMLBlockStyle.length - (breaking ? 1 : 0); i < e; i++)
  16919. if (HTMLBlockStyle[i][0].test(rest))
  16920. return i;
  16921. return -1;
  16922. }
  16923. function isSetextUnderline(line) {
  16924. if (line.next != 45 && line.next != 61 /* '-=' */)
  16925. return -1;
  16926. let pos = line.start + 1;
  16927. while (pos < line.text.length && line.text.charCodeAt(pos) == line.next)
  16928. pos++;
  16929. while (pos < line.text.length && space(line.text.charCodeAt(pos)))
  16930. pos++;
  16931. return pos == line.text.length ? 1 : -1;
  16932. }
  16933. const BreakParagraph = [
  16934. isAtxHeading,
  16935. isFencedCode,
  16936. isBlockquote,
  16937. isBulletList,
  16938. isOrderedList,
  16939. isHorizontalRule,
  16940. isHTMLBlock
  16941. ];
  16942. function getListIndent(text, start) {
  16943. let indentAfter = countIndent(text, start) + 1;
  16944. let indented = countIndent(text, skipSpace(text, start));
  16945. return indented >= indentAfter + 4 ? indentAfter : indented;
  16946. }
  16947. // Rules for parsing blocks. A return value of false means the rule
  16948. // doesn't apply here, true means it does. When true is returned and
  16949. // `p.line` has been updated, the rule is assumed to have consumed a
  16950. // leaf block. Otherwise, it is assumed to have opened a context.
  16951. const Blocks = [
  16952. function indentedCode(p, line) {
  16953. let base = line.baseIndent + 4;
  16954. if (line.indent < base)
  16955. return 0 /* No */;
  16956. let start = findIndent(line.text, base);
  16957. let from = p._pos + start, end = p._pos + line.text.length;
  16958. let marks = [], pendingMarks = [];
  16959. for (; p.nextLine();) {
  16960. if (line.depth < p.contextStack.length)
  16961. break;
  16962. if (line.start == line.text.length) { // Empty
  16963. for (let m of line.markers)
  16964. pendingMarks.push(m);
  16965. }
  16966. else if (line.indent < base) {
  16967. break;
  16968. }
  16969. else {
  16970. if (pendingMarks.length) {
  16971. for (let m of pendingMarks)
  16972. marks.push(m);
  16973. pendingMarks = [];
  16974. }
  16975. for (let m of line.markers)
  16976. marks.push(m);
  16977. end = p._pos + line.text.length;
  16978. }
  16979. }
  16980. if (pendingMarks.length)
  16981. line.markers = pendingMarks.concat(line.markers);
  16982. let nest = !marks.length && p.parser.codeParser && p.parser.codeParser("");
  16983. if (nest)
  16984. p.startNested(new NestedParse(from, nest.startParse(p.input.clip(end), from, p.parseContext), tree => new Tree(p.parser.nodeSet.types[Type.CodeBlock], [tree], [0], end - from)));
  16985. else
  16986. p.addNode(new Buffer(p).writeElements(marks, -from).finish(Type.CodeBlock, end - from), from);
  16987. return 1 /* Done */;
  16988. },
  16989. function fencedCode(p, line) {
  16990. let fenceEnd = isFencedCode(line);
  16991. if (fenceEnd < 0)
  16992. return 0 /* No */;
  16993. let from = p._pos + line.start, ch = line.next, len = fenceEnd - line.start;
  16994. let infoFrom = skipSpace(line.text, fenceEnd), infoTo = skipSpaceBack(line.text, line.text.length, infoFrom);
  16995. let marks = [elt(Type.CodeMark, from, from + len)], info = "";
  16996. if (infoFrom < infoTo) {
  16997. marks.push(elt(Type.CodeInfo, p._pos + infoFrom, p._pos + infoTo));
  16998. info = line.text.slice(infoFrom, infoTo);
  16999. }
  17000. let ownMarks = marks.length, startMarks = ownMarks;
  17001. let codeStart = p._pos + line.text.length + 1, codeEnd = -1;
  17002. for (; p.nextLine();) {
  17003. if (line.depth < p.contextStack.length)
  17004. break;
  17005. for (let m of line.markers)
  17006. marks.push(m);
  17007. let i = line.start;
  17008. if (line.indent - line.baseIndent < 4)
  17009. while (i < line.text.length && line.text.charCodeAt(i) == ch)
  17010. i++;
  17011. if (i - line.start >= len && skipSpace(line.text, i) == line.text.length) {
  17012. marks.push(elt(Type.CodeMark, p._pos + line.start, p._pos + i));
  17013. ownMarks++;
  17014. codeEnd = p._pos - 1;
  17015. p.nextLine();
  17016. break;
  17017. }
  17018. }
  17019. let to = p.prevLineEnd();
  17020. if (codeEnd < 0)
  17021. codeEnd = to;
  17022. // (Don't try to nest if there are blockquote marks in the region.)
  17023. let nest = marks.length == ownMarks && p.parser.codeParser && p.parser.codeParser(info);
  17024. if (nest) {
  17025. p.startNested(new NestedParse(from, nest.startParse(p.input.clip(codeEnd), codeStart, p.parseContext), tree => {
  17026. marks.splice(startMarks, 0, new TreeElement(tree, codeStart));
  17027. return elt(Type.FencedCode, from, to, marks).toTree(p.parser.nodeSet, -from);
  17028. }));
  17029. }
  17030. else {
  17031. p.addNode(new Buffer(p).writeElements(marks, -from).finish(Type.FencedCode, p.prevLineEnd() - from), from);
  17032. }
  17033. return 1 /* Done */;
  17034. },
  17035. function blockquote(p, line) {
  17036. let size = isBlockquote(line);
  17037. if (size < 0)
  17038. return 0 /* No */;
  17039. p.startContext(Type.Blockquote, line.start);
  17040. p.addNode(Type.QuoteMark, p._pos + line.start, p._pos + line.start + 1);
  17041. line.basePos = line.start + size;
  17042. line.baseIndent = line.indent + size;
  17043. line.moveStart(line.start + size);
  17044. return 2 /* Continue */;
  17045. },
  17046. function horizontalRule(p, line) {
  17047. if (isHorizontalRule(line) < 0)
  17048. return 0 /* No */;
  17049. let from = p._pos + line.start;
  17050. p.nextLine();
  17051. p.addNode(Type.HorizontalRule, from);
  17052. return 1 /* Done */;
  17053. },
  17054. function bulletList(p, line) {
  17055. let size = isBulletList(line, p, false);
  17056. if (size < 0)
  17057. return 0 /* No */;
  17058. let cxStart = findIndent(line.text, line.baseIndent);
  17059. if (p.context.type != Type.BulletList)
  17060. p.startContext(Type.BulletList, cxStart, line.next);
  17061. let newBase = getListIndent(line.text, line.start + 1);
  17062. p.startContext(Type.ListItem, cxStart, newBase - line.baseIndent);
  17063. p.addNode(Type.ListMark, p._pos + line.start, p._pos + line.start + size);
  17064. line.baseIndent = newBase;
  17065. line.basePos = findIndent(line.text, newBase);
  17066. line.moveStart(Math.min(line.text.length, line.start + 2));
  17067. return 2 /* Continue */;
  17068. },
  17069. function orderedList(p, line) {
  17070. let size = isOrderedList(line, p, false);
  17071. if (size < 0)
  17072. return 0 /* No */;
  17073. let cxStart = findIndent(line.text, line.baseIndent);
  17074. if (p.context.type != Type.OrderedList)
  17075. p.startContext(Type.OrderedList, cxStart, line.text.charCodeAt(line.start + size - 1));
  17076. let newBase = getListIndent(line.text, line.start + size);
  17077. p.startContext(Type.ListItem, cxStart, newBase - line.baseIndent);
  17078. p.addNode(Type.ListMark, p._pos + line.start, p._pos + line.start + size);
  17079. line.baseIndent = newBase;
  17080. line.basePos = findIndent(line.text, newBase);
  17081. line.moveStart(Math.min(line.text.length, line.start + size + 1));
  17082. return 2 /* Continue */;
  17083. },
  17084. function atxHeading(p, line) {
  17085. let size = isAtxHeading(line);
  17086. if (size < 0)
  17087. return 0 /* No */;
  17088. let off = line.start, from = p._pos + off;
  17089. let endOfSpace = skipSpaceBack(line.text, line.text.length, off), after = endOfSpace;
  17090. while (after > off && line.text.charCodeAt(after - 1) == line.next)
  17091. after--;
  17092. if (after == endOfSpace || after == off || !space(line.text.charCodeAt(after - 1)))
  17093. after = line.text.length;
  17094. let buf = new Buffer(p)
  17095. .write(Type.HeaderMark, 0, size - 1)
  17096. .writeElements(parseInline(p, line.text.slice(off + size, after)), size);
  17097. if (after < line.text.length)
  17098. buf.write(Type.HeaderMark, after - off, endOfSpace - off);
  17099. let node = buf.finish(Type.ATXHeading, line.text.length - off);
  17100. p.nextLine();
  17101. p.addNode(node, from);
  17102. return 1 /* Done */;
  17103. },
  17104. function htmlBlock(p, line) {
  17105. let type = isHTMLBlock(line, p, false);
  17106. if (type < 0)
  17107. return 0 /* No */;
  17108. let from = p._pos + line.start, end = HTMLBlockStyle[type][1];
  17109. let marks = [], trailing = end != EmptyLine;
  17110. while (!end.test(line.text) && p.nextLine()) {
  17111. if (line.depth < p.contextStack.length) {
  17112. trailing = false;
  17113. break;
  17114. }
  17115. for (let m of line.markers)
  17116. marks.push(m);
  17117. }
  17118. if (trailing)
  17119. p.nextLine();
  17120. let nodeType = end == CommentEnd ? Type.CommentBlock : end == ProcessingEnd ? Type.ProcessingInstructionBlock : Type.HTMLBlock;
  17121. let to = p.prevLineEnd();
  17122. if (!marks.length && nodeType == Type.HTMLBlock && p.parser.htmlParser) {
  17123. p.startNested(new NestedParse(from, p.parser.htmlParser.startParse(p.input.clip(to), from, p.parseContext), tree => new Tree(p.parser.nodeSet.types[nodeType], [tree], [0], to - from)));
  17124. return 1 /* Done */;
  17125. }
  17126. p.addNode(new Buffer(p).writeElements(marks, -from).finish(nodeType, to - from), from);
  17127. return 1 /* Done */;
  17128. },
  17129. function paragraph(p, line) {
  17130. let from = p._pos + line.start, content = line.text.slice(line.start), marks = [];
  17131. let heading = false;
  17132. lines: for (; p.nextLine();) {
  17133. if (line.start == line.text.length)
  17134. break;
  17135. if (line.indent < line.baseIndent + 4) {
  17136. if (isSetextUnderline(line) > -1 && line.depth == p.contextStack.length) {
  17137. for (let m of line.markers)
  17138. marks.push(m);
  17139. heading = true;
  17140. break;
  17141. }
  17142. for (let check of BreakParagraph)
  17143. if (check(line, p, true) >= 0)
  17144. break lines;
  17145. }
  17146. for (let m of line.markers)
  17147. marks.push(m);
  17148. content += "\n";
  17149. content += line.text;
  17150. }
  17151. content = clearMarks(content, marks, from);
  17152. for (;;) {
  17153. let ref = parseLinkReference(p, content);
  17154. if (!ref)
  17155. break;
  17156. p.addNode(ref, from);
  17157. if (content.length <= ref.length + 1 && !heading)
  17158. return 1 /* Done */;
  17159. content = content.slice(ref.length + 1);
  17160. from += ref.length + 1;
  17161. // FIXME these are dropped, but should be added to the ref (awkward!)
  17162. while (marks.length && marks[0].to <= from)
  17163. marks.shift();
  17164. }
  17165. let inline = injectMarks(parseInline(p, content), marks, from);
  17166. if (heading) {
  17167. let node = new Buffer(p)
  17168. .writeElements(inline)
  17169. .write(Type.HeaderMark, p._pos - from, p._pos + line.text.length - from)
  17170. .finish(Type.SetextHeading, p._pos + line.text.length - from);
  17171. p.nextLine();
  17172. p.addNode(node, from);
  17173. }
  17174. else {
  17175. p.addNode(new Buffer(p)
  17176. .writeElements(inline)
  17177. .finish(Type.Paragraph, content.length), from);
  17178. }
  17179. return 1 /* Done */;
  17180. }
  17181. ];
  17182. class NestedParse {
  17183. constructor(from, parser, finish) {
  17184. this.from = from;
  17185. this.parser = parser;
  17186. this.finish = finish;
  17187. }
  17188. }
  17189. class Parse {
  17190. constructor(parser, input, startPos, parseContext) {
  17191. this.parser = parser;
  17192. this.input = input;
  17193. this.parseContext = parseContext;
  17194. this.line = new Line$1();
  17195. this.atEnd = false;
  17196. this.nested = null;
  17197. this._pos = startPos;
  17198. this.context = BlockContext.create(Type.Document, 0, this._pos, 0, 0);
  17199. this.contextStack = [this.context];
  17200. this.fragments = (parseContext === null || parseContext === void 0 ? void 0 : parseContext.fragments) ? new FragmentCursor(parseContext.fragments, input) : null;
  17201. this.updateLine(input.lineAfter(this._pos));
  17202. }
  17203. get pos() {
  17204. return this.nested ? this.nested.parser.pos : this._pos;
  17205. }
  17206. advance() {
  17207. if (this.nested) {
  17208. let done = this.nested.parser.advance();
  17209. if (done) {
  17210. this.addNode(this.nested.finish(done), this.nested.from);
  17211. this.nested = null;
  17212. }
  17213. return null;
  17214. }
  17215. let { line } = this;
  17216. for (;;) {
  17217. while (line.depth < this.contextStack.length)
  17218. this.finishContext();
  17219. for (let mark of line.markers)
  17220. this.addNode(mark.type, mark.from, mark.to);
  17221. if (line.start < line.text.length)
  17222. break;
  17223. // Empty line
  17224. if (!this.nextLine())
  17225. return this.finish();
  17226. }
  17227. if (this.fragments && this.reuseFragment(line.basePos))
  17228. return null;
  17229. for (;;) {
  17230. for (let type of Blocks) {
  17231. let result = type(this, line);
  17232. if (result != 0 /* No */) {
  17233. if (result == 1 /* Done */)
  17234. return null;
  17235. break;
  17236. }
  17237. }
  17238. }
  17239. }
  17240. reuseFragment(start) {
  17241. if (!this.fragments.moveTo(this._pos + start, this._pos) ||
  17242. !this.fragments.matches(this.context.hash))
  17243. return false;
  17244. let taken = this.fragments.takeNodes(this);
  17245. if (!taken)
  17246. return false;
  17247. this._pos += taken;
  17248. if (this._pos < this.input.length) {
  17249. this._pos++;
  17250. this.updateLine(this.input.lineAfter(this._pos));
  17251. }
  17252. else {
  17253. this.atEnd = true;
  17254. this.updateLine("");
  17255. }
  17256. return true;
  17257. }
  17258. nextLine() {
  17259. this._pos += this.line.text.length;
  17260. if (this._pos >= this.input.length) {
  17261. this.atEnd = true;
  17262. this.updateLine("");
  17263. return false;
  17264. }
  17265. else {
  17266. this._pos++;
  17267. this.updateLine(this.input.lineAfter(this._pos));
  17268. return true;
  17269. }
  17270. }
  17271. updateLine(text) {
  17272. let { line } = this;
  17273. line.reset(text);
  17274. for (; line.depth < this.contextStack.length; line.depth++) {
  17275. let cx = this.contextStack[line.depth], handler = SkipMarkup[cx.type];
  17276. if (!handler)
  17277. throw new Error("Unhandled block context " + Type[cx.type]);
  17278. if (!handler(cx, this, line))
  17279. break;
  17280. }
  17281. }
  17282. prevLineEnd() { return this.atEnd ? this._pos : this._pos - 1; }
  17283. startContext(type, start, value = 0) {
  17284. this.context = BlockContext.create(type, value, this._pos + start, this.context.hash, this._pos + this.line.text.length);
  17285. this.contextStack.push(this.context);
  17286. }
  17287. addNode(block, from, to) {
  17288. if (typeof block == "number")
  17289. block = new Tree(this.parser.nodeSet.types[block], none$7, none$7, (to !== null && to !== void 0 ? to : this.prevLineEnd()) - from);
  17290. this.context.children.push(block);
  17291. this.context.positions.push(from - this.context.from);
  17292. }
  17293. startNested(parse) {
  17294. this.nested = parse;
  17295. }
  17296. finishContext() {
  17297. this.context = finishContext(this.contextStack, this.parser.nodeSet);
  17298. }
  17299. finish() {
  17300. while (this.contextStack.length > 1)
  17301. this.finishContext();
  17302. return this.context.toTree(this.parser.nodeSet, this._pos);
  17303. }
  17304. forceFinish() {
  17305. let cx = this.contextStack.map(cx => cx.copy());
  17306. if (this.nested) {
  17307. let inner = cx[cx.length - 1];
  17308. inner.children.push(this.nested.parser.forceFinish());
  17309. inner.positions.push(this.nested.from - inner.from);
  17310. }
  17311. while (cx.length > 1)
  17312. finishContext(cx, this.parser.nodeSet);
  17313. return cx[0].toTree(this.parser.nodeSet, this._pos);
  17314. }
  17315. }
  17316. class MarkdownParser {
  17317. /// @internal
  17318. constructor(nodeSet, codeParser, htmlParser) {
  17319. this.nodeSet = nodeSet;
  17320. this.codeParser = codeParser;
  17321. this.htmlParser = htmlParser;
  17322. }
  17323. /// Start a parse on the given input.
  17324. startParse(input, startPos = 0, parseContext = {}) {
  17325. return new Parse(this, input, startPos, parseContext);
  17326. }
  17327. /// Reconfigure the parser.
  17328. configure(config) {
  17329. return new MarkdownParser(config.props ? this.nodeSet.extend(...config.props) : this.nodeSet, config.codeParser || this.codeParser, config.htmlParser || this.htmlParser);
  17330. }
  17331. }
  17332. const parser = new MarkdownParser(new NodeSet(nodeTypes), null, null);
  17333. function finishContext(stack, nodeSet) {
  17334. let cx = stack.pop();
  17335. let top = stack[stack.length - 1];
  17336. top.children.push(cx.toTree(nodeSet));
  17337. top.positions.push(cx.from - top.from);
  17338. return top;
  17339. }
  17340. const none$7 = [];
  17341. class Buffer {
  17342. constructor(p) {
  17343. this.content = [];
  17344. this.nodes = [];
  17345. this.nodeSet = p.parser.nodeSet;
  17346. }
  17347. write(type, from, to, children = 0) {
  17348. this.content.push(type, from, to, 4 + children * 4);
  17349. return this;
  17350. }
  17351. writeElements(elts, offset = 0) {
  17352. for (let e of elts)
  17353. e.writeTo(this, offset);
  17354. return this;
  17355. }
  17356. finish(type, length) {
  17357. return Tree.build({
  17358. buffer: this.content,
  17359. nodeSet: this.nodeSet,
  17360. reused: this.nodes,
  17361. topID: type,
  17362. length
  17363. });
  17364. }
  17365. }
  17366. class Element {
  17367. constructor(type, from, to, children = null) {
  17368. this.type = type;
  17369. this.from = from;
  17370. this.to = to;
  17371. this.children = children;
  17372. }
  17373. writeTo(buf, offset) {
  17374. let startOff = buf.content.length;
  17375. if (this.children)
  17376. buf.writeElements(this.children, offset);
  17377. buf.content.push(this.type, this.from + offset, this.to + offset, buf.content.length + 4 - startOff);
  17378. }
  17379. toTree(nodeSet, offset) {
  17380. return new Tree(nodeSet.types[this.type], this.children ? this.children.map(ch => ch.toTree(nodeSet, this.from)) : [], this.children ? this.children.map(ch => ch.from + offset) : [], this.to - this.from);
  17381. }
  17382. }
  17383. class TreeElement {
  17384. constructor(tree, from) {
  17385. this.tree = tree;
  17386. this.from = from;
  17387. }
  17388. get to() { return this.from + this.tree.length; }
  17389. writeTo(buf, offset) {
  17390. buf.nodes.push(this.tree);
  17391. buf.content.push(buf.nodes.length - 1, this.from + offset, this.to + offset, -1);
  17392. }
  17393. toTree() { return this.tree; }
  17394. }
  17395. function elt(type, from, to, children) {
  17396. return new Element(type, from, to, children);
  17397. }
  17398. class InlineMarker {
  17399. constructor(type, from, to, value) {
  17400. this.type = type;
  17401. this.from = from;
  17402. this.to = to;
  17403. this.value = value;
  17404. }
  17405. }
  17406. const Escapable = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
  17407. let Punctuation = /[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\u2010-\u2027]/;
  17408. try {
  17409. Punctuation = /[\p{Pc}|\p{Pd}|\p{Pe}|\p{Pf}|\p{Pi}|\p{Po}|\p{Ps}]/u;
  17410. }
  17411. catch (_) { }
  17412. const InlineTokens = [
  17413. function escape(cx, next, start) {
  17414. if (next != 92 /* '\\' */ || start == cx.text.length - 1)
  17415. return -1;
  17416. let escaped = cx.text.charCodeAt(start + 1);
  17417. for (let i = 0; i < Escapable.length; i++)
  17418. if (Escapable.charCodeAt(i) == escaped)
  17419. return cx.append(elt(Type.Escape, start, start + 2));
  17420. return -1;
  17421. },
  17422. function entity(cx, next, start) {
  17423. if (next != 38 /* '&' */)
  17424. return -1;
  17425. let m = /^(?:#\d+|#x[a-f\d]+|\w+);/i.exec(cx.text.slice(start + 1, start + 31));
  17426. return m ? cx.append(elt(Type.Entity, start, start + 1 + m[0].length)) : -1;
  17427. },
  17428. function code(cx, next, start) {
  17429. if (next != 96 /* '`' */ || start && cx.text.charCodeAt(start - 1) == 96)
  17430. return -1;
  17431. let pos = start + 1;
  17432. while (pos < cx.text.length && cx.text.charCodeAt(pos) == 96)
  17433. pos++;
  17434. let size = pos - start, curSize = 0;
  17435. for (; pos < cx.text.length; pos++) {
  17436. if (cx.text.charCodeAt(pos) == 96) {
  17437. curSize++;
  17438. if (curSize == size && cx.text.charCodeAt(pos + 1) != 96)
  17439. return cx.append(elt(Type.InlineCode, start, pos + 1, [
  17440. elt(Type.CodeMark, start, start + size),
  17441. elt(Type.CodeMark, pos + 1 - size, pos + 1)
  17442. ]));
  17443. }
  17444. else {
  17445. curSize = 0;
  17446. }
  17447. }
  17448. return -1;
  17449. },
  17450. function htmlTagOrURL(cx, next, start) {
  17451. if (next != 60 /* '<' */ || start == cx.text.length - 1)
  17452. return -1;
  17453. let after = cx.text.slice(start + 1);
  17454. let url = /^(?:[a-z][-\w+.]+:[^\s>]+|[a-z\d.!#$%&'*+/=?^_`{|}~-]+@[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?)*)>/i.exec(after);
  17455. if (url)
  17456. return cx.append(elt(Type.URL, start, start + 1 + url[0].length));
  17457. let comment = /^!--[^>](?:-[^-]|[^-])*?-->/i.exec(after);
  17458. if (comment)
  17459. return cx.append(elt(Type.Comment, start, start + 1 + comment[0].length));
  17460. let procInst = /^\?[^]*?\?>/.exec(after);
  17461. if (procInst)
  17462. return cx.append(elt(Type.ProcessingInstruction, start, start + 1 + procInst[0].length));
  17463. let m = /^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(after);
  17464. if (!m)
  17465. return -1;
  17466. let children = [];
  17467. if (cx.parser.htmlParser) {
  17468. let p = cx.parser.htmlParser.startParse(stringInput(cx.text.slice(start, start + 1 + m[0].length)), 0, {}), tree;
  17469. while (!(tree = p.advance())) { }
  17470. children = tree.children.map((ch, i) => new TreeElement(ch, start + tree.positions[i]));
  17471. }
  17472. return cx.append(elt(Type.HTMLTag, start, start + 1 + m[0].length, children));
  17473. },
  17474. function emphasis(cx, next, start) {
  17475. if (next != 95 && next != 42)
  17476. return -1;
  17477. let pos = start + 1;
  17478. while (pos < cx.text.length && cx.text.charCodeAt(pos) == next)
  17479. pos++;
  17480. let before = cx.text.charAt(start - 1), after = cx.text.charAt(pos);
  17481. let pBefore = Punctuation.test(before), pAfter = Punctuation.test(after);
  17482. let sBefore = /\s|^$/.test(before), sAfter = /\s|^$/.test(after);
  17483. let leftFlanking = !sAfter && (!pAfter || sBefore || pBefore);
  17484. let rightFlanking = !sBefore && (!pBefore || sAfter || pAfter);
  17485. let canOpen = leftFlanking && (next == 42 || !rightFlanking || pBefore);
  17486. let canClose = rightFlanking && (next == 42 || !leftFlanking || pAfter);
  17487. return cx.append(new InlineMarker(Type.Emphasis, start, pos, (canOpen ? 1 /* Open */ : 0) | (canClose ? 2 /* Close */ : 0)));
  17488. },
  17489. function hardBreak(cx, next, start) {
  17490. if (next == 92 /* '\\' */ && cx.text.charCodeAt(start + 1) == 10 /* '\n' */)
  17491. return cx.append(elt(Type.HardBreak, start, start + 2));
  17492. if (next == 32) {
  17493. let pos = start + 1;
  17494. while (pos < cx.text.length && cx.text.charCodeAt(pos) == 32)
  17495. pos++;
  17496. if (cx.text.charCodeAt(pos) == 10 && pos >= start + 2)
  17497. return cx.append(elt(Type.HardBreak, start, pos + 1));
  17498. }
  17499. return -1;
  17500. },
  17501. function linkOpen(cx, next, start) {
  17502. return next == 91 /* '[' */ ? cx.append(new InlineMarker(Type.Link, start, start + 1, 1)) : -1;
  17503. },
  17504. function imageOpen(cx, next, start) {
  17505. return next == 33 /* '!' */ && start < cx.text.length - 1 && cx.text.charCodeAt(start + 1) == 91 /* '[' */
  17506. ? cx.append(new InlineMarker(Type.Image, start, start + 2, 1)) : -1;
  17507. },
  17508. function linkEnd(cx, next, start) {
  17509. if (next != 93 /* ']' */)
  17510. return -1;
  17511. for (let i = cx.parts.length - 1; i >= 0; i--) {
  17512. let part = cx.parts[i];
  17513. if (part instanceof InlineMarker && (part.type == Type.Link || part.type == Type.Image)) {
  17514. if (!part.value) {
  17515. cx.parts[i] = null;
  17516. return -1;
  17517. }
  17518. if (skipSpace(cx.text, part.to) == start && !/[(\[]/.test(cx.text[start + 1]))
  17519. return -1;
  17520. let content = cx.resolveMarkers(i + 1);
  17521. cx.parts.length = i;
  17522. let link = cx.parts[i] = finishLink(cx.text, content, part.type, part.from, start + 1);
  17523. for (let j = 0; j < i; j++) {
  17524. let p = cx.parts[j];
  17525. if (part.type == Type.Link && p instanceof InlineMarker && p.type == Type.Link)
  17526. p.value = 0;
  17527. }
  17528. return link.to;
  17529. }
  17530. }
  17531. return -1;
  17532. },
  17533. ];
  17534. function finishLink(text, content, type, start, startPos) {
  17535. let next = startPos < text.length ? text.charCodeAt(startPos) : -1, endPos = startPos;
  17536. content.unshift(elt(Type.LinkMark, start, start + (type == Type.Image ? 2 : 1)));
  17537. content.push(elt(Type.LinkMark, startPos - 1, startPos));
  17538. if (next == 40 /* '(' */) {
  17539. let pos = skipSpace(text, startPos + 1);
  17540. let dest = parseURL(text, pos), title;
  17541. if (dest) {
  17542. pos = skipSpace(text, dest.to);
  17543. title = parseLinkTitle(text, pos);
  17544. if (title)
  17545. pos = skipSpace(text, title.to);
  17546. }
  17547. if (text.charCodeAt(pos) == 41 /* ')' */) {
  17548. content.push(elt(Type.LinkMark, startPos, startPos + 1));
  17549. endPos = pos + 1;
  17550. if (dest)
  17551. content.push(dest);
  17552. if (title)
  17553. content.push(title);
  17554. content.push(elt(Type.LinkMark, pos, endPos));
  17555. }
  17556. }
  17557. else if (next == 91 /* '[' */) {
  17558. let label = parseLinkLabel(text, startPos, false);
  17559. if (label) {
  17560. content.push(label);
  17561. endPos = label.to;
  17562. }
  17563. }
  17564. return elt(type, start, endPos, content);
  17565. }
  17566. function parseURL(text, start) {
  17567. let next = text.charCodeAt(start);
  17568. if (next == 60 /* '<' */) {
  17569. for (let pos = start + 1; pos < text.length; pos++) {
  17570. let ch = text.charCodeAt(pos);
  17571. if (ch == 62 /* '>' */)
  17572. return elt(Type.URL, start, pos + 1);
  17573. if (ch == 60 || ch == 10 /* '<\n' */)
  17574. break;
  17575. }
  17576. return null;
  17577. }
  17578. else {
  17579. let depth = 0, pos = start;
  17580. for (let escaped = false; pos < text.length; pos++) {
  17581. let ch = text.charCodeAt(pos);
  17582. if (space(ch)) {
  17583. break;
  17584. }
  17585. else if (escaped) {
  17586. escaped = false;
  17587. }
  17588. else if (ch == 40 /* '(' */) {
  17589. depth++;
  17590. }
  17591. else if (ch == 41 /* ')' */) {
  17592. if (!depth)
  17593. break;
  17594. depth--;
  17595. }
  17596. else if (ch == 92 /* '\\' */) {
  17597. escaped = true;
  17598. }
  17599. }
  17600. return pos > start ? elt(Type.URL, start, pos) : null;
  17601. }
  17602. }
  17603. function parseLinkTitle(text, start) {
  17604. let next = text.charCodeAt(start);
  17605. if (next != 39 && next != 34 && next != 40 /* '"\'(' */)
  17606. return null;
  17607. let end = next == 40 ? 41 : next;
  17608. for (let pos = start + 1, escaped = false; pos < text.length; pos++) {
  17609. let ch = text.charCodeAt(pos);
  17610. if (escaped)
  17611. escaped = false;
  17612. else if (ch == end)
  17613. return elt(Type.LinkTitle, start, pos + 1);
  17614. else if (ch == 92 /* '\\' */)
  17615. escaped = true;
  17616. }
  17617. return null;
  17618. }
  17619. function parseLinkLabel(text, start, requireNonWS) {
  17620. for (let escaped = false, pos = start + 1, end = Math.min(text.length, pos + 999); pos < end; pos++) {
  17621. let ch = text.charCodeAt(pos);
  17622. if (escaped)
  17623. escaped = false;
  17624. else if (ch == 93 /* ']' */)
  17625. return requireNonWS ? null : elt(Type.LinkLabel, start, pos + 1);
  17626. else {
  17627. if (requireNonWS && !space(ch))
  17628. requireNonWS = false;
  17629. if (ch == 91 /* '[' */)
  17630. break;
  17631. else if (ch == 92 /* '\\' */)
  17632. escaped = true;
  17633. }
  17634. }
  17635. return null;
  17636. }
  17637. function lineEnd(text, pos) {
  17638. for (; pos < text.length; pos++) {
  17639. let next = text.charCodeAt(pos);
  17640. if (next == 10)
  17641. break;
  17642. if (!space(next))
  17643. return -1;
  17644. }
  17645. return pos;
  17646. }
  17647. function parseLinkReference(p, text) {
  17648. if (text.charCodeAt(0) != 91 /* '[' */)
  17649. return null;
  17650. let ref = parseLinkLabel(text, 0, true);
  17651. if (!ref || text.charCodeAt(ref.to) != 58 /* ':' */)
  17652. return null;
  17653. let elts = [ref, elt(Type.LinkMark, ref.to, ref.to + 1)];
  17654. let url = parseURL(text, skipSpace(text, ref.to + 1));
  17655. if (!url)
  17656. return null;
  17657. elts.push(url);
  17658. let pos = skipSpace(text, url.to), title, end = 0;
  17659. if (pos > url.to && (title = parseLinkTitle(text, pos))) {
  17660. let afterURL = lineEnd(text, title.to);
  17661. if (afterURL > 0) {
  17662. elts.push(title);
  17663. end = afterURL;
  17664. }
  17665. }
  17666. if (end == 0)
  17667. end = lineEnd(text, url.to);
  17668. return end < 0 ? null : new Buffer(p).writeElements(elts).finish(Type.LinkReference, end);
  17669. }
  17670. class InlineContext {
  17671. constructor(parser, text) {
  17672. this.parser = parser;
  17673. this.text = text;
  17674. this.parts = [];
  17675. }
  17676. append(elt) {
  17677. this.parts.push(elt);
  17678. return elt.to;
  17679. }
  17680. resolveMarkers(from) {
  17681. for (let i = from; i < this.parts.length; i++) {
  17682. let close = this.parts[i];
  17683. if (!(close instanceof InlineMarker && close.type == Type.Emphasis && (close.value & 2 /* Close */)))
  17684. continue;
  17685. let type = this.text.charCodeAt(close.from), closeSize = close.to - close.from;
  17686. let open, openSize = 0, j = i - 1;
  17687. for (; j >= from; j--) {
  17688. let part = this.parts[j];
  17689. if (!(part instanceof InlineMarker && (part.value & 1 /* Open */) && this.text.charCodeAt(part.from) == type))
  17690. continue;
  17691. openSize = part.to - part.from;
  17692. if (!((close.value & 1 /* Open */) || (part.value & 2 /* Close */)) ||
  17693. (openSize + closeSize) % 3 || (openSize % 3 == 0 && closeSize % 3 == 0)) {
  17694. open = part;
  17695. break;
  17696. }
  17697. }
  17698. if (!open)
  17699. continue;
  17700. let size = Math.min(2, openSize, closeSize);
  17701. let start = open.to - size, end = close.from + size, content = [elt(Type.EmphasisMark, start, open.to)];
  17702. for (let k = j + 1; k < i; k++) {
  17703. if (this.parts[k] instanceof Element)
  17704. content.push(this.parts[k]);
  17705. this.parts[k] = null;
  17706. }
  17707. content.push(elt(Type.EmphasisMark, close.from, end));
  17708. let element = elt(size == 1 ? Type.Emphasis : Type.StrongEmphasis, open.to - size, close.from + size, content);
  17709. this.parts[j] = open.from == start ? null : new InlineMarker(open.type, open.from, start, open.value);
  17710. let keep = this.parts[i] = close.to == end ? null : new InlineMarker(close.type, end, close.to, close.value);
  17711. if (keep)
  17712. this.parts.splice(i, 0, element);
  17713. else
  17714. this.parts[i] = element;
  17715. }
  17716. let result = [];
  17717. for (let i = from; i < this.parts.length; i++) {
  17718. let part = this.parts[i];
  17719. if (part instanceof Element)
  17720. result.push(part);
  17721. }
  17722. return result;
  17723. }
  17724. }
  17725. function parseInline(p, text) {
  17726. let cx = new InlineContext(p.parser, text);
  17727. outer: for (let pos = 0; pos < text.length;) {
  17728. let next = text.charCodeAt(pos);
  17729. for (let token of InlineTokens) {
  17730. let result = token(cx, next, pos);
  17731. if (result >= 0) {
  17732. pos = result;
  17733. continue outer;
  17734. }
  17735. }
  17736. pos++;
  17737. }
  17738. return cx.resolveMarkers(0);
  17739. }
  17740. function clearMarks(content, marks, offset) {
  17741. if (!marks.length)
  17742. return content;
  17743. let result = "", pos = 0;
  17744. for (let m of marks) {
  17745. let from = m.from - offset, to = m.to - offset;
  17746. result += content.slice(pos, from);
  17747. for (let i = from; i < to; i++)
  17748. result += " ";
  17749. pos = to;
  17750. }
  17751. result += content.slice(pos);
  17752. return result;
  17753. }
  17754. function injectMarks(elts, marks, offset) {
  17755. let eI = 0;
  17756. for (let mark of marks) {
  17757. let m = elt(mark.type, mark.from - offset, mark.to - offset);
  17758. while (eI < elts.length && elts[eI].to < m.to)
  17759. eI++;
  17760. if (eI < elts.length && elts[eI].from < m.from) {
  17761. let e = elts[eI];
  17762. if (e instanceof Element)
  17763. elts[eI] = new Element(e.type, e.from, e.to, e.children ? injectMarks(e.children.slice(), [m], 0) : [m]);
  17764. }
  17765. else {
  17766. elts.splice(eI++, 0, m);
  17767. }
  17768. }
  17769. return elts;
  17770. }
  17771. const ContextHash = new WeakMap();
  17772. function stampContext(nodes, hash) {
  17773. for (let n of nodes) {
  17774. ContextHash.set(n, hash);
  17775. if (n instanceof Tree && n.type.isAnonymous)
  17776. stampContext(n.children, hash);
  17777. }
  17778. }
  17779. // These are blocks that can span blank lines, and should thus only be
  17780. // reused if their next sibling is also being reused.
  17781. const NotLast = [Type.CodeBlock, Type.ListItem, Type.OrderedList, Type.BulletList];
  17782. class FragmentCursor {
  17783. constructor(fragments, input) {
  17784. this.fragments = fragments;
  17785. this.input = input;
  17786. // Index into fragment array
  17787. this.i = 0;
  17788. // Active fragment
  17789. this.fragment = null;
  17790. this.fragmentEnd = -1;
  17791. // Cursor into the current fragment, if any. When `moveTo` returns
  17792. // true, this points at the first block after `pos`.
  17793. this.cursor = null;
  17794. if (fragments.length)
  17795. this.fragment = fragments[this.i++];
  17796. }
  17797. nextFragment() {
  17798. this.fragment = this.i < this.fragments.length ? this.fragments[this.i++] : null;
  17799. this.cursor = null;
  17800. this.fragmentEnd = -1;
  17801. }
  17802. moveTo(pos, lineStart) {
  17803. while (this.fragment && this.fragment.to <= pos)
  17804. this.nextFragment();
  17805. if (!this.fragment || this.fragment.from > (pos ? pos - 1 : 0))
  17806. return false;
  17807. if (this.fragmentEnd < 0) {
  17808. let end = this.fragment.to;
  17809. while (end > 0 && this.input.get(end - 1) != 10)
  17810. end--;
  17811. this.fragmentEnd = end ? end - 1 : 0;
  17812. }
  17813. let c = this.cursor;
  17814. if (!c) {
  17815. c = this.cursor = this.fragment.tree.cursor();
  17816. c.firstChild();
  17817. }
  17818. let rPos = pos + this.fragment.offset;
  17819. while (c.to <= rPos)
  17820. if (!c.parent())
  17821. return false;
  17822. for (;;) {
  17823. if (c.from >= rPos)
  17824. return this.fragment.from <= lineStart;
  17825. if (!c.childAfter(rPos))
  17826. return false;
  17827. }
  17828. }
  17829. matches(hash) {
  17830. let tree = this.cursor.tree;
  17831. return tree && ContextHash.get(tree) == hash;
  17832. }
  17833. takeNodes(p) {
  17834. let cur = this.cursor, off = this.fragment.offset;
  17835. let start = p._pos, end = start, blockI = p.context.children.length;
  17836. let prevEnd = end, prevI = blockI;
  17837. for (;;) {
  17838. if (cur.to - off >= this.fragmentEnd) {
  17839. if (cur.type.isAnonymous && cur.firstChild())
  17840. continue;
  17841. break;
  17842. }
  17843. p.addNode(cur.tree, cur.from - off);
  17844. // Taken content must always end in a block, because incremental
  17845. // parsing happens on block boundaries. Never stop directly
  17846. // after an indented code block, since those can continue after
  17847. // any number of blank lines.
  17848. if (cur.type.is("Block")) {
  17849. if (NotLast.indexOf(cur.type.id) < 0) {
  17850. end = cur.to - off;
  17851. blockI = p.context.children.length;
  17852. }
  17853. else {
  17854. end = prevEnd;
  17855. blockI = prevI;
  17856. prevEnd = cur.to - off;
  17857. prevI = p.context.children.length;
  17858. }
  17859. }
  17860. if (!cur.nextSibling())
  17861. break;
  17862. }
  17863. while (p.context.children.length > blockI) {
  17864. p.context.children.pop();
  17865. p.context.positions.pop();
  17866. }
  17867. return end - start;
  17868. }
  17869. }
  17870. /// A parse stack. These are used internally by the parser to track
  17871. /// parsing progress. They also provide some properties and methods
  17872. /// that external code such as a tokenizer can use to get information
  17873. /// about the parse state.
  17874. class Stack {
  17875. /// @internal
  17876. constructor(
  17877. /// A group of values that the stack will share with all
  17878. /// split instances
  17879. ///@internal
  17880. cx,
  17881. /// Holds state, pos, value stack pos (15 bits array index, 15 bits
  17882. /// buffer index) triplets for all but the top state
  17883. /// @internal
  17884. stack,
  17885. /// The current parse state @internal
  17886. state,
  17887. // The position at which the next reduce should take place. This
  17888. // can be less than `this.pos` when skipped expressions have been
  17889. // added to the stack (which should be moved outside of the next
  17890. // reduction)
  17891. /// @internal
  17892. reducePos,
  17893. /// The input position up to which this stack has parsed.
  17894. pos,
  17895. /// The dynamic score of the stack, including dynamic precedence
  17896. /// and error-recovery penalties
  17897. /// @internal
  17898. score,
  17899. // The output buffer. Holds (type, start, end, size) quads
  17900. // representing nodes created by the parser, where `size` is
  17901. // amount of buffer array entries covered by this node.
  17902. /// @internal
  17903. buffer,
  17904. // The base offset of the buffer. When stacks are split, the split
  17905. // instance shared the buffer history with its parent up to
  17906. // `bufferBase`, which is the absolute offset (including the
  17907. // offset of previous splits) into the buffer at which this stack
  17908. // starts writing.
  17909. /// @internal
  17910. bufferBase,
  17911. // A parent stack from which this was split off, if any. This is
  17912. // set up so that it always points to a stack that has some
  17913. // additional buffer content, never to a stack with an equal
  17914. // `bufferBase`.
  17915. /// @internal
  17916. parent) {
  17917. this.cx = cx;
  17918. this.stack = stack;
  17919. this.state = state;
  17920. this.reducePos = reducePos;
  17921. this.pos = pos;
  17922. this.score = score;
  17923. this.buffer = buffer;
  17924. this.bufferBase = bufferBase;
  17925. this.parent = parent;
  17926. }
  17927. /// @internal
  17928. toString() {
  17929. return `[${this.stack.filter((_, i) => i % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
  17930. }
  17931. // Start an empty stack
  17932. /// @internal
  17933. static start(cx, state, pos = 0) {
  17934. return new Stack(cx, [], state, pos, pos, 0, [], 0, null);
  17935. }
  17936. // Push a state onto the stack, tracking its start position as well
  17937. // as the buffer base at that point.
  17938. /// @internal
  17939. pushState(state, start) {
  17940. this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
  17941. this.state = state;
  17942. }
  17943. // Apply a reduce action
  17944. /// @internal
  17945. reduce(action) {
  17946. let depth = action >> 19 /* ReduceDepthShift */, type = action & 65535 /* ValueMask */;
  17947. let { parser } = this.cx;
  17948. let dPrec = parser.dynamicPrecedence(type);
  17949. if (dPrec)
  17950. this.score += dPrec;
  17951. if (depth == 0) {
  17952. // Zero-depth reductions are a special case—they add stuff to
  17953. // the stack without popping anything off.
  17954. if (type < parser.minRepeatTerm)
  17955. this.storeNode(type, this.reducePos, this.reducePos, 4, true);
  17956. this.pushState(parser.getGoto(this.state, type, true), this.reducePos);
  17957. return;
  17958. }
  17959. // Find the base index into `this.stack`, content after which will
  17960. // be dropped. Note that with `StayFlag` reductions we need to
  17961. // consume two extra frames (the dummy parent node for the skipped
  17962. // expression and the state that we'll be staying in, which should
  17963. // be moved to `this.state`).
  17964. let base = this.stack.length - ((depth - 1) * 3) - (action & 262144 /* StayFlag */ ? 6 : 0);
  17965. let start = this.stack[base - 2];
  17966. let bufferBase = this.stack[base - 1], count = this.bufferBase + this.buffer.length - bufferBase;
  17967. // Store normal terms or `R -> R R` repeat reductions
  17968. if (type < parser.minRepeatTerm || (action & 131072 /* RepeatFlag */)) {
  17969. let pos = parser.stateFlag(this.state, 1 /* Skipped */) ? this.pos : this.reducePos;
  17970. this.storeNode(type, start, pos, count + 4, true);
  17971. }
  17972. if (action & 262144 /* StayFlag */) {
  17973. this.state = this.stack[base];
  17974. }
  17975. else {
  17976. let baseStateID = this.stack[base - 3];
  17977. this.state = parser.getGoto(baseStateID, type, true);
  17978. }
  17979. while (this.stack.length > base)
  17980. this.stack.pop();
  17981. }
  17982. // Shift a value into the buffer
  17983. /// @internal
  17984. storeNode(term, start, end, size = 4, isReduce = false) {
  17985. if (term == 0 /* Err */) { // Try to omit/merge adjacent error nodes
  17986. let cur = this, top = this.buffer.length;
  17987. if (top == 0 && cur.parent) {
  17988. top = cur.bufferBase - cur.parent.bufferBase;
  17989. cur = cur.parent;
  17990. }
  17991. if (top > 0 && cur.buffer[top - 4] == 0 /* Err */ && cur.buffer[top - 1] > -1) {
  17992. if (start == end)
  17993. return;
  17994. if (cur.buffer[top - 2] >= start) {
  17995. cur.buffer[top - 2] = end;
  17996. return;
  17997. }
  17998. }
  17999. }
  18000. if (!isReduce || this.pos == end) { // Simple case, just append
  18001. this.buffer.push(term, start, end, size);
  18002. }
  18003. else { // There may be skipped nodes that have to be moved forward
  18004. let index = this.buffer.length;
  18005. if (index > 0 && this.buffer[index - 4] != 0 /* Err */)
  18006. while (index > 0 && this.buffer[index - 2] > end) {
  18007. // Move this record forward
  18008. this.buffer[index] = this.buffer[index - 4];
  18009. this.buffer[index + 1] = this.buffer[index - 3];
  18010. this.buffer[index + 2] = this.buffer[index - 2];
  18011. this.buffer[index + 3] = this.buffer[index - 1];
  18012. index -= 4;
  18013. if (size > 4)
  18014. size -= 4;
  18015. }
  18016. this.buffer[index] = term;
  18017. this.buffer[index + 1] = start;
  18018. this.buffer[index + 2] = end;
  18019. this.buffer[index + 3] = size;
  18020. }
  18021. }
  18022. // Apply a shift action
  18023. /// @internal
  18024. shift(action, next, nextEnd) {
  18025. if (action & 131072 /* GotoFlag */) {
  18026. this.pushState(action & 65535 /* ValueMask */, this.pos);
  18027. }
  18028. else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift
  18029. let start = this.pos, nextState = action, { parser } = this.cx;
  18030. if (nextEnd > this.pos || next <= parser.maxNode) {
  18031. this.pos = nextEnd;
  18032. if (!parser.stateFlag(nextState, 1 /* Skipped */))
  18033. this.reducePos = nextEnd;
  18034. }
  18035. this.pushState(nextState, start);
  18036. if (next <= parser.maxNode)
  18037. this.buffer.push(next, start, nextEnd, 4);
  18038. }
  18039. else { // Shift-and-stay, which means this is a skipped token
  18040. if (next <= this.cx.parser.maxNode)
  18041. this.buffer.push(next, this.pos, nextEnd, 4);
  18042. this.pos = nextEnd;
  18043. }
  18044. }
  18045. // Apply an action
  18046. /// @internal
  18047. apply(action, next, nextEnd) {
  18048. if (action & 65536 /* ReduceFlag */)
  18049. this.reduce(action);
  18050. else
  18051. this.shift(action, next, nextEnd);
  18052. }
  18053. // Add a prebuilt node into the buffer. This may be a reused node or
  18054. // the result of running a nested parser.
  18055. /// @internal
  18056. useNode(value, next) {
  18057. let index = this.cx.reused.length - 1;
  18058. if (index < 0 || this.cx.reused[index] != value) {
  18059. this.cx.reused.push(value);
  18060. index++;
  18061. }
  18062. let start = this.pos;
  18063. this.reducePos = this.pos = start + value.length;
  18064. this.pushState(next, start);
  18065. this.buffer.push(index, start, this.reducePos, -1 /* size < 0 means this is a reused value */);
  18066. }
  18067. // Split the stack. Due to the buffer sharing and the fact
  18068. // that `this.stack` tends to stay quite shallow, this isn't very
  18069. // expensive.
  18070. /// @internal
  18071. split() {
  18072. let parent = this;
  18073. let off = parent.buffer.length;
  18074. // Because the top of the buffer (after this.pos) may be mutated
  18075. // to reorder reductions and skipped tokens, and shared buffers
  18076. // should be immutable, this copies any outstanding skipped tokens
  18077. // to the new buffer, and puts the base pointer before them.
  18078. while (off > 0 && parent.buffer[off - 2] > parent.reducePos)
  18079. off -= 4;
  18080. let buffer = parent.buffer.slice(off), base = parent.bufferBase + off;
  18081. // Make sure parent points to an actual parent with content, if there is such a parent.
  18082. while (parent && base == parent.bufferBase)
  18083. parent = parent.parent;
  18084. return new Stack(this.cx, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base, parent);
  18085. }
  18086. // Try to recover from an error by 'deleting' (ignoring) one token.
  18087. /// @internal
  18088. recoverByDelete(next, nextEnd) {
  18089. let isNode = next <= this.cx.parser.maxNode;
  18090. if (isNode)
  18091. this.storeNode(next, this.pos, nextEnd);
  18092. this.storeNode(0 /* Err */, this.pos, nextEnd, isNode ? 8 : 4);
  18093. this.pos = this.reducePos = nextEnd;
  18094. this.score -= 200 /* Token */;
  18095. }
  18096. /// Check if the given term would be able to be shifted (optionally
  18097. /// after some reductions) on this stack. This can be useful for
  18098. /// external tokenizers that want to make sure they only provide a
  18099. /// given token when it applies.
  18100. canShift(term) {
  18101. for (let sim = new SimulatedStack(this);;) {
  18102. let action = this.cx.parser.stateSlot(sim.top, 4 /* DefaultReduce */) || this.cx.parser.hasAction(sim.top, term);
  18103. if ((action & 65536 /* ReduceFlag */) == 0)
  18104. return true;
  18105. if (action == 0)
  18106. return false;
  18107. sim.reduce(action);
  18108. }
  18109. }
  18110. /// Find the start position of the rule that is currently being parsed.
  18111. get ruleStart() {
  18112. for (let state = this.state, base = this.stack.length;;) {
  18113. let force = this.cx.parser.stateSlot(state, 5 /* ForcedReduce */);
  18114. if (!(force & 65536 /* ReduceFlag */))
  18115. return 0;
  18116. base -= 3 * (force >> 19 /* ReduceDepthShift */);
  18117. if ((force & 65535 /* ValueMask */) < this.cx.parser.minRepeatTerm)
  18118. return this.stack[base + 1];
  18119. state = this.stack[base];
  18120. }
  18121. }
  18122. /// Find the start position of an instance of any of the given term
  18123. /// types, or return `null` when none of them are found.
  18124. ///
  18125. /// **Note:** this is only reliable when there is at least some
  18126. /// state that unambiguously matches the given rule on the stack.
  18127. /// I.e. if you have a grammar like this, where the difference
  18128. /// between `a` and `b` is only apparent at the third token:
  18129. ///
  18130. /// a { b | c }
  18131. /// b { "x" "y" "x" }
  18132. /// c { "x" "y" "z" }
  18133. ///
  18134. /// Then a parse state after `"x"` will not reliably tell you that
  18135. /// `b` is on the stack. You _can_ pass `[b, c]` to reliably check
  18136. /// for either of those two rules (assuming that `a` isn't part of
  18137. /// some rule that includes other things starting with `"x"`).
  18138. ///
  18139. /// When `before` is given, this keeps scanning up the stack until
  18140. /// it finds a match that starts before that position.
  18141. startOf(types, before) {
  18142. let state = this.state, frame = this.stack.length, { parser } = this.cx;
  18143. for (;;) {
  18144. let force = parser.stateSlot(state, 5 /* ForcedReduce */);
  18145. let depth = force >> 19 /* ReduceDepthShift */, term = force & 65535 /* ValueMask */;
  18146. if (types.indexOf(term) > -1) {
  18147. let base = frame - (3 * (force >> 19 /* ReduceDepthShift */)), pos = this.stack[base + 1];
  18148. if (before == null || before > pos)
  18149. return pos;
  18150. }
  18151. if (frame == 0)
  18152. return null;
  18153. if (depth == 0) {
  18154. frame -= 3;
  18155. state = this.stack[frame];
  18156. }
  18157. else {
  18158. frame -= 3 * (depth - 1);
  18159. state = parser.getGoto(this.stack[frame - 3], term, true);
  18160. }
  18161. }
  18162. }
  18163. // Apply up to Recover.MaxNext recovery actions that conceptually
  18164. // inserts some missing token or rule.
  18165. /// @internal
  18166. recoverByInsert(next) {
  18167. if (this.stack.length >= 300 /* MaxInsertStackDepth */)
  18168. return [];
  18169. let nextStates = this.cx.parser.nextStates(this.state);
  18170. if (nextStates.length > 4 /* MaxNext */ || this.stack.length >= 120 /* DampenInsertStackDepth */) {
  18171. let best = nextStates.filter(s => s != this.state && this.cx.parser.hasAction(s, next));
  18172. if (this.stack.length < 120 /* DampenInsertStackDepth */)
  18173. for (let i = 0; best.length < 4 /* MaxNext */ && i < nextStates.length; i++)
  18174. if (best.indexOf(nextStates[i]) < 0)
  18175. best.push(nextStates[i]);
  18176. nextStates = best;
  18177. }
  18178. let result = [];
  18179. for (let i = 0; i < nextStates.length && result.length < 4 /* MaxNext */; i++) {
  18180. if (nextStates[i] == this.state)
  18181. continue;
  18182. let stack = this.split();
  18183. stack.storeNode(0 /* Err */, stack.pos, stack.pos, 4, true);
  18184. stack.pushState(nextStates[i], this.pos);
  18185. stack.score -= 200 /* Token */;
  18186. result.push(stack);
  18187. }
  18188. return result;
  18189. }
  18190. // Force a reduce, if possible. Return false if that can't
  18191. // be done.
  18192. /// @internal
  18193. forceReduce() {
  18194. let reduce = this.cx.parser.stateSlot(this.state, 5 /* ForcedReduce */);
  18195. if ((reduce & 65536 /* ReduceFlag */) == 0)
  18196. return false;
  18197. if (!this.cx.parser.validAction(this.state, reduce)) {
  18198. this.storeNode(0 /* Err */, this.reducePos, this.reducePos, 4, true);
  18199. this.score -= 100 /* Reduce */;
  18200. }
  18201. this.reduce(reduce);
  18202. return true;
  18203. }
  18204. /// @internal
  18205. forceAll() {
  18206. while (!this.cx.parser.stateFlag(this.state, 2 /* Accepting */) && this.forceReduce()) { }
  18207. return this;
  18208. }
  18209. /// Check whether this state has no further actions (assumed to be a direct descendant of the
  18210. /// top state, since any other states must be able to continue
  18211. /// somehow). @internal
  18212. get deadEnd() {
  18213. if (this.stack.length != 3)
  18214. return false;
  18215. let { parser } = this.cx;
  18216. return parser.data[parser.stateSlot(this.state, 1 /* Actions */)] == 65535 /* End */ &&
  18217. !parser.stateSlot(this.state, 4 /* DefaultReduce */);
  18218. }
  18219. /// Restart the stack (put it back in its start state). Only safe
  18220. /// when this.stack.length == 3 (state is directly below the top
  18221. /// state). @internal
  18222. restart() {
  18223. this.state = this.stack[0];
  18224. this.stack.length = 0;
  18225. }
  18226. /// @internal
  18227. sameState(other) {
  18228. if (this.state != other.state || this.stack.length != other.stack.length)
  18229. return false;
  18230. for (let i = 0; i < this.stack.length; i += 3)
  18231. if (this.stack[i] != other.stack[i])
  18232. return false;
  18233. return true;
  18234. }
  18235. /// Get the parser used by this stack.
  18236. get parser() { return this.cx.parser; }
  18237. /// Test whether a given dialect (by numeric ID, as exported from
  18238. /// the terms file) is enabled.
  18239. dialectEnabled(dialectID) { return this.cx.parser.dialect.flags[dialectID]; }
  18240. }
  18241. var Recover;
  18242. (function (Recover) {
  18243. Recover[Recover["Token"] = 200] = "Token";
  18244. Recover[Recover["Reduce"] = 100] = "Reduce";
  18245. Recover[Recover["MaxNext"] = 4] = "MaxNext";
  18246. Recover[Recover["MaxInsertStackDepth"] = 300] = "MaxInsertStackDepth";
  18247. Recover[Recover["DampenInsertStackDepth"] = 120] = "DampenInsertStackDepth";
  18248. })(Recover || (Recover = {}));
  18249. // Used to cheaply run some reductions to scan ahead without mutating
  18250. // an entire stack
  18251. class SimulatedStack {
  18252. constructor(stack) {
  18253. this.stack = stack;
  18254. this.top = stack.state;
  18255. this.rest = stack.stack;
  18256. this.offset = this.rest.length;
  18257. }
  18258. reduce(action) {
  18259. let term = action & 65535 /* ValueMask */, depth = action >> 19 /* ReduceDepthShift */;
  18260. if (depth == 0) {
  18261. if (this.rest == this.stack.stack)
  18262. this.rest = this.rest.slice();
  18263. this.rest.push(this.top, 0, 0);
  18264. this.offset += 3;
  18265. }
  18266. else {
  18267. this.offset -= (depth - 1) * 3;
  18268. }
  18269. let goto = this.stack.cx.parser.getGoto(this.rest[this.offset - 3], term, true);
  18270. this.top = goto;
  18271. }
  18272. }
  18273. // This is given to `Tree.build` to build a buffer, and encapsulates
  18274. // the parent-stack-walking necessary to read the nodes.
  18275. class StackBufferCursor {
  18276. constructor(stack, pos, index) {
  18277. this.stack = stack;
  18278. this.pos = pos;
  18279. this.index = index;
  18280. this.buffer = stack.buffer;
  18281. if (this.index == 0)
  18282. this.maybeNext();
  18283. }
  18284. static create(stack) {
  18285. return new StackBufferCursor(stack, stack.bufferBase + stack.buffer.length, stack.buffer.length);
  18286. }
  18287. maybeNext() {
  18288. let next = this.stack.parent;
  18289. if (next != null) {
  18290. this.index = this.stack.bufferBase - next.bufferBase;
  18291. this.stack = next;
  18292. this.buffer = next.buffer;
  18293. }
  18294. }
  18295. get id() { return this.buffer[this.index - 4]; }
  18296. get start() { return this.buffer[this.index - 3]; }
  18297. get end() { return this.buffer[this.index - 2]; }
  18298. get size() { return this.buffer[this.index - 1]; }
  18299. next() {
  18300. this.index -= 4;
  18301. this.pos -= 4;
  18302. if (this.index == 0)
  18303. this.maybeNext();
  18304. }
  18305. fork() {
  18306. return new StackBufferCursor(this.stack, this.pos, this.index);
  18307. }
  18308. }
  18309. /// Tokenizers write the tokens they read into instances of this class.
  18310. class Token {
  18311. constructor() {
  18312. /// The start of the token. This is set by the parser, and should not
  18313. /// be mutated by the tokenizer.
  18314. this.start = -1;
  18315. /// This starts at -1, and should be updated to a term id when a
  18316. /// matching token is found.
  18317. this.value = -1;
  18318. /// When setting `.value`, you should also set `.end` to the end
  18319. /// position of the token. (You'll usually want to use the `accept`
  18320. /// method.)
  18321. this.end = -1;
  18322. }
  18323. /// Accept a token, setting `value` and `end` to the given values.
  18324. accept(value, end) {
  18325. this.value = value;
  18326. this.end = end;
  18327. }
  18328. }
  18329. /// @internal
  18330. class TokenGroup {
  18331. constructor(data, id) {
  18332. this.data = data;
  18333. this.id = id;
  18334. }
  18335. token(input, token, stack) { readToken(this.data, input, token, stack, this.id); }
  18336. }
  18337. TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
  18338. /// Exports that are used for `@external tokens` in the grammar should
  18339. /// export an instance of this class.
  18340. class ExternalTokenizer {
  18341. /// Create a tokenizer. The first argument is the function that,
  18342. /// given an input stream and a token object,
  18343. /// [fills](#lezer.Token.accept) the token object if it recognizes a
  18344. /// token. `token.start` should be used as the start position to
  18345. /// scan from.
  18346. constructor(
  18347. /// @internal
  18348. token, options = {}) {
  18349. this.token = token;
  18350. this.contextual = !!options.contextual;
  18351. this.fallback = !!options.fallback;
  18352. this.extend = !!options.extend;
  18353. }
  18354. }
  18355. // Tokenizer data is stored a big uint16 array containing, for each
  18356. // state:
  18357. //
  18358. // - A group bitmask, indicating what token groups are reachable from
  18359. // this state, so that paths that can only lead to tokens not in
  18360. // any of the current groups can be cut off early.
  18361. //
  18362. // - The position of the end of the state's sequence of accepting
  18363. // tokens
  18364. //
  18365. // - The number of outgoing edges for the state
  18366. //
  18367. // - The accepting tokens, as (token id, group mask) pairs
  18368. //
  18369. // - The outgoing edges, as (start character, end character, state
  18370. // index) triples, with end character being exclusive
  18371. //
  18372. // This function interprets that data, running through a stream as
  18373. // long as new states with the a matching group mask can be reached,
  18374. // and updating `token` when it matches a token.
  18375. function readToken(data, input, token, stack, group) {
  18376. let state = 0, groupMask = 1 << group, dialect = stack.cx.parser.dialect;
  18377. scan: for (let pos = token.start;;) {
  18378. if ((groupMask & data[state]) == 0)
  18379. break;
  18380. let accEnd = data[state + 1];
  18381. // Check whether this state can lead to a token in the current group
  18382. // Accept tokens in this state, possibly overwriting
  18383. // lower-precedence / shorter tokens
  18384. for (let i = state + 3; i < accEnd; i += 2)
  18385. if ((data[i + 1] & groupMask) > 0) {
  18386. let term = data[i];
  18387. if (dialect.allows(term) &&
  18388. (token.value == -1 || token.value == term || stack.cx.parser.overrides(term, token.value))) {
  18389. token.accept(term, pos);
  18390. break;
  18391. }
  18392. }
  18393. let next = input.get(pos++);
  18394. // Do a binary search on the state's edges
  18395. for (let low = 0, high = data[state + 2]; low < high;) {
  18396. let mid = (low + high) >> 1;
  18397. let index = accEnd + mid + (mid << 1);
  18398. let from = data[index], to = data[index + 1];
  18399. if (next < from)
  18400. high = mid;
  18401. else if (next >= to)
  18402. low = mid + 1;
  18403. else {
  18404. state = data[index + 2];
  18405. continue scan;
  18406. }
  18407. }
  18408. break;
  18409. }
  18410. }
  18411. // See lezer-generator/src/encode.ts for comments about the encoding
  18412. // used here
  18413. function decodeArray(input, Type = Uint16Array) {
  18414. if (typeof input != "string")
  18415. return input;
  18416. let array = null;
  18417. for (let pos = 0, out = 0; pos < input.length;) {
  18418. let value = 0;
  18419. for (;;) {
  18420. let next = input.charCodeAt(pos++), stop = false;
  18421. if (next == 126 /* BigValCode */) {
  18422. value = 65535 /* BigVal */;
  18423. break;
  18424. }
  18425. if (next >= 92 /* Gap2 */)
  18426. next--;
  18427. if (next >= 34 /* Gap1 */)
  18428. next--;
  18429. let digit = next - 32 /* Start */;
  18430. if (digit >= 46 /* Base */) {
  18431. digit -= 46 /* Base */;
  18432. stop = true;
  18433. }
  18434. value += digit;
  18435. if (stop)
  18436. break;
  18437. value *= 46 /* Base */;
  18438. }
  18439. if (array)
  18440. array[out++] = value;
  18441. else
  18442. array = new Type(value);
  18443. }
  18444. return array;
  18445. }
  18446. // FIXME find some way to reduce recovery work done when the input
  18447. // doesn't match the grammar at all.
  18448. // Environment variable used to control console output
  18449. const verbose = typeof process != "undefined" && /\bparse\b/.test(process.env.LOG);
  18450. let stackIDs = null;
  18451. function cutAt(tree, pos, side) {
  18452. let cursor = tree.cursor(pos);
  18453. for (;;) {
  18454. if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos)))
  18455. for (;;) {
  18456. if ((side < 0 ? cursor.to <= pos : cursor.from >= pos) && !cursor.type.isError)
  18457. return side < 0 ? cursor.to - 1 : cursor.from + 1;
  18458. if (side < 0 ? cursor.prevSibling() : cursor.nextSibling())
  18459. break;
  18460. if (!cursor.parent())
  18461. return side < 0 ? 0 : tree.length;
  18462. }
  18463. }
  18464. }
  18465. class FragmentCursor$1 {
  18466. constructor(fragments) {
  18467. this.fragments = fragments;
  18468. this.i = 0;
  18469. this.fragment = null;
  18470. this.safeFrom = -1;
  18471. this.safeTo = -1;
  18472. this.trees = [];
  18473. this.start = [];
  18474. this.index = [];
  18475. this.nextFragment();
  18476. }
  18477. nextFragment() {
  18478. let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
  18479. if (fr) {
  18480. this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
  18481. this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
  18482. while (this.trees.length) {
  18483. this.trees.pop();
  18484. this.start.pop();
  18485. this.index.pop();
  18486. }
  18487. this.trees.push(fr.tree);
  18488. this.start.push(-fr.offset);
  18489. this.index.push(0);
  18490. this.nextStart = this.safeFrom;
  18491. }
  18492. else {
  18493. this.nextStart = 1e9;
  18494. }
  18495. }
  18496. // `pos` must be >= any previously given `pos` for this cursor
  18497. nodeAt(pos) {
  18498. if (pos < this.nextStart)
  18499. return null;
  18500. while (this.fragment && this.safeTo <= pos)
  18501. this.nextFragment();
  18502. if (!this.fragment)
  18503. return null;
  18504. for (;;) {
  18505. let last = this.trees.length - 1;
  18506. if (last < 0) { // End of tree
  18507. this.nextFragment();
  18508. return null;
  18509. }
  18510. let top = this.trees[last], index = this.index[last];
  18511. if (index == top.children.length) {
  18512. this.trees.pop();
  18513. this.start.pop();
  18514. this.index.pop();
  18515. continue;
  18516. }
  18517. let next = top.children[index];
  18518. let start = this.start[last] + top.positions[index];
  18519. if (start > pos) {
  18520. this.nextStart = start;
  18521. return null;
  18522. }
  18523. else if (start == pos && start + next.length <= this.safeTo) {
  18524. return start == pos && start >= this.safeFrom ? next : null;
  18525. }
  18526. if (next instanceof TreeBuffer) {
  18527. this.index[last]++;
  18528. this.nextStart = start + next.length;
  18529. }
  18530. else {
  18531. this.index[last]++;
  18532. if (start + next.length >= pos) { // Enter this node
  18533. this.trees.push(next);
  18534. this.start.push(start);
  18535. this.index.push(0);
  18536. }
  18537. }
  18538. }
  18539. }
  18540. }
  18541. class CachedToken extends Token {
  18542. constructor() {
  18543. super(...arguments);
  18544. this.extended = -1;
  18545. this.mask = 0;
  18546. }
  18547. clear(start) {
  18548. this.start = start;
  18549. this.value = this.extended = -1;
  18550. }
  18551. }
  18552. const dummyToken = new Token;
  18553. class TokenCache {
  18554. constructor(parser) {
  18555. this.tokens = [];
  18556. this.mainToken = dummyToken;
  18557. this.actions = [];
  18558. this.tokens = parser.tokenizers.map(_ => new CachedToken);
  18559. }
  18560. getActions(stack, input) {
  18561. let actionIndex = 0;
  18562. let main = null;
  18563. let { parser } = stack.cx, { tokenizers } = parser;
  18564. let mask = parser.stateSlot(stack.state, 3 /* TokenizerMask */);
  18565. for (let i = 0; i < tokenizers.length; i++) {
  18566. if (((1 << i) & mask) == 0)
  18567. continue;
  18568. let tokenizer = tokenizers[i], token = this.tokens[i];
  18569. if (main && !tokenizer.fallback)
  18570. continue;
  18571. if (tokenizer.contextual || token.start != stack.pos || token.mask != mask) {
  18572. this.updateCachedToken(token, tokenizer, stack, input);
  18573. token.mask = mask;
  18574. }
  18575. if (token.value != 0 /* Err */) {
  18576. let startIndex = actionIndex;
  18577. if (token.extended > -1)
  18578. actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
  18579. actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
  18580. if (!tokenizer.extend) {
  18581. main = token;
  18582. if (actionIndex > startIndex)
  18583. break;
  18584. }
  18585. }
  18586. }
  18587. while (this.actions.length > actionIndex)
  18588. this.actions.pop();
  18589. if (!main) {
  18590. main = dummyToken;
  18591. main.start = stack.pos;
  18592. if (stack.pos == input.length)
  18593. main.accept(stack.cx.parser.eofTerm, stack.pos);
  18594. else
  18595. main.accept(0 /* Err */, stack.pos + 1);
  18596. }
  18597. this.mainToken = main;
  18598. return this.actions;
  18599. }
  18600. updateCachedToken(token, tokenizer, stack, input) {
  18601. token.clear(stack.pos);
  18602. tokenizer.token(input, token, stack);
  18603. if (token.value > -1) {
  18604. let { parser } = stack.cx;
  18605. for (let i = 0; i < parser.specialized.length; i++)
  18606. if (parser.specialized[i] == token.value) {
  18607. let result = parser.specializers[i](input.read(token.start, token.end), stack);
  18608. if (result >= 0 && stack.cx.parser.dialect.allows(result >> 1)) {
  18609. if ((result & 1) == 0 /* Specialize */)
  18610. token.value = result >> 1;
  18611. else
  18612. token.extended = result >> 1;
  18613. break;
  18614. }
  18615. }
  18616. }
  18617. else if (stack.pos == input.length) {
  18618. token.accept(stack.cx.parser.eofTerm, stack.pos);
  18619. }
  18620. else {
  18621. token.accept(0 /* Err */, stack.pos + 1);
  18622. }
  18623. }
  18624. putAction(action, token, end, index) {
  18625. // Don't add duplicate actions
  18626. for (let i = 0; i < index; i += 3)
  18627. if (this.actions[i] == action)
  18628. return index;
  18629. this.actions[index++] = action;
  18630. this.actions[index++] = token;
  18631. this.actions[index++] = end;
  18632. return index;
  18633. }
  18634. addActions(stack, token, end, index) {
  18635. let { state } = stack, { parser } = stack.cx, { data } = parser;
  18636. for (let set = 0; set < 2; set++) {
  18637. for (let i = parser.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */);; i += 3) {
  18638. if (data[i] == 65535 /* End */) {
  18639. if (data[i + 1] == 1 /* Next */) {
  18640. i = pair(data, i + 2);
  18641. }
  18642. else {
  18643. if (index == 0 && data[i + 1] == 2 /* Other */)
  18644. index = this.putAction(pair(data, i + 1), token, end, index);
  18645. break;
  18646. }
  18647. }
  18648. if (data[i] == token)
  18649. index = this.putAction(pair(data, i + 1), token, end, index);
  18650. }
  18651. }
  18652. return index;
  18653. }
  18654. }
  18655. var Rec;
  18656. (function (Rec) {
  18657. Rec[Rec["Distance"] = 5] = "Distance";
  18658. Rec[Rec["MaxRemainingPerStep"] = 3] = "MaxRemainingPerStep";
  18659. Rec[Rec["MinBufferLengthPrune"] = 200] = "MinBufferLengthPrune";
  18660. Rec[Rec["ForceReduceLimit"] = 10] = "ForceReduceLimit";
  18661. })(Rec || (Rec = {}));
  18662. /// A parse context can be used for step-by-step parsing. After
  18663. /// creating it, you repeatedly call `.advance()` until it returns a
  18664. /// tree to indicate it has reached the end of the parse.
  18665. class Parse$1 {
  18666. constructor(parser, input, startPos, context) {
  18667. this.parser = parser;
  18668. this.input = input;
  18669. this.startPos = startPos;
  18670. this.context = context;
  18671. // The position to which the parse has advanced.
  18672. this.pos = 0;
  18673. this.recovering = 0;
  18674. this.nextStackID = 0x2654;
  18675. this.nested = null;
  18676. this.nestEnd = 0;
  18677. this.nestWrap = null;
  18678. this.reused = [];
  18679. this.tokens = new TokenCache(parser);
  18680. this.topTerm = parser.top[1];
  18681. this.stacks = [Stack.start(this, parser.top[0], this.startPos)];
  18682. let fragments = context === null || context === void 0 ? void 0 : context.fragments;
  18683. this.fragments = fragments && fragments.length ? new FragmentCursor$1(fragments) : null;
  18684. }
  18685. // Move the parser forward. This will process all parse stacks at
  18686. // `this.pos` and try to advance them to a further position. If no
  18687. // stack for such a position is found, it'll start error-recovery.
  18688. //
  18689. // When the parse is finished, this will return a syntax tree. When
  18690. // not, it returns `null`.
  18691. advance() {
  18692. if (this.nested) {
  18693. let result = this.nested.advance();
  18694. this.pos = this.nested.pos;
  18695. if (result) {
  18696. this.finishNested(this.stacks[0], result);
  18697. this.nested = null;
  18698. }
  18699. return null;
  18700. }
  18701. let stacks = this.stacks, pos = this.pos;
  18702. // This will hold stacks beyond `pos`.
  18703. let newStacks = this.stacks = [];
  18704. let stopped, stoppedTokens;
  18705. let maybeNest;
  18706. // Keep advancing any stacks at `pos` until they either move
  18707. // forward or can't be advanced. Gather stacks that can't be
  18708. // advanced further in `stopped`.
  18709. for (let i = 0; i < stacks.length; i++) {
  18710. let stack = stacks[i], nest;
  18711. for (;;) {
  18712. if (stack.pos > pos) {
  18713. newStacks.push(stack);
  18714. }
  18715. else if (nest = this.checkNest(stack)) {
  18716. if (!maybeNest || maybeNest.stack.score < stack.score)
  18717. maybeNest = nest;
  18718. }
  18719. else if (this.advanceStack(stack, newStacks, stacks)) {
  18720. continue;
  18721. }
  18722. else {
  18723. if (!stopped) {
  18724. stopped = [];
  18725. stoppedTokens = [];
  18726. }
  18727. stopped.push(stack);
  18728. let tok = this.tokens.mainToken;
  18729. stoppedTokens.push(tok.value, tok.end);
  18730. }
  18731. break;
  18732. }
  18733. }
  18734. if (maybeNest) {
  18735. this.startNested(maybeNest);
  18736. return null;
  18737. }
  18738. if (!newStacks.length) {
  18739. let finished = stopped && findFinished(stopped);
  18740. if (finished)
  18741. return this.stackToTree(finished);
  18742. if (this.parser.strict) {
  18743. if (verbose && stopped)
  18744. console.log("Stuck with token " + this.parser.getName(this.tokens.mainToken.value));
  18745. throw new SyntaxError("No parse at " + pos);
  18746. }
  18747. if (!this.recovering)
  18748. this.recovering = 5 /* Distance */;
  18749. }
  18750. if (this.recovering && stopped) {
  18751. let finished = this.runRecovery(stopped, stoppedTokens, newStacks);
  18752. if (finished)
  18753. return this.stackToTree(finished.forceAll());
  18754. }
  18755. if (this.recovering) {
  18756. let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3 /* MaxRemainingPerStep */;
  18757. if (newStacks.length > maxRemaining) {
  18758. newStacks.sort((a, b) => b.score - a.score);
  18759. while (newStacks.length > maxRemaining)
  18760. newStacks.pop();
  18761. }
  18762. if (newStacks.some(s => s.reducePos > pos))
  18763. this.recovering--;
  18764. }
  18765. else if (newStacks.length > 1) {
  18766. // Prune stacks that are in the same state, or that have been
  18767. // running without splitting for a while, to avoid getting stuck
  18768. // with multiple successful stacks running endlessly on.
  18769. outer: for (let i = 0; i < newStacks.length - 1; i++) {
  18770. let stack = newStacks[i];
  18771. for (let j = i + 1; j < newStacks.length; j++) {
  18772. let other = newStacks[j];
  18773. if (stack.sameState(other) ||
  18774. stack.buffer.length > 200 /* MinBufferLengthPrune */ && other.buffer.length > 200 /* MinBufferLengthPrune */) {
  18775. if (((stack.score - other.score) || (stack.buffer.length - other.buffer.length)) > 0) {
  18776. newStacks.splice(j--, 1);
  18777. }
  18778. else {
  18779. newStacks.splice(i--, 1);
  18780. continue outer;
  18781. }
  18782. }
  18783. }
  18784. }
  18785. }
  18786. this.pos = newStacks[0].pos;
  18787. for (let i = 1; i < newStacks.length; i++)
  18788. if (newStacks[i].pos < this.pos)
  18789. this.pos = newStacks[i].pos;
  18790. return null;
  18791. }
  18792. // Returns an updated version of the given stack, or null if the
  18793. // stack can't advance normally. When `split` and `stacks` are
  18794. // given, stacks split off by ambiguous operations will be pushed to
  18795. // `split`, or added to `stacks` if they move `pos` forward.
  18796. advanceStack(stack, stacks, split) {
  18797. let start = stack.pos, { input, parser } = this;
  18798. let base = verbose ? this.stackID(stack) + " -> " : "";
  18799. if (this.fragments) {
  18800. for (let cached = this.fragments.nodeAt(start); cached;) {
  18801. let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser.getGoto(stack.state, cached.type.id) : -1;
  18802. if (match > -1 && cached.length) {
  18803. stack.useNode(cached, match);
  18804. if (verbose)
  18805. console.log(base + this.stackID(stack) + ` (via reuse of ${parser.getName(cached.type.id)})`);
  18806. return true;
  18807. }
  18808. if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0)
  18809. break;
  18810. let inner = cached.children[0];
  18811. if (inner instanceof Tree)
  18812. cached = inner;
  18813. else
  18814. break;
  18815. }
  18816. }
  18817. let defaultReduce = parser.stateSlot(stack.state, 4 /* DefaultReduce */);
  18818. if (defaultReduce > 0) {
  18819. stack.reduce(defaultReduce);
  18820. if (verbose)
  18821. console.log(base + this.stackID(stack) + ` (via always-reduce ${parser.getName(defaultReduce & 65535 /* ValueMask */)})`);
  18822. return true;
  18823. }
  18824. let actions = this.tokens.getActions(stack, input);
  18825. for (let i = 0; i < actions.length;) {
  18826. let action = actions[i++], term = actions[i++], end = actions[i++];
  18827. let last = i == actions.length || !split;
  18828. let localStack = last ? stack : stack.split();
  18829. localStack.apply(action, term, end);
  18830. if (verbose)
  18831. console.log(base + this.stackID(localStack) + ` (via ${(action & 65536 /* ReduceFlag */) == 0 ? "shift"
  18832. : `reduce of ${parser.getName(action & 65535 /* ValueMask */)}`} for ${parser.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
  18833. if (last)
  18834. return true;
  18835. else if (localStack.pos > start)
  18836. stacks.push(localStack);
  18837. else
  18838. split.push(localStack);
  18839. }
  18840. return false;
  18841. }
  18842. // Advance a given stack forward as far as it will go. Returns the
  18843. // (possibly updated) stack if it got stuck, or null if it moved
  18844. // forward and was given to `pushStackDedup`.
  18845. advanceFully(stack, newStacks) {
  18846. let pos = stack.pos;
  18847. for (;;) {
  18848. let nest = this.checkNest(stack);
  18849. if (nest)
  18850. return nest;
  18851. if (!this.advanceStack(stack, null, null))
  18852. return false;
  18853. if (stack.pos > pos) {
  18854. pushStackDedup(stack, newStacks);
  18855. return true;
  18856. }
  18857. }
  18858. }
  18859. runRecovery(stacks, tokens, newStacks) {
  18860. let finished = null, restarted = false;
  18861. let maybeNest;
  18862. for (let i = 0; i < stacks.length; i++) {
  18863. let stack = stacks[i], token = tokens[i << 1], tokenEnd = tokens[(i << 1) + 1];
  18864. let base = verbose ? this.stackID(stack) + " -> " : "";
  18865. if (stack.deadEnd) {
  18866. if (restarted)
  18867. continue;
  18868. restarted = true;
  18869. stack.restart();
  18870. if (verbose)
  18871. console.log(base + this.stackID(stack) + " (restarted)");
  18872. let done = this.advanceFully(stack, newStacks);
  18873. if (done) {
  18874. if (done !== true)
  18875. maybeNest = done;
  18876. continue;
  18877. }
  18878. }
  18879. let force = stack.split(), forceBase = base;
  18880. for (let j = 0; force.forceReduce() && j < 10 /* ForceReduceLimit */; j++) {
  18881. if (verbose)
  18882. console.log(forceBase + this.stackID(force) + " (via force-reduce)");
  18883. let done = this.advanceFully(force, newStacks);
  18884. if (done) {
  18885. if (done !== true)
  18886. maybeNest = done;
  18887. break;
  18888. }
  18889. if (verbose)
  18890. forceBase = this.stackID(force) + " -> ";
  18891. }
  18892. for (let insert of stack.recoverByInsert(token)) {
  18893. if (verbose)
  18894. console.log(base + this.stackID(insert) + " (via recover-insert)");
  18895. this.advanceFully(insert, newStacks);
  18896. }
  18897. if (this.input.length > stack.pos) {
  18898. if (tokenEnd == stack.pos) {
  18899. tokenEnd++;
  18900. token = 0 /* Err */;
  18901. }
  18902. stack.recoverByDelete(token, tokenEnd);
  18903. if (verbose)
  18904. console.log(base + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
  18905. pushStackDedup(stack, newStacks);
  18906. }
  18907. else if (!finished || finished.score < stack.score) {
  18908. finished = stack;
  18909. }
  18910. }
  18911. if (finished)
  18912. return finished;
  18913. if (maybeNest)
  18914. for (let s of this.stacks)
  18915. if (s.score > maybeNest.stack.score) {
  18916. maybeNest = undefined;
  18917. break;
  18918. }
  18919. if (maybeNest)
  18920. this.startNested(maybeNest);
  18921. return null;
  18922. }
  18923. forceFinish() {
  18924. let stack = this.stacks[0].split();
  18925. if (this.nested)
  18926. this.finishNested(stack, this.nested.forceFinish());
  18927. return this.stackToTree(stack.forceAll());
  18928. }
  18929. // Convert the stack's buffer to a syntax tree.
  18930. stackToTree(stack, pos = stack.pos) {
  18931. return Tree.build({ buffer: StackBufferCursor.create(stack),
  18932. nodeSet: this.parser.nodeSet,
  18933. topID: this.topTerm,
  18934. maxBufferLength: this.parser.bufferLength,
  18935. reused: this.reused,
  18936. start: this.startPos,
  18937. length: pos - this.startPos,
  18938. minRepeatType: this.parser.minRepeatTerm });
  18939. }
  18940. checkNest(stack) {
  18941. let info = this.parser.findNested(stack.state);
  18942. if (!info)
  18943. return null;
  18944. let spec = info.value;
  18945. if (typeof spec == "function")
  18946. spec = spec(this.input, stack);
  18947. return spec ? { stack, info, spec } : null;
  18948. }
  18949. startNested(nest) {
  18950. let { stack, info, spec } = nest;
  18951. this.stacks = [stack];
  18952. this.nestEnd = this.scanForNestEnd(stack, info.end, spec.filterEnd);
  18953. this.nestWrap = typeof spec.wrapType == "number" ? this.parser.nodeSet.types[spec.wrapType] : spec.wrapType || null;
  18954. if (spec.startParse) {
  18955. this.nested = spec.startParse(this.input.clip(this.nestEnd), stack.pos, this.context);
  18956. }
  18957. else {
  18958. this.finishNested(stack);
  18959. }
  18960. }
  18961. scanForNestEnd(stack, endToken, filter) {
  18962. for (let pos = stack.pos; pos < this.input.length; pos++) {
  18963. dummyToken.start = pos;
  18964. dummyToken.value = -1;
  18965. endToken.token(this.input, dummyToken, stack);
  18966. if (dummyToken.value > -1 && (!filter || filter(this.input.read(pos, dummyToken.end))))
  18967. return pos;
  18968. }
  18969. return this.input.length;
  18970. }
  18971. finishNested(stack, tree) {
  18972. if (this.nestWrap)
  18973. tree = new Tree(this.nestWrap, tree ? [tree] : [], tree ? [0] : [], this.nestEnd - stack.pos);
  18974. else if (!tree)
  18975. tree = new Tree(NodeType.none, [], [], this.nestEnd - stack.pos);
  18976. let info = this.parser.findNested(stack.state);
  18977. stack.useNode(tree, this.parser.getGoto(stack.state, info.placeholder, true));
  18978. if (verbose)
  18979. console.log(this.stackID(stack) + ` (via unnest)`);
  18980. }
  18981. stackID(stack) {
  18982. let id = (stackIDs || (stackIDs = new WeakMap)).get(stack);
  18983. if (!id)
  18984. stackIDs.set(stack, id = String.fromCodePoint(this.nextStackID++));
  18985. return id + stack;
  18986. }
  18987. }
  18988. function pushStackDedup(stack, newStacks) {
  18989. for (let i = 0; i < newStacks.length; i++) {
  18990. let other = newStacks[i];
  18991. if (other.pos == stack.pos && other.sameState(stack)) {
  18992. if (newStacks[i].score < stack.score)
  18993. newStacks[i] = stack;
  18994. return;
  18995. }
  18996. }
  18997. newStacks.push(stack);
  18998. }
  18999. class Dialect {
  19000. constructor(source, flags, disabled) {
  19001. this.source = source;
  19002. this.flags = flags;
  19003. this.disabled = disabled;
  19004. }
  19005. allows(term) { return !this.disabled || this.disabled[term] == 0; }
  19006. }
  19007. /// A parser holds the parse tables for a given grammar, as generated
  19008. /// by `lezer-generator`.
  19009. class Parser {
  19010. /// @internal
  19011. constructor(spec) {
  19012. /// @internal
  19013. this.bufferLength = DefaultBufferLength;
  19014. /// @internal
  19015. this.strict = false;
  19016. this.nextStateCache = [];
  19017. this.cachedDialect = null;
  19018. if (spec.version != 13 /* Version */)
  19019. throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (${13 /* Version */})`);
  19020. let tokenArray = decodeArray(spec.tokenData);
  19021. let nodeNames = spec.nodeNames.split(" ");
  19022. this.minRepeatTerm = nodeNames.length;
  19023. for (let i = 0; i < spec.repeatNodeCount; i++)
  19024. nodeNames.push("");
  19025. let nodeProps = [];
  19026. for (let i = 0; i < nodeNames.length; i++)
  19027. nodeProps.push([]);
  19028. function setProp(nodeID, prop, value) {
  19029. nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
  19030. }
  19031. if (spec.nodeProps)
  19032. for (let propSpec of spec.nodeProps) {
  19033. let prop = propSpec[0];
  19034. for (let i = 1; i < propSpec.length;) {
  19035. let next = propSpec[i++];
  19036. if (next >= 0) {
  19037. setProp(next, prop, propSpec[i++]);
  19038. }
  19039. else {
  19040. let value = propSpec[i + -next];
  19041. for (let j = -next; j > 0; j--)
  19042. setProp(propSpec[i++], prop, value);
  19043. i++;
  19044. }
  19045. }
  19046. }
  19047. this.specialized = new Uint16Array(spec.specialized ? spec.specialized.length : 0);
  19048. this.specializers = [];
  19049. if (spec.specialized)
  19050. for (let i = 0; i < spec.specialized.length; i++) {
  19051. this.specialized[i] = spec.specialized[i].term;
  19052. this.specializers[i] = spec.specialized[i].get;
  19053. }
  19054. this.states = decodeArray(spec.states, Uint32Array);
  19055. this.data = decodeArray(spec.stateData);
  19056. this.goto = decodeArray(spec.goto);
  19057. let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
  19058. this.nodeSet = new NodeSet(nodeNames.map((name, i) => NodeType.define({
  19059. name: i >= this.minRepeatTerm ? undefined : name,
  19060. id: i,
  19061. props: nodeProps[i],
  19062. top: topTerms.indexOf(i) > -1,
  19063. error: i == 0,
  19064. skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i) > -1
  19065. })));
  19066. this.maxTerm = spec.maxTerm;
  19067. this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
  19068. this.topRules = spec.topRules;
  19069. this.nested = (spec.nested || []).map(([name, value, endToken, placeholder]) => {
  19070. return { name, value, end: new TokenGroup(decodeArray(endToken), 0), placeholder };
  19071. });
  19072. this.dialects = spec.dialects || {};
  19073. this.dynamicPrecedences = spec.dynamicPrecedences || null;
  19074. this.tokenPrecTable = spec.tokenPrec;
  19075. this.termNames = spec.termNames || null;
  19076. this.maxNode = this.nodeSet.types.length - 1;
  19077. for (let i = 0, l = this.states.length / 6 /* Size */; i < l; i++)
  19078. this.nextStateCache[i] = null;
  19079. this.dialect = this.parseDialect();
  19080. this.top = this.topRules[Object.keys(this.topRules)[0]];
  19081. }
  19082. /// Parse a given string or stream.
  19083. parse(input, startPos = 0, context = {}) {
  19084. if (typeof input == "string")
  19085. input = stringInput(input);
  19086. let cx = new Parse$1(this, input, startPos, context);
  19087. for (;;) {
  19088. let done = cx.advance();
  19089. if (done)
  19090. return done;
  19091. }
  19092. }
  19093. /// Start an incremental parse.
  19094. startParse(input, startPos = 0, context = {}) {
  19095. if (typeof input == "string")
  19096. input = stringInput(input);
  19097. return new Parse$1(this, input, startPos, context);
  19098. }
  19099. /// Get a goto table entry @internal
  19100. getGoto(state, term, loose = false) {
  19101. let table = this.goto;
  19102. if (term >= table[0])
  19103. return -1;
  19104. for (let pos = table[term + 1];;) {
  19105. let groupTag = table[pos++], last = groupTag & 1;
  19106. let target = table[pos++];
  19107. if (last && loose)
  19108. return target;
  19109. for (let end = pos + (groupTag >> 1); pos < end; pos++)
  19110. if (table[pos] == state)
  19111. return target;
  19112. if (last)
  19113. return -1;
  19114. }
  19115. }
  19116. /// Check if this state has an action for a given terminal @internal
  19117. hasAction(state, terminal) {
  19118. let data = this.data;
  19119. for (let set = 0; set < 2; set++) {
  19120. for (let i = this.stateSlot(state, set ? 2 /* Skip */ : 1 /* Actions */), next;; i += 3) {
  19121. if ((next = data[i]) == 65535 /* End */) {
  19122. if (data[i + 1] == 1 /* Next */)
  19123. next = data[i = pair(data, i + 2)];
  19124. else if (data[i + 1] == 2 /* Other */)
  19125. return pair(data, i + 2);
  19126. else
  19127. break;
  19128. }
  19129. if (next == terminal || next == 0 /* Err */)
  19130. return pair(data, i + 1);
  19131. }
  19132. }
  19133. return 0;
  19134. }
  19135. /// @internal
  19136. stateSlot(state, slot) {
  19137. return this.states[(state * 6 /* Size */) + slot];
  19138. }
  19139. /// @internal
  19140. stateFlag(state, flag) {
  19141. return (this.stateSlot(state, 0 /* Flags */) & flag) > 0;
  19142. }
  19143. /// @internal
  19144. findNested(state) {
  19145. let flags = this.stateSlot(state, 0 /* Flags */);
  19146. return flags & 4 /* StartNest */ ? this.nested[flags >> 10 /* NestShift */] : null;
  19147. }
  19148. /// @internal
  19149. validAction(state, action) {
  19150. if (action == this.stateSlot(state, 4 /* DefaultReduce */))
  19151. return true;
  19152. for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) {
  19153. if (this.data[i] == 65535 /* End */) {
  19154. if (this.data[i + 1] == 1 /* Next */)
  19155. i = pair(this.data, i + 2);
  19156. else
  19157. return false;
  19158. }
  19159. if (action == pair(this.data, i + 1))
  19160. return true;
  19161. }
  19162. }
  19163. /// Get the states that can follow this one through shift actions or
  19164. /// goto jumps. @internal
  19165. nextStates(state) {
  19166. let cached = this.nextStateCache[state];
  19167. if (cached)
  19168. return cached;
  19169. let result = [];
  19170. for (let i = this.stateSlot(state, 1 /* Actions */);; i += 3) {
  19171. if (this.data[i] == 65535 /* End */) {
  19172. if (this.data[i + 1] == 1 /* Next */)
  19173. i = pair(this.data, i + 2);
  19174. else
  19175. break;
  19176. }
  19177. if ((this.data[i + 2] & (65536 /* ReduceFlag */ >> 16)) == 0 && result.indexOf(this.data[i + 1]) < 0)
  19178. result.push(this.data[i + 1]);
  19179. }
  19180. let table = this.goto, max = table[0];
  19181. for (let term = 0; term < max; term++) {
  19182. for (let pos = table[term + 1];;) {
  19183. let groupTag = table[pos++], target = table[pos++];
  19184. for (let end = pos + (groupTag >> 1); pos < end; pos++)
  19185. if (table[pos] == state && result.indexOf(target) < 0)
  19186. result.push(target);
  19187. if (groupTag & 1)
  19188. break;
  19189. }
  19190. }
  19191. return this.nextStateCache[state] = result;
  19192. }
  19193. /// @internal
  19194. overrides(token, prev) {
  19195. let iPrev = findOffset(this.data, this.tokenPrecTable, prev);
  19196. return iPrev < 0 || findOffset(this.data, this.tokenPrecTable, token) < iPrev;
  19197. }
  19198. /// Configure the parser. Returns a new parser instance that has the
  19199. /// given settings modified. Settings not provided in `config` are
  19200. /// kept from the original parser.
  19201. configure(config) {
  19202. // Hideous reflection-based kludge to make it easy to create a
  19203. // slightly modified copy of a parser.
  19204. let copy = Object.assign(Object.create(Parser.prototype), this);
  19205. if (config.props)
  19206. copy.nodeSet = this.nodeSet.extend(...config.props);
  19207. if (config.top) {
  19208. let info = this.topRules[config.top];
  19209. if (!info)
  19210. throw new RangeError(`Invalid top rule name ${config.top}`);
  19211. copy.top = info;
  19212. }
  19213. if (config.tokenizers)
  19214. copy.tokenizers = this.tokenizers.map(t => {
  19215. let found = config.tokenizers.find(r => r.from == t);
  19216. return found ? found.to : t;
  19217. });
  19218. if (config.dialect)
  19219. copy.dialect = this.parseDialect(config.dialect);
  19220. if (config.nested)
  19221. copy.nested = this.nested.map(obj => {
  19222. if (!Object.prototype.hasOwnProperty.call(config.nested, obj.name))
  19223. return obj;
  19224. return { name: obj.name, value: config.nested[obj.name], end: obj.end, placeholder: obj.placeholder };
  19225. });
  19226. if (config.strict != null)
  19227. copy.strict = config.strict;
  19228. if (config.bufferLength != null)
  19229. copy.bufferLength = config.bufferLength;
  19230. return copy;
  19231. }
  19232. /// Returns the name associated with a given term. This will only
  19233. /// work for all terms when the parser was generated with the
  19234. /// `--names` option. By default, only the names of tagged terms are
  19235. /// stored.
  19236. getName(term) {
  19237. return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
  19238. }
  19239. /// The eof term id is always allocated directly after the node
  19240. /// types. @internal
  19241. get eofTerm() { return this.maxNode + 1; }
  19242. /// Tells you whether this grammar has any nested grammars.
  19243. get hasNested() { return this.nested.length > 0; }
  19244. /// @internal
  19245. dynamicPrecedence(term) {
  19246. let prec = this.dynamicPrecedences;
  19247. return prec == null ? 0 : prec[term] || 0;
  19248. }
  19249. /// @internal
  19250. parseDialect(dialect) {
  19251. if (this.cachedDialect && this.cachedDialect.source == dialect)
  19252. return this.cachedDialect;
  19253. let values = Object.keys(this.dialects), flags = values.map(() => false);
  19254. if (dialect)
  19255. for (let part of dialect.split(" ")) {
  19256. let id = values.indexOf(part);
  19257. if (id >= 0)
  19258. flags[id] = true;
  19259. }
  19260. let disabled = null;
  19261. for (let i = 0; i < values.length; i++)
  19262. if (!flags[i]) {
  19263. for (let j = this.dialects[values[i]], id; (id = this.data[j++]) != 65535 /* End */;)
  19264. (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id] = 1;
  19265. }
  19266. return this.cachedDialect = new Dialect(dialect, flags, disabled);
  19267. }
  19268. /// (used by the output of the parser generator) @internal
  19269. static deserialize(spec) {
  19270. return new Parser(spec);
  19271. }
  19272. }
  19273. function pair(data, off) { return data[off] | (data[off + 1] << 16); }
  19274. function findOffset(data, start, term) {
  19275. for (let i = start, next; (next = data[i]) != 65535 /* End */; i++)
  19276. if (next == term)
  19277. return i - start;
  19278. return -1;
  19279. }
  19280. function findFinished(stacks) {
  19281. let best = null;
  19282. for (let stack of stacks) {
  19283. if (stack.pos == stack.cx.input.length &&
  19284. stack.cx.parser.stateFlag(stack.state, 2 /* Accepting */) &&
  19285. (!best || best.score < stack.score))
  19286. best = stack;
  19287. }
  19288. return best;
  19289. }
  19290. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19291. const
  19292. StartTag = 1,
  19293. StartCloseTag = 2,
  19294. MismatchedStartCloseTag = 3,
  19295. missingCloseTag = 33,
  19296. IncompleteCloseTag = 4,
  19297. SelfCloseEndTag = 5,
  19298. Element$1 = 10,
  19299. OpenTag = 11,
  19300. SelfClosingTag = 20,
  19301. RawText = 25,
  19302. Dialect_noMatch = 0;
  19303. /* Hand-written tokenizers for HTML. */
  19304. const selfClosers = {
  19305. area: true, base: true, br: true, col: true, command: true,
  19306. embed: true, frame: true, hr: true, img: true, input: true,
  19307. keygen: true, link: true, meta: true, param: true, source: true,
  19308. track: true, wbr: true, menuitem: true
  19309. };
  19310. const implicitlyClosed = {
  19311. dd: true, li: true, optgroup: true, option: true, p: true,
  19312. rp: true, rt: true, tbody: true, td: true, tfoot: true,
  19313. th: true, tr: true
  19314. };
  19315. const closeOnOpen = {
  19316. dd: {dd: true, dt: true},
  19317. dt: {dd: true, dt: true},
  19318. li: {li: true},
  19319. option: {option: true, optgroup: true},
  19320. optgroup: {optgroup: true},
  19321. p: {
  19322. address: true, article: true, aside: true, blockquote: true, dir: true,
  19323. div: true, dl: true, fieldset: true, footer: true, form: true,
  19324. h1: true, h2: true, h3: true, h4: true, h5: true, h6: true,
  19325. header: true, hgroup: true, hr: true, menu: true, nav: true, ol: true,
  19326. p: true, pre: true, section: true, table: true, ul: true
  19327. },
  19328. rp: {rp: true, rt: true},
  19329. rt: {rp: true, rt: true},
  19330. tbody: {tbody: true, tfoot: true},
  19331. td: {td: true, th: true},
  19332. tfoot: {tbody: true},
  19333. th: {td: true, th: true},
  19334. thead: {tbody: true, tfoot: true},
  19335. tr: {tr: true}
  19336. };
  19337. function nameChar(ch) {
  19338. return ch == 45 || ch == 46 || ch == 58 || ch >= 65 && ch <= 90 || ch == 95 || ch >= 97 && ch <= 122 || ch >= 161
  19339. }
  19340. function isSpace(ch) {
  19341. return ch == 9 || ch == 10 || ch == 13 || ch == 32
  19342. }
  19343. const lessThan = 60, greaterThan = 62, slash = 47, question = 63, bang = 33;
  19344. const tagStartExpr = /^<\s*([\.\-\:\w\xa1-\uffff]+)/;
  19345. let elementQuery = [Element$1], openAt = 0;
  19346. function parentElement(input, stack, pos, len) {
  19347. openAt = stack.startOf(elementQuery, pos);
  19348. if (openAt == null) return null
  19349. let match = tagStartExpr.exec(input.read(openAt, openAt + len + 10));
  19350. return match ? match[1].toLowerCase() : ""
  19351. }
  19352. const tagStart = new ExternalTokenizer((input, token, stack) => {
  19353. let pos = token.start, first = input.get(pos);
  19354. // End of file, just close anything
  19355. if (first < 0) {
  19356. let contextStart = stack.startOf(elementQuery);
  19357. let match = contextStart == null ? null : tagStartExpr.exec(input.read(contextStart, contextStart + 30));
  19358. if (match && implicitlyClosed[match[1].toLowerCase()]) token.accept(missingCloseTag, token.start);
  19359. }
  19360. if (first != lessThan) return
  19361. pos++;
  19362. let close = false, tokEnd = pos;
  19363. for (let next; next = input.get(pos);) {
  19364. if (next == slash && !close) { close = true; pos++; tokEnd = pos; }
  19365. else if (next == question || next == bang) return
  19366. else if (isSpace(next)) pos++;
  19367. else break
  19368. }
  19369. let nameStart = pos;
  19370. while (nameChar(input.get(pos))) pos++;
  19371. if (pos == nameStart) return token.accept(close ? IncompleteCloseTag : StartTag, tokEnd)
  19372. let name = input.read(nameStart, pos).toLowerCase();
  19373. let parent = parentElement(input, stack, stack.pos, name.length);
  19374. if (close) {
  19375. if (name == parent) return token.accept(StartCloseTag, tokEnd)
  19376. if (implicitlyClosed[parent]) return token.accept(missingCloseTag, token.start)
  19377. if (stack.dialectEnabled(Dialect_noMatch)) return token.accept(StartCloseTag, tokEnd)
  19378. while (parent != null) {
  19379. parent = parentElement(input, stack, openAt - 1, name.length);
  19380. if (parent == name) return
  19381. }
  19382. token.accept(MismatchedStartCloseTag, tokEnd);
  19383. } else {
  19384. if (parent && closeOnOpen[parent] && closeOnOpen[parent][name])
  19385. return token.accept(missingCloseTag, token.start)
  19386. token.accept(StartTag, tokEnd);
  19387. }
  19388. }, {contextual: true});
  19389. const tagQuery = [OpenTag, SelfClosingTag];
  19390. const selfClosed = new ExternalTokenizer((input, token, stack) => {
  19391. let next = input.get(token.start), end = token.start + 1;
  19392. if (next == slash) {
  19393. if (input.get(end) != greaterThan) return
  19394. end++;
  19395. } else if (next != greaterThan) {
  19396. return
  19397. }
  19398. let from = stack.startOf(tagQuery);
  19399. let match = from == null ? null : tagStartExpr.exec(input.read(from, token.start));
  19400. if (match && selfClosers[match[1].toLowerCase()]) token.accept(SelfCloseEndTag, end);
  19401. }, {contextual: true});
  19402. const openTag = /^<\/?\s*([\.\-\:\w\xa1-\uffff]+)/;
  19403. function tagName(tag) {
  19404. let m = openTag.exec(tag);
  19405. return m ? m[1].toLowerCase() : null
  19406. }
  19407. function attributes(tag) {
  19408. let open = openTag.exec(tag), attrs = {};
  19409. if (open) {
  19410. let attr = /\s*([\.\-\:\w\xa1-\uffff]+)\s*(?:=("[^"]*"|'[^']*'|[^\s=<>"'/]+))?/g, m;
  19411. attr.lastIndex = open.index + open[0].length;
  19412. while (m = attr.exec(tag)) attrs[m[1]] = m[2] || m[1];
  19413. }
  19414. return attrs
  19415. }
  19416. function skip(name) { return token => tagName(token) == name }
  19417. // tags: {
  19418. // tag: string,
  19419. // attrs?: ({[attr: string]: string}) => boolean,
  19420. // parser: {startParse: (input: Input, startPos?: number, context?: ParseContext) => IncrementalParse}
  19421. // }[]
  19422. function resolveContent(tags) {
  19423. let tagMap = null;
  19424. for (let tag of tags) {
  19425. if (!tagMap) tagMap = Object.create(null)
  19426. ;(tagMap[tag.tag] || (tagMap[tag.tag] = [])).push({
  19427. attrs: tag.attrs,
  19428. value: {
  19429. filterEnd: skip(tag.tag),
  19430. startParse: tag.parser.startParse.bind(tag.parser)
  19431. }
  19432. });
  19433. }
  19434. return function(input, stack) {
  19435. let openTag = input.read(stack.ruleStart, stack.pos);
  19436. let name = tagName(openTag), matches, attrs;
  19437. if (!name) return null
  19438. if (tagMap && (matches = tagMap[name])) {
  19439. for (let match of matches) {
  19440. if (!match.attrs || match.attrs(attrs || (attrs = attributes(openTag)))) return match.value
  19441. }
  19442. }
  19443. if (name == "script" || name == "textarea" || name == "style") return {
  19444. filterEnd: skip(name),
  19445. wrapType: RawText
  19446. }
  19447. return null
  19448. }
  19449. }
  19450. const elementContent = resolveContent([]);
  19451. function configureNesting(tags) {
  19452. return {elementContent: resolveContent(tags)}
  19453. }
  19454. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19455. const parser$1 = Parser.deserialize({
  19456. version: 13,
  19457. states: "*hOQOTOOOoOWO'#CgS!cOTO'#CfOOOP'#Cf'#CfO!mOWO'#CsOOOP'#DO'#DOOOOP'#Cv'#CvQQOTOOOOOQ'#Cw'#CwO!uOWO,59RO!}ObO,59ROOOP'#C{'#C{O#]OTO'#DUO#gOPO,59QO#oOWO,59_O#wOWO,59_OOOP-E6t-E6tOOOQ-E6u-E6uO$PObO1G.mO$PObO1G.mO$_ObO'#CiOOOQ'#Cx'#CxO$pObO1G.mOOOP1G.m1G.mOOOP1G.v1G.vOOOP-E6y-E6yO${OWO'#CoOOOP1G.l1G.lO%TOWO1G.yO%TOWO1G.yOOOP1G.y1G.yO%]ObO7+$XO%kObO7+$XOOOP7+$X7+$XOOOP7+$b7+$bO%vObO,59TO&XOpO,59TOOOQ-E6v-E6vO&gOWO,59ZO&oOWO,59ZO&wOWO7+$eOOOP7+$e7+$eO'PObO<<GsOOOP<<Gs<<GsOOOP<<G|<<G|O'[OpO1G.oO'[OpO1G.oO'jO!bO'#ClO'xO#tO'#ClO(WObO1G.oO(fOWO1G.uO(fOWO1G.uOOOP1G.u1G.uOOOP<<HP<<HPOOOPAN=_AN=_OOOPAN=hAN=hO(nOpO7+$ZO(|ObO7+$ZOOOO'#Cy'#CyO)[O!bO,59WOOOQ,59W,59WOOOO'#Cz'#CzO)jO#tO,59WO(|ObO7+$ZO)xOWO7+$aOOOP7+$a7+$aO*QObO<<GuO*QObO<<GuOOOO-E6w-E6wOOOQ1G.r1G.rOOOO-E6x-E6xOOOP<<G{<<G{O*`ObOAN=a",
  19458. stateData: "*s~OPPORSOSTOVTOWTOXTOeTOfTOhUO~O[YOsWO~OPPORSOSTOVTOWTOXTOeTOfTO~OQxPqxP~PwO[_OsWO~O[bOsWO~OThO^dObgOsWO~OQxXqxX~PwOQjOqkO~O[lOsWO~ObnOsWO~OTrO^dObqOsWO~O_tOsWOT]X^]Xb]X~OTrO^dObqO~O[wOsWO~ObyOsWO~OT|O^dOb{OsWO~OT|O^dOb{O~O_}OsWOT]a^]ab]a~Oa!ROsWOt!POv!QO~O[!SOsWO~Ob!UOsWO~Ob!VOsWO~OT!XO^dOb!WO~Oa!ZOsWOt!POv!QO~OW![OX![Ot!^Ou![O~OW!_OX!_Ov!^Ow!_O~OsWOT]i^]ib]i~Ob!cOsWO~Oa!dOsWOt!POv!QO~OsWOT]q^]qb]q~OW![OX![Ot!gOu![O~OW!_OX!_Ov!gOw!_O~Ob!iOsWO~OsWOT]y^]yb]y~OsWOT]!R^]!Rb]!R~Oefhf~",
  19459. goto: "%YyPPPPPPPPPPz!QP!WPP!aPP!k!nPPzPP!t!z$[$k$q$wPP$}PPPPP%VXTOQV[XQOQV[_eYbcfopzQ!RtS!Z}!OR!d!YRk]XROQV[QVOR`VQXPQ^SnaX^cmosvx!O!T!Y!a!b!e!jQcYQm_QobQsdQvjQxlQ!OtQ!TwQ!Y}Q!a!RQ!b!SQ!e!ZR!j!dQfYSpbcUufpzRzoQ!]!PR!f!]Q!`!QR!h!`Q[QRi[SUOVTZQ[R]Q",
  19460. nodeNames: "⚠ StartTag StartCloseTag StartCloseTag IncompleteCloseTag SelfCloseEndTag Document Text EntityReference CharacterReference Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue EndTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag DoctypeDecl RawText",
  19461. maxTerm: 40,
  19462. nodeProps: [
  19463. [NodeProp.clos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^!mpq!m![!]$O!c!}$O#R#S$O#T#o$O%W%o$O%p&a$O&b1p$O4U4d$O4e$IS$O$I`$Ib$O$Kh%#t$O&/x&Et$O&FV;'S$O;'S;:j&e?&r?Ah$O?BY?Mn$O~!pdXY!mYZ!m]^!mpq!m![!]$O!c!}$O#R#S$O#T#o$O%W%o$O%p&a$O&b1p$O4U4d$O4e$IS$O$I`$Ib$O$Kh%#t$O&/x&Et$O&FV;'S$O;'S;:j&e?&r?Ah$O?BY?Mn$O~$RkXY%vYZ%v]^%vpq%v}!O$O!O!P$O!Q![$O![!]$O!`!a&Y!c!}$O#R#S$O#T#o$O$}%O$O%W%o$O%p&a$O&b1p$O1p4U$O4U4d$O4e$IS$O$I`$Ib$O$Je$Jg$O$Kh%#t$O&/x&Et$O&FV;'S$O;'S;:j&_?&r?Ah$O?BY?Mn$O~%yTXY%vYZ%v]^%vpq%v!`!a&Y~&_Op~~&bP;=`<%l$O~&hP;=`<%l$O", 40]],
  19472. dialects: {noMatch: 0},
  19473. tokenPrec: 444
  19474. });
  19475. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19476. const
  19477. descendantOp = 92,
  19478. Unit = 1,
  19479. callee = 93,
  19480. identifier = 94;
  19481. /* Hand-written tokenizers for CSS tokens that can't be
  19482. expressed by Lezer's built-in tokenizer. */
  19483. const space$1 = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197,
  19484. 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288];
  19485. const colon = 58, parenL = 40, underscore = 95, bracketL = 91, dash = 45, period = 46,
  19486. hash = 35, percent = 37;
  19487. function isAlpha(ch) { return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 161 }
  19488. function isDigit(ch) { return ch >= 48 && ch <= 57 }
  19489. const identifiers = new ExternalTokenizer((input, token) => {
  19490. let start = token.start, pos = start, inside = false;
  19491. for (;;) {
  19492. let next = input.get(pos);
  19493. if (isAlpha(next) || next == dash || next == underscore || (inside && isDigit(next))) {
  19494. if (!inside && (next != dash || pos > start)) inside = true;
  19495. pos++;
  19496. continue
  19497. }
  19498. if (inside)
  19499. token.accept(next == parenL ? callee : identifier, pos);
  19500. break
  19501. }
  19502. });
  19503. const descendant = new ExternalTokenizer((input, token) => {
  19504. if (space$1.includes(input.get(token.start - 1))) {
  19505. let next = input.get(token.start);
  19506. if (isAlpha(next) || next == underscore || next == hash || next == period ||
  19507. next == bracketL || next == colon || next == dash)
  19508. token.accept(descendantOp, token.start);
  19509. }
  19510. });
  19511. const unitToken = new ExternalTokenizer((input, token) => {
  19512. let {start} = token;
  19513. if (!space$1.includes(input.get(start - 1))) {
  19514. let next = input.get(start);
  19515. if (next == percent) token.accept(Unit, start + 1);
  19516. if (isAlpha(next)) {
  19517. let pos = start + 1;
  19518. while (isAlpha(input.get(pos))) pos++;
  19519. token.accept(Unit, pos);
  19520. }
  19521. }
  19522. });
  19523. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19524. const spec_callee = {__proto__:null,not:30, url:64, "url-prefix":64, domain:64, regexp:64, selector:132};
  19525. const spec_AtKeyword = {__proto__:null,"@import":112, "@media":136, "@charset":140, "@namespace":144, "@keyframes":150, "@supports":162};
  19526. const spec_identifier = {__proto__:null,not:126, only:126, from:156, to:158};
  19527. const parser$2 = Parser.deserialize({
  19528. version: 13,
  19529. states: "7WOYQ[OOOOQP'#Cc'#CcOOQP'#Cb'#CbO!ZQ[O'#CeO!}QXO'#C`O#UQ[O'#CgO#aQ[O'#DOO#fQ[O'#DSOOQP'#Eb'#EbO#kQdO'#DdO$SQ[O'#DqO#kQdO'#DsO$eQ[O'#DuO$pQ[O'#DxO$uQ[O'#EOO%TQ[O'#EQOOQS'#Ea'#EaOOQS'#ER'#ERQYQ[OOOOQP'#Cf'#CfOOQP,59P,59PO!ZQ[O,59PO%[Q[O'#ESO%vQWO,58zO&OQ[O,59RO#aQ[O,59jO#fQ[O,59nO%[Q[O,59rO%[Q[O,59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gP&rP#gP#g#gPPP&x'['hPP#_PP'n'n'x'nP'nP'n'nP#_P#_P#_P'{#_P(O(RPP#_P#_(U(d(n(|)S)Y)d)jPPPPPP)p)xP*d*g*jP+`+i]`Obn!s#d$QiWObfklmn!s!t#V#d$QiQObfklmn!s!t#V#d$QQdRR!ceQrTR!ghQ!gsR#`!hQtTR!ihQ!gtQ!|!OR#`!iq!QXZz!u!w!z#b#c#k#r$O$X$^$e$f$jp!QXZz!u!w!z#b#c#k#r$O$X$^$e$f$jT#z#[#{q!OXZz!u!w!z#b#c#k#r$O$X$^$e$f$jp!QXZz!u!w!z#b#c#k#r$O$X$^$e$f$jQ![[R#Z!]QvUR!jiQxVR!kjQoSQ!fgQ#W!XQ#^!`Q#_!aR$`#zQ!rnQ#g!sQ$P#dR$h$QX!pn!s#d$Qa!WY^_|!S!U#R#SR#P!SR!][R!_]R#]!_QbOU!bb!s$QQ!snR$Q#dQgSS!eg$UR$U#hQ#k!uU$W#k$^$jQ$^#rR$j$XQ$Y#kR$k$YQ$f$OR$n$fQ#e!rS$R#e$TR$T#gQ#T!TR#v#TQ#{#[R$a#{]aObn!s#d$Q[SObn!s#d$QQ!dfQ!lkQ!mlQ!nmQ#h!tR#w#VR#i!tR#l!uQ|XQ!YZQ!xz[#j!u#k#r$X$^$jQ#m!wQ#o!zQ#}#bQ$O#cS$d$O$fR$m$eQ!XYQ!a_R!{|U!TY_|Q!`^Q#Q!SQ#U!UQ#t#RR#u#S",
  19532. nodeNames: "⚠ Unit Comment StyleSheet RuleSet UniversalSelector TagSelector TagName NestingSelector ClassSelector ClassName PseudoClassSelector : :: PseudoClassName not ) ( ArgList , PseudoClassName ArgList ValueName ParenthesizedValue ColorLiteral NumberLiteral StringLiteral BinaryExpression BinOp CallExpression Callee CallLiteral CallTag ParenthesizedContent IdSelector # IdName ] AttributeSelector [ AttributeName MatchOp ChildSelector ChildOp DescendantSelector SiblingSelector SiblingOp } { Block Declaration PropertyName Important ; ImportStatement AtKeyword import KeywordQuery FeatureQuery FeatureName BinaryQuery LogicOp UnaryQuery UnaryQueryOp ParenthesizedQuery SelectorQuery callee MediaStatement media CharsetStatement charset NamespaceStatement namespace NamespaceName KeyframesStatement keyframes KeyframeName KeyframeList from to SupportsStatement supports AtRule",
  19533. maxTerm: 105,
  19534. nodeProps: [
  19535. [NodeProp.openedBy, 16,"(",47,"{"],
  19536. [NodeProp.closedBy, 17,")",48,"}"]
  19537. ],
  19538. skippedNodes: [0,2],
  19539. repeatNodeCount: 8,
  19540. tokenData: "Bj~R![OX$wX^%]^p$wpq%]qr(crs+}st,otu2Uuv$wvw2rwx2}xy3jyz3uz{3z{|4_|}8u}!O9Q!O!P9i!P!Q9z!Q![<U![!]<y!]!^=i!^!_$w!_!`=t!`!a>P!a!b$w!b!c>o!c!}$w!}#O?{#O#P$w#P#Q@W#Q#R2U#R#T$w#T#U@c#U#c$w#c#dAb#d#o$w#o#pAq#p#q2U#q#rA|#r#sBX#s#y$w#y#z%]#z$f$w$f$g%]$g#BY$w#BY#BZ%]#BZ$IS$w$IS$I_%]$I_$I|$w$I|$JO%]$JO$JT$w$JT$JU%]$JU$KV$w$KV$KW%]$KW&FU$w&FU&FV%]&FV~$wW$zQOy%Qz~%QW%VQqWOy%Qz~%Q~%bf#S~OX%QX^&v^p%Qpq&vqy%Qz#y%Q#y#z&v#z$f%Q$f$g&v$g#BY%Q#BY#BZ&v#BZ$IS%Q$IS$I_&v$I_$I|%Q$I|$JO&v$JO$JT%Q$JT$JU&v$JU$KV%Q$KV$KW&v$KW&FU%Q&FU&FV&v&FV~%Q~&}f#S~qWOX%QX^&v^p%Qpq&vqy%Qz#y%Q#y#z&v#z$f%Q$f$g&v$g#BY%Q#BY#BZ&v#BZ$IS%Q$IS$I_&v$I_$I|%Q$I|$JO&v$JO$JT%Q$JT$JU&v$JU$KV%Q$KV$KW&v$KW&FU%Q&FU&FV&v&FV~%Q^(fSOy%Qz#]%Q#]#^(r#^~%Q^(wSqWOy%Qz#a%Q#a#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okenizers: [descendant, unitToken, identifiers, 0, 1, 2, 3],
  19542. topRules: {"StyleSheet":[0,3]},
  19543. specialized: [{term: 93, get: value => spec_callee[value] || -1},{term: 55, get: value => spec_AtKeyword[value] || -1},{term: 94, get: value => spec_identifier[value] || -1}],
  19544. tokenPrec: 1060
  19545. });
  19546. let _properties = null;
  19547. function properties() {
  19548. if (!_properties && typeof document == "object" && document.body) {
  19549. let names = [];
  19550. for (let prop in document.body.style) {
  19551. if (!/[A-Z]|^-|^(item|length)$/.test(prop))
  19552. names.push(prop);
  19553. }
  19554. _properties = names.sort().map(name => ({ type: "property", label: name }));
  19555. }
  19556. return _properties || [];
  19557. }
  19558. const pseudoClasses = [
  19559. "active", "after", "before", "checked", "default",
  19560. "disabled", "empty", "enabled", "first-child", "first-letter",
  19561. "first-line", "first-of-type", "focus", "hover", "in-range",
  19562. "indeterminate", "invalid", "lang", "last-child", "last-of-type",
  19563. "link", "not", "nth-child", "nth-last-child", "nth-last-of-type",
  19564. "nth-of-type", "only-of-type", "only-child", "optional", "out-of-range",
  19565. "placeholder", "read-only", "read-write", "required", "root",
  19566. "selection", "target", "valid", "visited"
  19567. ].map(name => ({ type: "class", label: name }));
  19568. const values = [
  19569. "above", "absolute", "activeborder", "additive", "activecaption", "after-white-space",
  19570. "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", "always",
  19571. "antialiased", "appworkspace", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column",
  19572. "avoid-page", "avoid-region", "axis-pan", "background", "backwards", "baseline", "below",
  19573. "bidi-override", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
  19574. "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
  19575. "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "capitalize",
  19576. "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle",
  19577. "cjk-decimal", "clear", "clip", "close-quote", "col-resize", "collapse", "color", "color-burn",
  19578. "color-dodge", "column", "column-reverse", "compact", "condensed", "contain", "content",
  19579. "contents", "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover",
  19580. "crop", "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
  19581. "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in",
  19582. "destination-out", "destination-over", "difference", "disc", "discard", "disclosure-closed",
  19583. "disclosure-open", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize",
  19584. "ease", "ease-in", "ease-in-out", "ease-out", "element", "ellipse", "ellipsis", "embed", "end",
  19585. "ethiopic-abegede-gez", "ethiopic-halehame-aa-er", "ethiopic-halehame-gez", "ew-resize", "exclusion",
  19586. "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fill-box",
  19587. "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from",
  19588. "geometricPrecision", "graytext", "grid", "groove", "hand", "hard-light", "help", "hidden", "hide",
  19589. "higher", "highlight", "highlighttext", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
  19590. "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext",
  19591. "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid",
  19592. "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "keep-all",
  19593. "landscape", "large", "larger", "left", "level", "lighter", "lighten", "line-through", "linear",
  19594. "linear-gradient", "lines", "list-item", "listbox", "listitem", "local", "logical", "loud", "lower",
  19595. "lower-hexadecimal", "lower-latin", "lower-norwegian", "lowercase", "ltr", "luminosity", "manipulation",
  19596. "match", "matrix", "matrix3d", "medium", "menu", "menutext", "message-box", "middle", "min-intrinsic",
  19597. "mix", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "n-resize", "narrower",
  19598. "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none",
  19599. "normal", "not-allowed", "nowrap", "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize",
  19600. "oblique", "opacity", "open-quote", "optimizeLegibility", "optimizeSpeed", "outset", "outside",
  19601. "outside-shape", "overlay", "overline", "padding", "padding-box", "painted", "page", "paused",
  19602. "perspective", "pinch-zoom", "plus-darker", "plus-lighter", "pointer", "polygon", "portrait",
  19603. "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radial-gradient", "radio",
  19604. "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", "relative", "repeat",
  19605. "repeating-linear-gradient", "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
  19606. "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", "rotateZ", "round",
  19607. "row", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturation",
  19608. "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position",
  19609. "se-resize", "self-start", "self-end", "semi-condensed", "semi-expanded", "separate", "serif", "show",
  19610. "single", "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
  19611. "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps",
  19612. "small-caption", "smaller", "soft-light", "solid", "source-atop", "source-in", "source-out",
  19613. "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "start",
  19614. "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", "subpixel-antialiased", "svg_masks",
  19615. "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", "table-caption", "table-cell",
  19616. "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row",
  19617. "table-row-group", "text", "text-bottom", "text-top", "textarea", "textfield", "thick", "thin",
  19618. "threeddarkshadow", "threedface", "threedhighlight", "threedlightshadow", "threedshadow", "to", "top",
  19619. "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent",
  19620. "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", "upper-latin",
  19621. "uppercase", "url", "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill",
  19622. "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", "window", "windowframe",
  19623. "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small"
  19624. ].map(name => ({ type: "keyword", label: name })).concat([
  19625. "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
  19626. "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
  19627. "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
  19628. "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
  19629. "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
  19630. "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
  19631. "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
  19632. "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
  19633. "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
  19634. "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
  19635. "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
  19636. "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
  19637. "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
  19638. "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
  19639. "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
  19640. "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
  19641. "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
  19642. "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
  19643. "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
  19644. "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
  19645. "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
  19646. "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
  19647. "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
  19648. "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
  19649. "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
  19650. "whitesmoke", "yellow", "yellowgreen"
  19651. ].map(name => ({ type: "constant", label: name })));
  19652. const tags$1 = [
  19653. "a", "abbr", "address", "article", "aside", "b", "bdi", "bdo", "blockquote", "body",
  19654. "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "dd", "del",
  19655. "details", "dfn", "dialog", "div", "dl", "dt", "em", "figcaption", "figure", "footer",
  19656. "form", "header", "hgroup", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "html", "i", "iframe",
  19657. "img", "input", "ins", "kbd", "label", "legend", "li", "main", "meter", "nav", "ol", "output",
  19658. "p", "pre", "ruby", "section", "select", "small", "source", "span", "strong", "sub", "summary",
  19659. "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "tr", "u", "ul"
  19660. ].map(name => ({ type: "type", label: name }));
  19661. const span = /^[\w-]*/;
  19662. const completeCSS = context => {
  19663. let { state, pos } = context, node = syntaxTree(state).resolve(pos, -1);
  19664. if (node.name == "PropertyName")
  19665. return { from: node.from, options: properties(), span };
  19666. if (node.name == "ValueName")
  19667. return { from: node.from, options: values, span };
  19668. if (node.name == "PseudoClassName")
  19669. return { from: node.from, options: pseudoClasses, span };
  19670. if (node.name == "TagName") {
  19671. for (let { parent } = node; parent; parent = parent.parent)
  19672. if (parent.name == "Block")
  19673. return { from: node.from, options: properties(), span };
  19674. return { from: node.from, options: tags$1, span };
  19675. }
  19676. if (!context.explicit)
  19677. return null;
  19678. let above = node.resolve(pos), before = above.childBefore(pos);
  19679. if (before && before.name == ":" && above.name == "PseudoClassSelector")
  19680. return { from: pos, options: pseudoClasses, span };
  19681. if (before && before.name == ":" && above.name == "Declaration" || above.name == "ArgList")
  19682. return { from: pos, options: values, span };
  19683. if (above.name == "Block")
  19684. return { from: pos, options: properties(), span };
  19685. return null;
  19686. };
  19687. /// A language provider based on the [Lezer CSS
  19688. /// parser](https://github.com/lezer-parser/css), extended with
  19689. /// highlighting and indentation information.
  19690. const cssLanguage = LezerLanguage.define({
  19691. parser: parser$2.configure({
  19692. props: [
  19693. indentNodeProp.add({
  19694. Declaration: continuedIndent()
  19695. }),
  19696. foldNodeProp.add({
  19697. Block(subtree) { return { from: subtree.from + 1, to: subtree.to - 1 }; }
  19698. }),
  19699. styleTags({
  19700. "import charset namespace keyframes": tags.definitionKeyword,
  19701. "media supports": tags.controlKeyword,
  19702. "from to": tags.keyword,
  19703. NamespaceName: tags.namespace,
  19704. KeyframeName: tags.labelName,
  19705. TagName: tags.typeName,
  19706. ClassName: tags.className,
  19707. PseudoClassName: tags.constant(tags.className),
  19708. not: tags.operatorKeyword,
  19709. IdName: tags.labelName,
  19710. "FeatureName PropertyName AttributeName": tags.propertyName,
  19711. NumberLiteral: tags.number,
  19712. KeywordQuery: tags.keyword,
  19713. UnaryQueryOp: tags.operatorKeyword,
  19714. callee: tags.keyword,
  19715. "CallTag ValueName": tags.atom,
  19716. Callee: tags.variableName,
  19717. Unit: tags.unit,
  19718. "UniversalSelector NestingSelector": tags.definitionOperator,
  19719. AtKeyword: tags.keyword,
  19720. MatchOp: tags.compareOperator,
  19721. "ChildOp SiblingOp, LogicOp": tags.logicOperator,
  19722. BinOp: tags.arithmeticOperator,
  19723. Important: tags.modifier,
  19724. Comment: tags.blockComment,
  19725. ParenthesizedContent: tags.special(tags.name),
  19726. ColorLiteral: tags.color,
  19727. StringLiteral: tags.string,
  19728. ":": tags.punctuation,
  19729. "PseudoOp #": tags.derefOperator,
  19730. "; ,": tags.separator,
  19731. "( )": tags.paren,
  19732. "[ ]": tags.squareBracket,
  19733. "{ }": tags.brace
  19734. })
  19735. ]
  19736. }),
  19737. languageData: {
  19738. commentTokens: { block: { open: "/*", close: "*/" } },
  19739. indentOnInput: /^\s*\}$/
  19740. }
  19741. });
  19742. /// CSS property and value keyword completion.
  19743. const cssCompletion = cssLanguage.data.of({ autocomplete: completeCSS });
  19744. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19745. const
  19746. noSemi = 268,
  19747. incdec = 1,
  19748. incdecPrefix = 2,
  19749. templateContent = 269,
  19750. templateDollarBrace = 270,
  19751. templateEnd = 271,
  19752. insertSemi = 272,
  19753. TSExtends = 3,
  19754. Dialect_ts = 1;
  19755. /* Hand-written tokenizers for JavaScript tokens that can't be
  19756. expressed by lezer's built-in tokenizer. */
  19757. const newline = [10, 13, 8232, 8233];
  19758. const space$2 = [9, 11, 12, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288];
  19759. const braceR = 125, braceL = 123, semicolon = 59, slash$1 = 47, star = 42,
  19760. plus = 43, minus = 45, dollar = 36, backtick = 96, backslash = 92;
  19761. // FIXME this should technically enter block comments
  19762. function newlineBefore(input, pos) {
  19763. for (let i = pos - 1; i >= 0; i--) {
  19764. let prev = input.get(i);
  19765. if (newline.indexOf(prev) > -1) return true
  19766. if (space$2.indexOf(prev) < 0) break
  19767. }
  19768. return false
  19769. }
  19770. const insertSemicolon = new ExternalTokenizer((input, token, stack) => {
  19771. let pos = token.start, next = input.get(pos);
  19772. if ((next == braceR || next == -1 || newlineBefore(input, pos)) && stack.canShift(insertSemi))
  19773. token.accept(insertSemi, token.start);
  19774. }, {contextual: true, fallback: true});
  19775. const noSemicolon = new ExternalTokenizer((input, token, stack) => {
  19776. let pos = token.start, next = input.get(pos++);
  19777. if (space$2.indexOf(next) > -1 || newline.indexOf(next) > -1) return
  19778. if (next == slash$1) {
  19779. let after = input.get(pos++);
  19780. if (after == slash$1 || after == star) return
  19781. }
  19782. if (next != braceR && next != semicolon && next != -1 && !newlineBefore(input, token.start) &&
  19783. stack.canShift(noSemi))
  19784. token.accept(noSemi, token.start);
  19785. }, {contextual: true});
  19786. const incdecToken = new ExternalTokenizer((input, token, stack) => {
  19787. let pos = token.start, next = input.get(pos);
  19788. if ((next == plus || next == minus) && next == input.get(pos + 1)) {
  19789. let mayPostfix = !newlineBefore(input, token.start) && stack.canShift(incdec);
  19790. token.accept(mayPostfix ? incdec : incdecPrefix, pos + 2);
  19791. }
  19792. }, {contextual: true});
  19793. const template = new ExternalTokenizer((input, token) => {
  19794. let pos = token.start, afterDollar = false;
  19795. for (;;) {
  19796. let next = input.get(pos++);
  19797. if (next < 0) {
  19798. if (pos - 1 > token.start) token.accept(templateContent, pos - 1);
  19799. break
  19800. } else if (next == backtick) {
  19801. if (pos == token.start + 1) token.accept(templateEnd, pos);
  19802. else token.accept(templateContent, pos - 1);
  19803. break
  19804. } else if (next == braceL && afterDollar) {
  19805. if (pos == token.start + 2) token.accept(templateDollarBrace, pos);
  19806. else token.accept(templateContent, pos - 2);
  19807. break
  19808. } else if (next == 10 /* "\n" */ && pos > token.start + 1) {
  19809. // Break up template strings on lines, to avoid huge tokens
  19810. token.accept(templateContent, pos);
  19811. break
  19812. } else if (next == backslash && pos != input.length) {
  19813. pos++;
  19814. }
  19815. afterDollar = next == dollar;
  19816. }
  19817. });
  19818. function tsExtends(value, stack) {
  19819. return value == "extends" && stack.dialectEnabled(Dialect_ts) ? TSExtends : -1
  19820. }
  19821. // This file was generated by lezer-generator. You probably shouldn't edit it.
  19822. const spec_identifier$1 = {__proto__:null,export:16, as:21, from:25, default:30, async:35, function:36, this:46, true:54, false:54, void:58, typeof:62, null:76, super:78, new:112, await:129, yield:131, delete:132, class:142, extends:144, public:181, private:181, protected:181, readonly:183, in:202, instanceof:204, import:236, keyof:285, unique:289, infer:295, is:329, abstract:349, implements:351, type:353, let:356, var:358, const:360, interface:367, enum:371, namespace:377, module:379, declare:383, global:387, for:408, of:417, while:420, with:424, do:428, if:432, else:434, switch:438, case:444, try:450, catch:452, finally:454, return:458, throw:462, break:466, continue:470, debugger:474};
  19823. const spec_word = {__proto__:null,async:99, get:101, set:103, public:151, private:151, protected:151, static:153, abstract:155, readonly:159, new:333};
  19824. const spec_LessThan = {__proto__:null,"<":119};
  19825. const parser$3 = Parser.deserialize({
  19826. version: 13,
  19827. states: "$8YO]QYOOO&zQ!LdO'#CgO'ROSO'#DRO)ZQYO'#DWO)kQYO'#DcO)rQYO'#DmO-iQYO'#DsOOQO'#ET'#ETO-|QWO'#ESO.RQWO'#ESO.ZQ!LdO'#IfO2dQ!LdO'#IgO3QQWO'#EpO3VQpO'#FUOOQ!LS'#Ex'#ExO3_O!bO'#ExO3mQWO'#F]O4wQWO'#F[OOQ!LS'#Ig'#IgOOQ!LS'#If'#IfOOQQ'#JQ'#JQO4|QWO'#HdO5RQ!LYO'#HeOOQQ'#IZ'#IZOOQQ'#Hf'#HfQ]QYOOO)rQYO'#DeO5ZQWO'#GPO5`Q#tO'#ClO5nQWO'#ESO5yQ#tO'#EwO6eQWO'#GPO6jQWO'#GTO6uQWO'#GTO7TQWO'#GXO7TQWO'#GYO7TQWO'#G[O5ZQWO'#G_O7tQWO'#GbO9SQWO'#CcO9dQWO'#GoO9lQWO'#GuO9lQWO'#GwO]QYO'#GyO9lQWO'#G{O9lQWO'#HOO9qQWO'#HUO9vQ!LZO'#HYO)rQYO'#H[O:RQ!LZO'#H^O:^Q!LZO'#H`O5RQ!LYO'#HbO)rQYO'#IiOOOS'#Hg'#HgO:iOSO,59mOOQ!LS,59m,59mO<zQbO'#CgO=UQYO'#HhO=cQWO'#IkO?bQbO'#IkO'^QYO'#IkO?iQWO,59rO@PQ&jO'#D]O@xQWO'#ETOAVQWO'#IuOAbQWO'#ItOAjQWO,5:qOAoQWO'#IsOAvQWO'#DtO5`Q#tO'#ERO5qQWO'#ESOBUQ`O'#EwOOQ!LS,59},59}OB^QYO,59}OD[Q!LdO,5:XODxQWO,5:_OEcQ!LYO'#IrO6jQWO'#IqOEjQWO'#IqOErQWO,5:pOEwQWO'#IqOFVQYO,5:nOHSQWO'#EPOIZQWO,5:n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)d$mR)Z$gT%[x%_T%]x%_T.x*c.y",
  19830. nodeNames: "⚠ ArithOp ArithOp extends LineComment BlockComment Script ExportDeclaration export Star as VariableName from String ; default FunctionDeclaration async function VariableDefinition TypeParamList TypeDefinition ThisType this LiteralType ArithOp Number BooleanLiteral VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString null super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyNameDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression await yield delete LogicOp BitOp ParenthesizedExpression ClassExpression class extends ClassBody MethodDeclaration Privacy static abstract PropertyDeclaration readonly Optional TypeAnnotation Equals FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp in instanceof CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplatExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var const TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody MethodDeclaration AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try catch finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement",
  19831. maxTerm: 320,
  19832. nodeProps: [
  19833. [NodeProp.group, -26,7,14,16,53,173,177,181,182,184,187,190,201,203,209,211,213,215,218,224,228,230,232,234,236,238,239,"Statement",-30,11,13,23,26,27,37,38,39,40,42,47,55,63,69,70,83,84,93,94,109,112,114,115,116,117,119,120,137,138,140,"Expression",-21,22,24,28,30,141,143,145,146,148,149,150,152,153,154,156,157,158,167,169,171,172,"Type",-2,74,78,"ClassItem"],
  19834. [NodeProp.closedBy, 36,"]",46,"}",61,")",122,"JSXSelfCloseEndTag JSXEndTag",135,"JSXEndTag"],
  19835. [NodeProp.openedBy, 41,"[",45,"{",60,"(",121,"JSXStartTag",130,"JSXStartTag JSXStartCloseTag"]
  19836. ],
  19837. skippedNodes: [0,4,5],
  19838. repeatNodeCount: 27,
  19839. tokenData: "!Ck~R!ZOX$tX^%S^p$tpq%Sqr&rrs'zst$ttu/wuv2Xvw2|wx3zxy:byz:rz{;S{|<S|}<g}!O<S!O!P<w!P!QAT!Q!R!0Z!R![!2j![!]!8Y!]!^!8l!^!_!8|!_!`!9y!`!a!;U!a!b!<{!b!c$t!c!}/w!}#O!>^#O#P$t#P#Q!>n#Q#R!?O#R#S/w#S#T!?c#T#o/w#o#p!?s#p#q!?x#q#r!@`#r#s!@r#s#y$t#y#z%S#z$f$t$f$g%S$g#BY/w#BY#BZ!AS#BZ$IS/w$IS$I_!AS$I_$I|/w$I|$JO!AS$JO$JT/w$JT$JU!AS$JU$KV/w$KV$KW!AS$KW&FU/w&FU&FV!AS&FV~/wW$yR#yWO!^$t!_#o$t#p~$t,T%Zg#yW&|+{OX$tX^%S^p$tpq%Sq!^$t!_#o$t#p#y$t#y#z%S#z$f$t$f$g%S$g#BY$t#BY#BZ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'^QO!^$t!_#o$t#p~$tX!@yR!fP#yWO!^$t!_#o$t#p~$t,T!Aar#yW#pS'Xp'O%k&|+{OX$tX^%S^p$tpq%Sqt$ttu/wu}$t}!O1R!O!Q$t!Q![/w![!^$t!_!c$t!c!}/w!}#R$t#R#S/w#S#T$t#T#o/w#p#y$t#y#z%S#z$f$t$f$g%S$g#BY/w#BY#BZ!AS#BZ$IS/w$IS$I_!AS$I_$I|/w$I|$JO!AS$JO$JT/w$JT$JU!AS$JU$KV/w$KV$KW!AS$KW&FU/w&FU&FV!AS&FV~/w",
  19840. tokenizers: [noSemicolon, incdecToken, template, 0, 1, 2, 3, 4, 5, 6, 7, 8, insertSemicolon],
  19841. topRules: {"Script":[0,6]},
  19842. dialects: {jsx: 12762, ts: 12764},
  19843. dynamicPrecedences: {"138":1,"165":1},
  19844. specialized: [{term: 276, get: (value, stack) => (tsExtends(value, stack) << 1) | 1},{term: 276, get: value => spec_identifier$1[value] || -1},{term: 285, get: value => spec_word[value] || -1},{term: 58, get: value => spec_LessThan[value] || -1}],
  19845. tokenPrec: 12784
  19846. });
  19847. /// A collection of JavaScript-related
  19848. /// [snippets](#autocomplete.snippet).
  19849. const snippets = [
  19850. snippetCompletion("function ${name}(${params}) {\n\t${}\n}", {
  19851. label: "function",
  19852. detail: "definition",
  19853. type: "keyword"
  19854. }),
  19855. snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}", {
  19856. label: "for",
  19857. detail: "loop",
  19858. type: "keyword"
  19859. }),
  19860. snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}", {
  19861. label: "for",
  19862. detail: "of loop",
  19863. type: "keyword"
  19864. }),
  19865. snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}", {
  19866. label: "try",
  19867. detail: "block",
  19868. type: "keyword"
  19869. }),
  19870. snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}", {
  19871. label: "class",
  19872. detail: "definition",
  19873. type: "keyword"
  19874. }),
  19875. snippetCompletion("import {${names}} from \"${module}\"\n${}", {
  19876. label: "import",
  19877. detail: "named",
  19878. type: "keyword"
  19879. }),
  19880. snippetCompletion("import ${name} from \"${module}\"\n${}", {
  19881. label: "import",
  19882. detail: "default",
  19883. type: "keyword"
  19884. })
  19885. ];
  19886. /// A language provider based on the [Lezer JavaScript
  19887. /// parser](https://github.com/lezer-parser/javascript), extended with
  19888. /// highlighting and indentation information.
  19889. const javascriptLanguage = LezerLanguage.define({
  19890. parser: parser$3.configure({
  19891. props: [
  19892. indentNodeProp.add({
  19893. IfStatement: continuedIndent({ except: /^\s*({|else\b)/ }),
  19894. TryStatement: continuedIndent({ except: /^\s*({|catch|finally)\b/ }),
  19895. LabeledStatement: flatIndent,
  19896. SwitchBody: context => {
  19897. let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
  19898. return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
  19899. },
  19900. Block: delimitedIndent({ closing: "}" }),
  19901. "TemplateString BlockComment": () => -1,
  19902. "Statement Property": continuedIndent({ except: /^{/ })
  19903. }),
  19904. foldNodeProp.add({
  19905. "Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression"(tree) {
  19906. return { from: tree.from + 1, to: tree.to - 1 };
  19907. },
  19908. BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
  19909. }),
  19910. styleTags({
  19911. "get set async static": tags.modifier,
  19912. "for while do if else switch try catch finally return throw break continue default case": tags.controlKeyword,
  19913. "in of await yield void typeof delete instanceof": tags.operatorKeyword,
  19914. "export import let var const function class extends": tags.definitionKeyword,
  19915. "with debugger from as new": tags.keyword,
  19916. TemplateString: tags.special(tags.string),
  19917. Super: tags.atom,
  19918. BooleanLiteral: tags.bool,
  19919. this: tags.self,
  19920. null: tags.null,
  19921. Star: tags.modifier,
  19922. VariableName: tags.variableName,
  19923. "CallExpression/VariableName": tags.function(tags.variableName),
  19924. VariableDefinition: tags.definition(tags.variableName),
  19925. Label: tags.labelName,
  19926. PropertyName: tags.propertyName,
  19927. "CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName),
  19928. PropertyNameDefinition: tags.definition(tags.propertyName),
  19929. UpdateOp: tags.updateOperator,
  19930. LineComment: tags.lineComment,
  19931. BlockComment: tags.blockComment,
  19932. Number: tags.number,
  19933. String: tags.string,
  19934. ArithOp: tags.arithmeticOperator,
  19935. LogicOp: tags.logicOperator,
  19936. BitOp: tags.bitwiseOperator,
  19937. CompareOp: tags.compareOperator,
  19938. RegExp: tags.regexp,
  19939. Equals: tags.definitionOperator,
  19940. "Arrow : Spread": tags.punctuation,
  19941. "( )": tags.paren,
  19942. "[ ]": tags.squareBracket,
  19943. "{ }": tags.brace,
  19944. ".": tags.derefOperator,
  19945. ", ;": tags.separator,
  19946. TypeName: tags.typeName,
  19947. TypeDefinition: tags.definition(tags.typeName),
  19948. "type enum interface implements namespace module declare": tags.definitionKeyword,
  19949. "abstract global privacy readonly": tags.modifier,
  19950. "is keyof unique infer": tags.operatorKeyword,
  19951. JSXAttributeValue: tags.string,
  19952. JSXText: tags.content,
  19953. "JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags.angleBracket,
  19954. "JSXIdentifier JSXNameSpacedName": tags.typeName,
  19955. "JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags.propertyName
  19956. })
  19957. ]
  19958. }),
  19959. languageData: {
  19960. closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
  19961. commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
  19962. indentOnInput: /^\s*(?:case |default:|\{|\})$/,
  19963. wordChars: "$"
  19964. }
  19965. });
  19966. /// A language provider for TypeScript.
  19967. const typescriptLanguage = javascriptLanguage.configure({ dialect: "ts" });
  19968. /// Language provider for JSX.
  19969. const jsxLanguage = javascriptLanguage.configure({ dialect: "jsx" });
  19970. /// Language provider for JSX + TypeScript.
  19971. const tsxLanguage = javascriptLanguage.configure({ dialect: "jsx ts" });
  19972. const Targets = ["_blank", "_self", "_top", "_parent"];
  19973. const Charsets = ["ascii", "utf-8", "utf-16", "latin1", "latin1"];
  19974. const Methods = ["get", "post", "put", "delete"];
  19975. const Encs = ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"];
  19976. const Bool = ["true", "false"];
  19977. const S = {}; // Empty tag spec
  19978. const Tags = {
  19979. a: {
  19980. attrs: {
  19981. href: null, ping: null, type: null,
  19982. media: null,
  19983. target: Targets,
  19984. hreflang: null
  19985. }
  19986. },
  19987. abbr: S,
  19988. acronym: S,
  19989. address: S,
  19990. applet: S,
  19991. area: {
  19992. attrs: {
  19993. alt: null, coords: null, href: null, target: null, ping: null,
  19994. media: null, hreflang: null, type: null,
  19995. shape: ["default", "rect", "circle", "poly"]
  19996. }
  19997. },
  19998. article: S,
  19999. aside: S,
  20000. audio: {
  20001. attrs: {
  20002. src: null, mediagroup: null,
  20003. crossorigin: ["anonymous", "use-credentials"],
  20004. preload: ["none", "metadata", "auto"],
  20005. autoplay: ["autoplay"],
  20006. loop: ["loop"],
  20007. controls: ["controls"]
  20008. }
  20009. },
  20010. b: S,
  20011. base: { attrs: { href: null, target: Targets } },
  20012. basefont: S,
  20013. bdi: S,
  20014. bdo: S,
  20015. big: S,
  20016. blockquote: { attrs: { cite: null } },
  20017. body: S,
  20018. br: S,
  20019. button: {
  20020. attrs: {
  20021. form: null, formaction: null, name: null, value: null,
  20022. autofocus: ["autofocus"],
  20023. disabled: ["autofocus"],
  20024. formenctype: Encs,
  20025. formmethod: Methods,
  20026. formnovalidate: ["novalidate"],
  20027. formtarget: Targets,
  20028. type: ["submit", "reset", "button"]
  20029. }
  20030. },
  20031. canvas: { attrs: { width: null, height: null } },
  20032. caption: S,
  20033. center: S,
  20034. cite: S,
  20035. code: S,
  20036. col: { attrs: { span: null } },
  20037. colgroup: { attrs: { span: null } },
  20038. command: {
  20039. attrs: {
  20040. type: ["command", "checkbox", "radio"],
  20041. label: null, icon: null, radiogroup: null, command: null, title: null,
  20042. disabled: ["disabled"],
  20043. checked: ["checked"]
  20044. }
  20045. },
  20046. data: { attrs: { value: null } },
  20047. datagrid: { attrs: { disabled: ["disabled"], multiple: ["multiple"] } },
  20048. datalist: { attrs: { data: null } },
  20049. dd: S,
  20050. del: { attrs: { cite: null, datetime: null } },
  20051. details: { attrs: { open: ["open"] } },
  20052. dfn: S,
  20053. dir: S,
  20054. div: S,
  20055. dl: S,
  20056. dt: S,
  20057. em: S,
  20058. embed: { attrs: { src: null, type: null, width: null, height: null } },
  20059. eventsource: { attrs: { src: null } },
  20060. fieldset: { attrs: { disabled: ["disabled"], form: null, name: null } },
  20061. figcaption: S,
  20062. figure: S,
  20063. font: S,
  20064. footer: S,
  20065. form: {
  20066. attrs: {
  20067. action: null, name: null,
  20068. "accept-charset": Charsets,
  20069. autocomplete: ["on", "off"],
  20070. enctype: Encs,
  20071. method: Methods,
  20072. novalidate: ["novalidate"],
  20073. target: Targets
  20074. }
  20075. },
  20076. frame: S,
  20077. frameset: S,
  20078. h1: S, h2: S, h3: S, h4: S, h5: S, h6: S,
  20079. head: {
  20080. children: ["title", "base", "link", "style", "meta", "script", "noscript", "command"]
  20081. },
  20082. header: S,
  20083. hgroup: S,
  20084. hr: S,
  20085. html: {
  20086. attrs: { manifest: null },
  20087. children: ["head", "body"]
  20088. },
  20089. i: S,
  20090. iframe: {
  20091. attrs: {
  20092. src: null, srcdoc: null, name: null, width: null, height: null,
  20093. sandbox: ["allow-top-navigation", "allow-same-origin", "allow-forms", "allow-scripts"],
  20094. seamless: ["seamless"]
  20095. }
  20096. },
  20097. img: {
  20098. attrs: {
  20099. alt: null, src: null, ismap: null, usemap: null, width: null, height: null,
  20100. crossorigin: ["anonymous", "use-credentials"]
  20101. }
  20102. },
  20103. input: {
  20104. attrs: {
  20105. alt: null, dirname: null, form: null, formaction: null,
  20106. height: null, list: null, max: null, maxlength: null, min: null,
  20107. name: null, pattern: null, placeholder: null, size: null, src: null,
  20108. step: null, value: null, width: null,
  20109. accept: ["audio/*", "video/*", "image/*"],
  20110. autocomplete: ["on", "off"],
  20111. autofocus: ["autofocus"],
  20112. checked: ["checked"],
  20113. disabled: ["disabled"],
  20114. formenctype: Encs,
  20115. formmethod: Methods,
  20116. formnovalidate: ["novalidate"],
  20117. formtarget: Targets,
  20118. multiple: ["multiple"],
  20119. readonly: ["readonly"],
  20120. required: ["required"],
  20121. type: ["hidden", "text", "search", "tel", "url", "email", "password", "datetime", "date", "month",
  20122. "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio",
  20123. "file", "submit", "image", "reset", "button"]
  20124. }
  20125. },
  20126. ins: { attrs: { cite: null, datetime: null } },
  20127. kbd: S,
  20128. keygen: {
  20129. attrs: {
  20130. challenge: null, form: null, name: null,
  20131. autofocus: ["autofocus"],
  20132. disabled: ["disabled"],
  20133. keytype: ["RSA"]
  20134. }
  20135. },
  20136. label: { attrs: { for: null, form: null } },
  20137. legend: S,
  20138. li: { attrs: { value: null } },
  20139. link: {
  20140. attrs: {
  20141. href: null, type: null,
  20142. hreflang: null,
  20143. media: null,
  20144. sizes: ["all", "16x16", "16x16 32x32", "16x16 32x32 64x64"]
  20145. }
  20146. },
  20147. map: { attrs: { name: null } },
  20148. mark: S,
  20149. menu: { attrs: { label: null, type: ["list", "context", "toolbar"] } },
  20150. meta: {
  20151. attrs: {
  20152. content: null,
  20153. charset: Charsets,
  20154. name: ["viewport", "application-name", "author", "description", "generator", "keywords"],
  20155. "http-equiv": ["content-language", "content-type", "default-style", "refresh"]
  20156. }
  20157. },
  20158. meter: { attrs: { value: null, min: null, low: null, high: null, max: null, optimum: null } },
  20159. nav: S,
  20160. noframes: S,
  20161. noscript: S,
  20162. object: {
  20163. attrs: {
  20164. data: null, type: null, name: null, usemap: null, form: null, width: null, height: null,
  20165. typemustmatch: ["typemustmatch"]
  20166. }
  20167. },
  20168. ol: { attrs: { reversed: ["reversed"], start: null, type: ["1", "a", "A", "i", "I"] },
  20169. children: ["li", "script", "template", "ul", "ol"] },
  20170. optgroup: { attrs: { disabled: ["disabled"], label: null } },
  20171. option: { attrs: { disabled: ["disabled"], label: null, selected: ["selected"], value: null } },
  20172. output: { attrs: { for: null, form: null, name: null } },
  20173. p: S,
  20174. param: { attrs: { name: null, value: null } },
  20175. pre: S,
  20176. progress: { attrs: { value: null, max: null } },
  20177. q: { attrs: { cite: null } },
  20178. rp: S,
  20179. rt: S,
  20180. ruby: S,
  20181. s: S,
  20182. samp: S,
  20183. script: {
  20184. attrs: {
  20185. type: ["text/javascript"],
  20186. src: null,
  20187. async: ["async"],
  20188. defer: ["defer"],
  20189. charset: Charsets
  20190. }
  20191. },
  20192. section: S,
  20193. select: {
  20194. attrs: {
  20195. form: null, name: null, size: null,
  20196. autofocus: ["autofocus"],
  20197. disabled: ["disabled"],
  20198. multiple: ["multiple"]
  20199. }
  20200. },
  20201. small: S,
  20202. source: { attrs: { src: null, type: null, media: null } },
  20203. span: S,
  20204. strike: S,
  20205. strong: S,
  20206. style: {
  20207. attrs: {
  20208. type: ["text/css"],
  20209. media: null,
  20210. scoped: null
  20211. }
  20212. },
  20213. sub: S,
  20214. summary: S,
  20215. sup: S,
  20216. table: S,
  20217. tbody: S,
  20218. td: { attrs: { colspan: null, rowspan: null, headers: null } },
  20219. textarea: {
  20220. attrs: {
  20221. dirname: null, form: null, maxlength: null, name: null, placeholder: null,
  20222. rows: null, cols: null,
  20223. autofocus: ["autofocus"],
  20224. disabled: ["disabled"],
  20225. readonly: ["readonly"],
  20226. required: ["required"],
  20227. wrap: ["soft", "hard"]
  20228. }
  20229. },
  20230. tfoot: S,
  20231. th: { attrs: { colspan: null, rowspan: null, headers: null, scope: ["row", "col", "rowgroup", "colgroup"] } },
  20232. thead: S,
  20233. time: { attrs: { datetime: null } },
  20234. title: S,
  20235. tr: S,
  20236. track: {
  20237. attrs: {
  20238. src: null, label: null, default: null,
  20239. kind: ["subtitles", "captions", "descriptions", "chapters", "metadata"],
  20240. srclang: null
  20241. }
  20242. },
  20243. tt: S,
  20244. u: S,
  20245. ul: { children: ["li", "script", "template", "ul", "ol"] },
  20246. var: S,
  20247. video: {
  20248. attrs: {
  20249. src: null, poster: null, width: null, height: null,
  20250. crossorigin: ["anonymous", "use-credentials"],
  20251. preload: ["auto", "metadata", "none"],
  20252. autoplay: ["autoplay"],
  20253. mediagroup: ["movie"],
  20254. muted: ["muted"],
  20255. controls: ["controls"]
  20256. }
  20257. },
  20258. wbr: S
  20259. };
  20260. const GlobalAttrs = {
  20261. accesskey: null,
  20262. class: null,
  20263. contenteditable: Bool,
  20264. contextmenu: null,
  20265. dir: ["ltr", "rtl", "auto"],
  20266. draggable: ["true", "false", "auto"],
  20267. dropzone: ["copy", "move", "link", "string:", "file:"],
  20268. hidden: ["hidden"],
  20269. id: null,
  20270. inert: ["inert"],
  20271. itemid: null,
  20272. itemprop: null,
  20273. itemref: null,
  20274. itemscope: ["itemscope"],
  20275. itemtype: null,
  20276. lang: ["ar", "bn", "de", "en-GB", "en-US", "es", "fr", "hi", "id", "ja", "pa", "pt", "ru", "tr", "zh"],
  20277. spellcheck: Bool,
  20278. autocorrect: Bool,
  20279. autocapitalize: Bool,
  20280. style: null,
  20281. tabindex: null,
  20282. title: null,
  20283. translate: ["yes", "no"],
  20284. onclick: null,
  20285. rel: ["stylesheet", "alternate", "author", "bookmark", "help", "license", "next", "nofollow", "noreferrer", "prefetch", "prev", "search", "tag"],
  20286. role: "alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),
  20287. "aria-activedescendant": null,
  20288. "aria-atomic": Bool,
  20289. "aria-autocomplete": ["inline", "list", "both", "none"],
  20290. "aria-busy": Bool,
  20291. "aria-checked": ["true", "false", "mixed", "undefined"],
  20292. "aria-controls": null,
  20293. "aria-describedby": null,
  20294. "aria-disabled": Bool,
  20295. "aria-dropeffect": null,
  20296. "aria-expanded": ["true", "false", "undefined"],
  20297. "aria-flowto": null,
  20298. "aria-grabbed": ["true", "false", "undefined"],
  20299. "aria-haspopup": Bool,
  20300. "aria-hidden": Bool,
  20301. "aria-invalid": ["true", "false", "grammar", "spelling"],
  20302. "aria-label": null,
  20303. "aria-labelledby": null,
  20304. "aria-level": null,
  20305. "aria-live": ["off", "polite", "assertive"],
  20306. "aria-multiline": Bool,
  20307. "aria-multiselectable": Bool,
  20308. "aria-owns": null,
  20309. "aria-posinset": null,
  20310. "aria-pressed": ["true", "false", "mixed", "undefined"],
  20311. "aria-readonly": Bool,
  20312. "aria-relevant": null,
  20313. "aria-required": Bool,
  20314. "aria-selected": ["true", "false", "undefined"],
  20315. "aria-setsize": null,
  20316. "aria-sort": ["ascending", "descending", "none", "other"],
  20317. "aria-valuemax": null,
  20318. "aria-valuemin": null,
  20319. "aria-valuenow": null,
  20320. "aria-valuetext": null
  20321. };
  20322. const AllTags = Object.keys(Tags);
  20323. const GlobalAttrNames = Object.keys(GlobalAttrs);
  20324. function elementName(doc, tree) {
  20325. let tag = tree.firstChild;
  20326. if (!tag || tag.name != "OpenTag")
  20327. return "";
  20328. let name = tag.getChild("TagName");
  20329. return name ? doc.sliceString(name.from, name.to) : "";
  20330. }
  20331. function findParentElement(tree, skip = false) {
  20332. for (let cur = tree.parent; cur; cur = cur.parent)
  20333. if (cur.name == "Element") {
  20334. if (skip)
  20335. skip = false;
  20336. else
  20337. return cur;
  20338. }
  20339. return null;
  20340. }
  20341. function allowedChildren(doc, tree) {
  20342. let parent = findParentElement(tree, true);
  20343. let parentInfo = parent ? Tags[elementName(doc, parent)] : null;
  20344. return (parentInfo === null || parentInfo === void 0 ? void 0 : parentInfo.children) || AllTags;
  20345. }
  20346. function openTags(doc, tree) {
  20347. let open = [];
  20348. for (let parent = tree; parent = findParentElement(parent);) {
  20349. let tagName = elementName(doc, parent);
  20350. if (tagName && parent.lastChild.name == "CloseTag")
  20351. break;
  20352. if (tagName && open.indexOf(tagName) < 0)
  20353. open.push(tagName);
  20354. }
  20355. return open;
  20356. }
  20357. const identifier$1 = /^[:\-\.\w\u00b7-\uffff]+$/;
  20358. function completeTag(state, tree, from, to) {
  20359. let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
  20360. return { from, to,
  20361. options: allowedChildren(state.doc, tree).map(tagName => ({ label: tagName, type: "type" })).concat(openTags(state.doc, tree).map((tag, i) => ({ label: "/" + tag, apply: "/" + tag + end, type: "type", boost: 99 - i }))),
  20362. span: /^\/?[:\-\.\w\u00b7-\uffff]*$/ };
  20363. }
  20364. function completeCloseTag(state, tree, from, to) {
  20365. let end = /\s*>/.test(state.sliceDoc(to, to + 5)) ? "" : ">";
  20366. return { from, to,
  20367. options: openTags(state.doc, tree).map((tag, i) => ({ label: tag, apply: tag + end, type: "type", boost: 99 - i })),
  20368. span: identifier$1 };
  20369. }
  20370. function completeStartTag(state, tree, pos) {
  20371. let options = [], level = 0;
  20372. for (let tagName of allowedChildren(state.doc, tree))
  20373. options.push({ label: "<" + tagName, type: "type" });
  20374. for (let open of openTags(state.doc, tree))
  20375. options.push({ label: "</" + open + ">", type: "type", boost: 99 - level++ });
  20376. return { from: pos, to: pos, options, span: /^<\/?[:\-\.\w\u00b7-\uffff]*$/ };
  20377. }
  20378. function completeAttrName(state, tree, from, to) {
  20379. let elt = findParentElement(tree), info = elt ? Tags[elementName(state.doc, elt)] : null;
  20380. let names = (info && info.attrs ? Object.keys(info.attrs).concat(GlobalAttrNames) : GlobalAttrNames);
  20381. return { from, to,
  20382. options: names.map(attrName => ({ label: attrName, type: "property" })),
  20383. span: identifier$1 };
  20384. }
  20385. function completeAttrValue(state, tree, from, to) {
  20386. var _a;
  20387. let nameNode = (_a = tree.parent) === null || _a === void 0 ? void 0 : _a.getChild("AttributeName");
  20388. let options = [], span = undefined;
  20389. if (nameNode) {
  20390. let attrName = state.sliceDoc(nameNode.from, nameNode.to);
  20391. let attrs = GlobalAttrs[attrName];
  20392. if (!attrs) {
  20393. let elt = findParentElement(tree), info = elt ? Tags[elementName(state.doc, elt)] : null;
  20394. attrs = (info === null || info === void 0 ? void 0 : info.attrs) && info.attrs[attrName];
  20395. }
  20396. if (attrs) {
  20397. let base = state.sliceDoc(from, to).toLowerCase(), quoteStart = '"', quoteEnd = '"';
  20398. if (/^['"]/.test(base)) {
  20399. span = base[0] == '"' ? /^[^"]*$/ : /^[^']*$/;
  20400. quoteStart = "";
  20401. quoteEnd = state.sliceDoc(to, to + 1) == base[0] ? "" : base[0];
  20402. base = base.slice(1);
  20403. from++;
  20404. }
  20405. else {
  20406. span = /^[^\s<>='"]*$/;
  20407. }
  20408. for (let value of attrs)
  20409. options.push({ label: value, apply: quoteStart + value + quoteEnd, type: "constant" });
  20410. }
  20411. }
  20412. return { from, to, options, span };
  20413. }
  20414. function completeHTML(context) {
  20415. let { state, pos } = context, around = syntaxTree(state).resolve(pos), tree = around.resolve(pos, -1);
  20416. if (tree.name == "TagName") {
  20417. return tree.parent && /CloseTag$/.test(tree.parent.name) ? completeCloseTag(state, tree, tree.from, pos)
  20418. : completeTag(state, tree, tree.from, pos);
  20419. }
  20420. else if (tree.name == "StartTag") {
  20421. return completeTag(state, tree, pos, pos);
  20422. }
  20423. else if (tree.name == "StartCloseTag" || tree.name == "IncompleteCloseTag") {
  20424. return completeCloseTag(state, tree, pos, pos);
  20425. }
  20426. else if (context.explicit && (tree.name == "OpenTag" || tree.name == "SelfClosingTag") || tree.name == "AttributeName") {
  20427. return completeAttrName(state, tree, tree.name == "AttributeName" ? tree.from : pos, pos);
  20428. }
  20429. else if (tree.name == "Is" || tree.name == "AttributeValue" || tree.name == "UnquotedAttributeValue") {
  20430. return completeAttrValue(state, tree, tree.name == "Is" ? pos : tree.from, pos);
  20431. }
  20432. else if (context.explicit && (around.name == "Element" || around.name == "Text" || around.name == "Document")) {
  20433. return completeStartTag(state, tree, pos);
  20434. }
  20435. else {
  20436. return null;
  20437. }
  20438. }
  20439. /// A language provider based on the [Lezer HTML
  20440. /// parser](https://github.com/lezer-parser/html), wired up with the
  20441. /// JavaScript and CSS parsers to parse the content of `<script>` and
  20442. /// `<style>` tags.
  20443. const htmlLanguage = LezerLanguage.define({
  20444. parser: parser$1.configure({
  20445. props: [
  20446. indentNodeProp.add({
  20447. Element(context) {
  20448. let closed = /^\s*<\//.test(context.textAfter);
  20449. return context.lineIndent(context.state.doc.lineAt(context.node.from)) + (closed ? 0 : context.unit);
  20450. },
  20451. "OpenTag CloseTag SelfClosingTag"(context) {
  20452. return context.column(context.node.from) + context.unit;
  20453. }
  20454. }),
  20455. foldNodeProp.add({
  20456. Element(node) {
  20457. let first = node.firstChild, last = node.lastChild;
  20458. if (!first || first.name != "OpenTag")
  20459. return null;
  20460. return { from: first.to, to: last.name == "CloseTag" ? last.from : node.to };
  20461. }
  20462. }),
  20463. styleTags({
  20464. AttributeValue: tags.string,
  20465. "Text RawText": tags.content,
  20466. "StartTag StartCloseTag SelfCloserEndTag EndTag SelfCloseEndTag": tags.angleBracket,
  20467. TagName: tags.typeName,
  20468. "MismatchedCloseTag/TagName": [tags.typeName, tags.invalid],
  20469. AttributeName: tags.propertyName,
  20470. UnquotedAttributeValue: tags.string,
  20471. Is: tags.definitionOperator,
  20472. "EntityReference CharacterReference": tags.character,
  20473. Comment: tags.blockComment,
  20474. ProcessingInst: tags.processingInstruction,
  20475. DoctypeDecl: tags.documentMeta
  20476. })
  20477. ],
  20478. nested: configureNesting([
  20479. { tag: "script",
  20480. attrs(attrs) {
  20481. return !attrs.type || /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(attrs.type);
  20482. },
  20483. parser: javascriptLanguage.parser },
  20484. { tag: "style",
  20485. attrs(attrs) {
  20486. return (!attrs.lang || attrs.lang == "css") && (!attrs.type || /^(text\/)?(x-)?(stylesheet|css)$/i.test(attrs.type));
  20487. },
  20488. parser: cssLanguage.parser }
  20489. ])
  20490. }),
  20491. languageData: {
  20492. commentTokens: { block: { open: "<!--", close: "-->" } },
  20493. indentOnInput: /^\s*<\/$/
  20494. }
  20495. });
  20496. /// HTML tag completion. Opens and closes tags and attributes in a
  20497. /// context-aware way.
  20498. const htmlCompletion = htmlLanguage.data.of({ autocomplete: completeHTML });
  20499. const data = defineLanguageFacet({ block: { open: "<!--", close: "-->" } });
  20500. const parser$4 = parser.configure({
  20501. props: [
  20502. styleTags({
  20503. "Blockquote/...": tags.quote,
  20504. HorizontalRule: tags.contentSeparator,
  20505. "ATXHeading/... SetextHeading/...": tags.heading,
  20506. "Comment CommentBlock": tags.comment,
  20507. Escape: tags.escape,
  20508. Entity: tags.character,
  20509. "Emphasis/...": tags.emphasis,
  20510. "StrongEmphasis/...": tags.strong,
  20511. "Link/... Image/...": tags.link,
  20512. "OrderedList/... BulletList/...": tags.list,
  20513. "BlockQuote/...": tags.quote,
  20514. InlineCode: tags.monospace,
  20515. URL: tags.url,
  20516. "HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark": tags.processingInstruction,
  20517. "CodeInfo LinkLabel": tags.labelName,
  20518. LinkTitle: tags.string
  20519. }),
  20520. foldNodeProp.add(type => {
  20521. if (!type.is("Block") || type.is("Document"))
  20522. return undefined;
  20523. return (tree, state) => ({ from: state.doc.lineAt(tree.from).to, to: tree.to });
  20524. }),
  20525. indentNodeProp.add({
  20526. Document: () => null
  20527. }),
  20528. languageDataProp.add({
  20529. Document: data
  20530. })
  20531. ],
  20532. htmlParser: htmlLanguage.parser.configure({ dialect: "noMatch" }),
  20533. });
  20534. /// Language support for Markdown/CommonMark.
  20535. const markdownLanguage = new Language(data, parser$4);
  20536. // Create an instance of the Markdown language that will, for code
  20537. // blocks, try to find a language that matches the block's info
  20538. // string in `languages` or, if none if found, use `defaultLanguage`
  20539. // to parse the block.
  20540. function markdownWithCodeLanguages(languages, defaultLanguage) {
  20541. return new Language(data, parser$4.configure({
  20542. codeParser(info) {
  20543. let found = info && LanguageDescription.matchLanguageName(languages, info, true);
  20544. if (!found)
  20545. return defaultLanguage ? defaultLanguage.parser : null;
  20546. if (found.support)
  20547. return found.support.language.parser;
  20548. found.load();
  20549. return EditorParseContext.skippingParser;
  20550. }
  20551. }));
  20552. }
  20553. function nodeStart$1(node, doc) {
  20554. return doc.sliceString(node.from, node.from + 50);
  20555. }
  20556. function gatherMarkup(node, line, doc) {
  20557. let nodes = [];
  20558. for (let cur = node; cur && cur.name != "Document"; cur = cur.parent) {
  20559. if (cur.name == "ListItem" || cur.name == "Blockquote")
  20560. nodes.push(cur);
  20561. }
  20562. let markup = [], pos = 0;
  20563. for (let i = nodes.length - 1; i >= 0; i--) {
  20564. let node = nodes[i], match;
  20565. if (node.name == "Blockquote" && (match = /^\s*> ?/.exec(line.slice(pos)))) {
  20566. markup.push({ from: pos, string: match[0], node });
  20567. pos += match[0].length;
  20568. }
  20569. else if (node.name == "ListItem" && node.parent.name == "OrderedList" &&
  20570. (match = /^\s*\d+([.)])\s*/.exec(nodeStart$1(node, doc)))) {
  20571. let len = match[1].length >= 4 ? match[0].length - match[1].length + 1 : match[0].length;
  20572. markup.push({ from: pos, string: line.slice(pos, pos + len).replace(/\S/g, " "), node });
  20573. pos += len;
  20574. }
  20575. else if (node.name == "ListItem" && node.parent.name == "BulletList" &&
  20576. (match = /^\s*[-+*] (\s*)/.exec(nodeStart$1(node, doc)))) {
  20577. let len = match[1].length >= 4 ? match[0].length - match[1].length : match[0].length;
  20578. markup.push({ from: pos, string: line.slice(pos, pos + len).replace(/\S/g, " "), node });
  20579. pos += len;
  20580. }
  20581. }
  20582. return markup;
  20583. }
  20584. function renumberList(after, doc, changes) {
  20585. for (let prev = -1, node = after;;) {
  20586. if (node.name == "ListItem") {
  20587. let m = /^(\s*)(\d+)(?=[.)])/.exec(doc.sliceString(node.from, node.from + 10));
  20588. if (!m)
  20589. return;
  20590. let number = +m[2];
  20591. if (prev >= 0) {
  20592. if (number != prev + 1)
  20593. return;
  20594. changes.push({ from: node.from + m[1].length, to: node.from + m[0].length, insert: String(prev + 2) });
  20595. }
  20596. prev = number;
  20597. }
  20598. let next = node.nextSibling;
  20599. if (!next)
  20600. break;
  20601. node = next;
  20602. }
  20603. }
  20604. /// This command, when invoked in Markdown context with cursor
  20605. /// selection(s), will create a new line with the markup for
  20606. /// blockquotes and lists that were active on the old line. If the
  20607. /// cursor was directly after the end of the markup for the old line,
  20608. /// trailing whitespace and list markers are removed from that line.
  20609. ///
  20610. /// The command does nothing in non-Markdown context, so it should
  20611. /// not be used as the only binding for Enter (even in a Markdown
  20612. /// document, HTML and code regions might use a different language).
  20613. const insertNewlineContinueMarkup = ({ state, dispatch }) => {
  20614. let tree = syntaxTree(state);
  20615. let dont = null, changes = state.changeByRange(range => {
  20616. if (range.empty && markdownLanguage.isActiveAt(state, range.from)) {
  20617. let line = state.doc.lineAt(range.from);
  20618. let markup = gatherMarkup(tree.resolve(range.from, -1), line.text, state.doc);
  20619. let from = range.from, changes = [];
  20620. if (markup.length) {
  20621. let inner = markup[markup.length - 1], innerEnd = inner.from + inner.string.length;
  20622. if (range.from - line.from >= innerEnd && !/\S/.test(line.text.slice(innerEnd, range.from - line.from))) {
  20623. let start = /List/.test(inner.node.name) ? inner.from : innerEnd;
  20624. while (start > 0 && /\s/.test(line.text[start - 1]))
  20625. start--;
  20626. from = line.from + start;
  20627. }
  20628. if (inner.node.name == "ListItem") {
  20629. if (from < range.from && inner.node.parent.from == inner.node.from) { // First item
  20630. inner.string = "";
  20631. }
  20632. else {
  20633. inner.string = line.text.slice(inner.from, inner.from + inner.string.length);
  20634. if (inner.node.parent.name == "OrderedList" && from == range.from) {
  20635. inner.string = inner.string.replace(/\d+/, m => (+m + 1));
  20636. renumberList(inner.node, state.doc, changes);
  20637. }
  20638. }
  20639. }
  20640. }
  20641. let insert = markup.map(m => m.string).join("");
  20642. changes.push({ from, to: range.from, insert: Text.of(["", insert]) });
  20643. return { range: EditorSelection.cursor(from + 1 + insert.length), changes };
  20644. }
  20645. return dont = { range };
  20646. });
  20647. if (dont)
  20648. return false;
  20649. dispatch(state.update(changes, { scrollIntoView: true }));
  20650. return true;
  20651. };
  20652. /// This command will, when invoked in a Markdown context with the
  20653. /// cursor directly after list or blockquote markup, delete one level
  20654. /// of markup. When the markup is for a list, it will be replaced by
  20655. /// spaces on the first invocation (a further invocation will delete
  20656. /// the spaces), to make it easy to continue a list.
  20657. ///
  20658. /// When not after Markdown block markup, this command will return
  20659. /// false, so it is intended to be bound alongside other deletion
  20660. /// commands, with a higher precedence than the more generic commands.
  20661. const deleteMarkupBackward = ({ state, dispatch }) => {
  20662. let tree = syntaxTree(state);
  20663. let dont = null, changes = state.changeByRange(range => {
  20664. if (range.empty && markdownLanguage.isActiveAt(state, range.from)) {
  20665. let line = state.doc.lineAt(range.from);
  20666. let markup = gatherMarkup(tree.resolve(range.from, -1), line.text, state.doc);
  20667. if (markup.length) {
  20668. let inner = markup[markup.length - 1], innerEnd = inner.from + inner.string.length;
  20669. if (range.from > innerEnd + line.from && !/\S/.test(line.text.slice(innerEnd, range.from - line.from)))
  20670. return { range: EditorSelection.cursor(innerEnd + line.from),
  20671. changes: { from: innerEnd + line.from, to: range.from } };
  20672. if (range.from - line.from == innerEnd) {
  20673. let start = line.from + inner.from;
  20674. if (inner.node.name == "ListItem" && inner.node.parent.from < inner.node.from &&
  20675. /\S/.test(line.text.slice(inner.from, innerEnd)))
  20676. return { range, changes: { from: start, to: start + inner.string.length, insert: inner.string } };
  20677. return { range: EditorSelection.cursor(start), changes: { from: start, to: range.from } };
  20678. }
  20679. }
  20680. }
  20681. return dont = { range };
  20682. });
  20683. if (dont)
  20684. return false;
  20685. dispatch(state.update(changes, { scrollIntoView: true }));
  20686. return true;
  20687. };
  20688. /// A small keymap with Markdown-specific bindings. Binds Enter to
  20689. /// [`insertNewlineContinueMarkup`](#lang-markdown.insertNewlineContinueMarkup)
  20690. /// and Backspace to
  20691. /// [`deleteMarkupBackward`](#lang-markdown.deleteMarkupBackward).
  20692. const markdownKeymap = [
  20693. { key: "Enter", run: insertNewlineContinueMarkup },
  20694. { key: "Backspace", run: deleteMarkupBackward }
  20695. ];
  20696. /// Markdown language support.
  20697. function markdown(config = {}) {
  20698. let { codeLanguages, defaultCodeLanguage, addKeymap = true } = config;
  20699. let language = codeLanguages || defaultCodeLanguage ? markdownWithCodeLanguages(codeLanguages || [], defaultCodeLanguage)
  20700. : markdownLanguage;
  20701. return new LanguageSupport(language, addKeymap ? Prec.extend(keymap.of(markdownKeymap)) : []);
  20702. }
  20703. const chalky = "#e5c07b", coral = "#e06c75", cyan = "#56b6c2", invalid = "#ffffff", ivory = "#abb2bf", stone = "#5c6370", malibu = "#61afef", sage = "#98c379", whiskey = "#d19a66", violet = "#c678dd", background = "#282c34", selection = "#3E4451", cursor = "#528bff";
  20704. /// The editor theme styles for One Dark.
  20705. const oneDarkTheme = EditorView.theme({
  20706. $: {
  20707. color: ivory,
  20708. backgroundColor: background,
  20709. "& ::selection": { backgroundColor: selection },
  20710. caretColor: cursor
  20711. },
  20712. "$$focused $cursor": { borderLeftColor: cursor },
  20713. "$$focused $selectionBackground": { backgroundColor: selection },
  20714. $panels: { backgroundColor: background, color: ivory },
  20715. "$panels.top": { borderBottom: "2px solid black" },
  20716. "$panels.bottom": { borderTop: "2px solid black" },
  20717. $searchMatch: {
  20718. backgroundColor: "#72a1ff59",
  20719. outline: "1px solid #457dff"
  20720. },
  20721. "$searchMatch.selected": {
  20722. backgroundColor: "#6199ff2f"
  20723. },
  20724. $activeLine: { backgroundColor: "#2c313c" },
  20725. $selectionMatch: { backgroundColor: "#aafe661a" },
  20726. "$matchingBracket, $nonmatchingBracket": {
  20727. backgroundColor: "#bad0f847",
  20728. outline: "1px solid #515a6b"
  20729. },
  20730. $gutters: {
  20731. backgroundColor: background,
  20732. color: "#545868",
  20733. border: "none"
  20734. },
  20735. "$gutterElement.lineNumber": { color: "inherit" },
  20736. $foldPlaceholder: {
  20737. backgroundColor: "none",
  20738. border: "none",
  20739. color: "#ddd"
  20740. },
  20741. $tooltip: {
  20742. border: "1px solid #181a1f",
  20743. backgroundColor: "#606862"
  20744. },
  20745. "$tooltip.autocomplete": {
  20746. "& > ul > li[aria-selected]": {
  20747. backgroundColor: background,
  20748. color: ivory
  20749. }
  20750. }
  20751. }, { dark: true });
  20752. /// The highlighting style for code in the One Dark theme.
  20753. const oneDarkHighlightStyle = HighlightStyle.define({ tag: tags.keyword,
  20754. color: violet }, { tag: [tags.name, tags.deleted, tags.character, tags.propertyName, tags.macroName],
  20755. color: coral }, { tag: [tags.processingInstruction, tags.string, tags.inserted],
  20756. color: sage }, { tag: [tags.function(tags.variableName), tags.labelName],
  20757. color: malibu }, { tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)],
  20758. color: whiskey }, { tag: [tags.definition(tags.name), tags.separator],
  20759. color: ivory }, { tag: [tags.typeName, tags.className, tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace],
  20760. color: chalky }, { tag: [tags.operator, tags.operatorKeyword, tags.url, tags.escape, tags.regexp, tags.link, tags.special(tags.string)],
  20761. color: cyan }, { tag: [tags.meta, tags.comment],
  20762. color: stone }, { tag: tags.strong,
  20763. fontWeight: "bold" }, { tag: tags.emphasis,
  20764. fontStyle: "italic" }, { tag: tags.link,
  20765. color: stone,
  20766. textDecoration: "underline" }, { tag: tags.heading,
  20767. fontWeight: "bold",
  20768. color: coral }, { tag: [tags.atom, tags.bool, tags.special(tags.variableName)],
  20769. color: whiskey }, { tag: tags.invalid,
  20770. color: invalid });
  20771. /// Extension to enable the One Dark theme (both the editor theme and
  20772. /// the highlight style).
  20773. const oneDark = [oneDarkTheme, oneDarkHighlightStyle];
  20774. let editableTag = Symbol();
  20775. let editor = new EditorView({
  20776. state: EditorState.create({
  20777. extensions: [basicSetup, markdown(), oneDark, oneDarkHighlightStyle, tagExtension(editableTag, EditorView.editable.of(document.getElementById('submit') != null))]
  20778. }),
  20779. parent: document.querySelector("#editor")
  20780. });
  20781. const setEditorContents = (text) => {
  20782. editor.dispatch({
  20783. changes: {from: 0, to: editor.state.doc.length, insert: text}
  20784. });
  20785. };
  20786. const syncEditor = (event) => {
  20787. event.preventDefault();
  20788. const successAlert = document.querySelector('#success-alert');
  20789. const errorAlert = document.querySelector('#error-alert');
  20790. fetch('/save', {
  20791. method: 'POST',
  20792. headers: { "Content-Type": "application/json; charset=utf-8" },
  20793. body: editor.state.sliceDoc()
  20794. })
  20795. .then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
  20796. .then(response => {
  20797. // here you do what you want with response
  20798. console.log(response);
  20799. successAlert.innerHTML = response.msg;
  20800. successAlert.style.display = "block";
  20801. errorAlert.style.display = "none";
  20802. })
  20803. .catch(err => {
  20804. console.log(err);
  20805. errorAlert.innerHTML = err.msg;
  20806. errorAlert.style.display = "block";
  20807. successAlert.style.display = "none";
  20808. });
  20809. };
  20810. // If we're on the create paste page, set up the submit listener
  20811. if (document.getElementById('submit') != null) {
  20812. const submitButton = document.querySelector("#submit");
  20813. submitButton.addEventListener("click", syncEditor);
  20814. }
  20815. // If we're on the public paste display page, copy the text from the contents div and then delete it
  20816. if (document.getElementById('contents') != null) {
  20817. const contentsDiv = document.querySelector("#contents");
  20818. setEditorContents(contentsDiv.textContent);
  20819. contentsDiv.remove();
  20820. }
  20821. }());