index.js 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  1. import { Annotation, EditorSelection, codePointAt, codePointSize, fromCodePoint, Facet, combineConfig, StateEffect, StateField, Prec, Text, MapMode, RangeValue, RangeSet, CharCategory } from '@codemirror/state';
  2. import { logException, Direction, showTooltip, EditorView, ViewPlugin, getTooltip, Decoration, WidgetType, keymap } from '@codemirror/view';
  3. import { syntaxTree, indentUnit } from '@codemirror/language';
  4. /**
  5. An instance of this is passed to completion source functions.
  6. */
  7. class CompletionContext {
  8. /**
  9. Create a new completion context. (Mostly useful for testing
  10. completion sources—in the editor, the extension will create
  11. these for you.)
  12. */
  13. constructor(
  14. /**
  15. The editor state that the completion happens in.
  16. */
  17. state,
  18. /**
  19. The position at which the completion is happening.
  20. */
  21. pos,
  22. /**
  23. Indicates whether completion was activated explicitly, or
  24. implicitly by typing. The usual way to respond to this is to
  25. only return completions when either there is part of a
  26. completable entity before the cursor, or `explicit` is true.
  27. */
  28. explicit) {
  29. this.state = state;
  30. this.pos = pos;
  31. this.explicit = explicit;
  32. /**
  33. @internal
  34. */
  35. this.abortListeners = [];
  36. }
  37. /**
  38. Get the extent, content, and (if there is a token) type of the
  39. token before `this.pos`.
  40. */
  41. tokenBefore(types) {
  42. let token = syntaxTree(this.state).resolveInner(this.pos, -1);
  43. while (token && types.indexOf(token.name) < 0)
  44. token = token.parent;
  45. return token ? { from: token.from, to: this.pos,
  46. text: this.state.sliceDoc(token.from, this.pos),
  47. type: token.type } : null;
  48. }
  49. /**
  50. Get the match of the given expression directly before the
  51. cursor.
  52. */
  53. matchBefore(expr) {
  54. let line = this.state.doc.lineAt(this.pos);
  55. let start = Math.max(line.from, this.pos - 250);
  56. let str = line.text.slice(start - line.from, this.pos - line.from);
  57. let found = str.search(ensureAnchor(expr, false));
  58. return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };
  59. }
  60. /**
  61. Yields true when the query has been aborted. Can be useful in
  62. asynchronous queries to avoid doing work that will be ignored.
  63. */
  64. get aborted() { return this.abortListeners == null; }
  65. /**
  66. Allows you to register abort handlers, which will be called when
  67. the query is
  68. [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
  69. */
  70. addEventListener(type, listener) {
  71. if (type == "abort" && this.abortListeners)
  72. this.abortListeners.push(listener);
  73. }
  74. }
  75. function toSet(chars) {
  76. let flat = Object.keys(chars).join("");
  77. let words = /\w/.test(flat);
  78. if (words)
  79. flat = flat.replace(/\w/g, "");
  80. return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
  81. }
  82. function prefixMatch(options) {
  83. let first = Object.create(null), rest = Object.create(null);
  84. for (let { label } of options) {
  85. first[label[0]] = true;
  86. for (let i = 1; i < label.length; i++)
  87. rest[label[i]] = true;
  88. }
  89. let source = toSet(first) + toSet(rest) + "*$";
  90. return [new RegExp("^" + source), new RegExp(source)];
  91. }
  92. /**
  93. Given a a fixed array of options, return an autocompleter that
  94. completes them.
  95. */
  96. function completeFromList(list) {
  97. let options = list.map(o => typeof o == "string" ? { label: o } : o);
  98. let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch(options);
  99. return (context) => {
  100. let token = context.matchBefore(match);
  101. return token || context.explicit ? { from: token ? token.from : context.pos, options, validFor } : null;
  102. };
  103. }
  104. /**
  105. Wrap the given completion source so that it will only fire when the
  106. cursor is in a syntax node with one of the given names.
  107. */
  108. function ifIn(nodes, source) {
  109. return (context) => {
  110. for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent)
  111. if (nodes.indexOf(pos.name) > -1)
  112. return source(context);
  113. return null;
  114. };
  115. }
  116. /**
  117. Wrap the given completion source so that it will not fire when the
  118. cursor is in a syntax node with one of the given names.
  119. */
  120. function ifNotIn(nodes, source) {
  121. return (context) => {
  122. for (let pos = syntaxTree(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent)
  123. if (nodes.indexOf(pos.name) > -1)
  124. return null;
  125. return source(context);
  126. };
  127. }
  128. class Option {
  129. constructor(completion, source, match) {
  130. this.completion = completion;
  131. this.source = source;
  132. this.match = match;
  133. }
  134. }
  135. function cur(state) { return state.selection.main.head; }
  136. // Make sure the given regexp has a $ at its end and, if `start` is
  137. // true, a ^ at its start.
  138. function ensureAnchor(expr, start) {
  139. var _a;
  140. let { source } = expr;
  141. let addStart = start && source[0] != "^", addEnd = source[source.length - 1] != "$";
  142. if (!addStart && !addEnd)
  143. return expr;
  144. return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a = expr.flags) !== null && _a !== void 0 ? _a : (expr.ignoreCase ? "i" : ""));
  145. }
  146. /**
  147. This annotation is added to transactions that are produced by
  148. picking a completion.
  149. */
  150. const pickedCompletion = /*@__PURE__*/Annotation.define();
  151. /**
  152. Helper function that returns a transaction spec which inserts a
  153. completion's text in the main selection range, and any other
  154. selection range that has the same text in front of it.
  155. */
  156. function insertCompletionText(state, text, from, to) {
  157. return Object.assign(Object.assign({}, state.changeByRange(range => {
  158. if (range == state.selection.main)
  159. return {
  160. changes: { from: from, to: to, insert: text },
  161. range: EditorSelection.cursor(from + text.length)
  162. };
  163. let len = to - from;
  164. if (!range.empty ||
  165. len && state.sliceDoc(range.from - len, range.from) != state.sliceDoc(from, to))
  166. return { range };
  167. return {
  168. changes: { from: range.from - len, to: range.from, insert: text },
  169. range: EditorSelection.cursor(range.from - len + text.length)
  170. };
  171. })), { userEvent: "input.complete" });
  172. }
  173. function applyCompletion(view, option) {
  174. const apply = option.completion.apply || option.completion.label;
  175. let result = option.source;
  176. if (typeof apply == "string")
  177. view.dispatch(insertCompletionText(view.state, apply, result.from, result.to));
  178. else
  179. apply(view, option.completion, result.from, result.to);
  180. }
  181. const SourceCache = /*@__PURE__*/new WeakMap();
  182. function asSource(source) {
  183. if (!Array.isArray(source))
  184. return source;
  185. let known = SourceCache.get(source);
  186. if (!known)
  187. SourceCache.set(source, known = completeFromList(source));
  188. return known;
  189. }
  190. // A pattern matcher for fuzzy completion matching. Create an instance
  191. // once for a pattern, and then use that to match any number of
  192. // completions.
  193. class FuzzyMatcher {
  194. constructor(pattern) {
  195. this.pattern = pattern;
  196. this.chars = [];
  197. this.folded = [];
  198. // Buffers reused by calls to `match` to track matched character
  199. // positions.
  200. this.any = [];
  201. this.precise = [];
  202. this.byWord = [];
  203. for (let p = 0; p < pattern.length;) {
  204. let char = codePointAt(pattern, p), size = codePointSize(char);
  205. this.chars.push(char);
  206. let part = pattern.slice(p, p + size), upper = part.toUpperCase();
  207. this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
  208. p += size;
  209. }
  210. this.astral = pattern.length != this.chars.length;
  211. }
  212. // Matches a given word (completion) against the pattern (input).
  213. // Will return null for no match, and otherwise an array that starts
  214. // with the match score, followed by any number of `from, to` pairs
  215. // indicating the matched parts of `word`.
  216. //
  217. // The score is a number that is more negative the worse the match
  218. // is. See `Penalty` above.
  219. match(word) {
  220. if (this.pattern.length == 0)
  221. return [0];
  222. if (word.length < this.pattern.length)
  223. return null;
  224. let { chars, folded, any, precise, byWord } = this;
  225. // For single-character queries, only match when they occur right
  226. // at the start
  227. if (chars.length == 1) {
  228. let first = codePointAt(word, 0);
  229. return first == chars[0] ? [0, 0, codePointSize(first)]
  230. : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;
  231. }
  232. let direct = word.indexOf(this.pattern);
  233. if (direct == 0)
  234. return [0, 0, this.pattern.length];
  235. let len = chars.length, anyTo = 0;
  236. if (direct < 0) {
  237. for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {
  238. let next = codePointAt(word, i);
  239. if (next == chars[anyTo] || next == folded[anyTo])
  240. any[anyTo++] = i;
  241. i += codePointSize(next);
  242. }
  243. // No match, exit immediately
  244. if (anyTo < len)
  245. return null;
  246. }
  247. // This tracks the extent of the precise (non-folded, not
  248. // necessarily adjacent) match
  249. let preciseTo = 0;
  250. // Tracks whether there is a match that hits only characters that
  251. // appear to be starting words. `byWordFolded` is set to true when
  252. // a case folded character is encountered in such a match
  253. let byWordTo = 0, byWordFolded = false;
  254. // If we've found a partial adjacent match, these track its state
  255. let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;
  256. let hasLower = /[a-z]/.test(word), wordAdjacent = true;
  257. // Go over the option's text, scanning for the various kinds of matches
  258. for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {
  259. let next = codePointAt(word, i);
  260. if (direct < 0) {
  261. if (preciseTo < len && next == chars[preciseTo])
  262. precise[preciseTo++] = i;
  263. if (adjacentTo < len) {
  264. if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
  265. if (adjacentTo == 0)
  266. adjacentStart = i;
  267. adjacentEnd = i + 1;
  268. adjacentTo++;
  269. }
  270. else {
  271. adjacentTo = 0;
  272. }
  273. }
  274. }
  275. let ch, type = next < 0xff
  276. ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)
  277. : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);
  278. if (!i || type == 1 /* Upper */ && hasLower || prevType == 0 /* NonWord */ && type != 0 /* NonWord */) {
  279. if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))
  280. byWord[byWordTo++] = i;
  281. else if (byWord.length)
  282. wordAdjacent = false;
  283. }
  284. prevType = type;
  285. i += codePointSize(next);
  286. }
  287. if (byWordTo == len && byWord[0] == 0 && wordAdjacent)
  288. return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);
  289. if (adjacentTo == len && adjacentStart == 0)
  290. return [-200 /* CaseFold */ - word.length, 0, adjacentEnd];
  291. if (direct > -1)
  292. return [-700 /* NotStart */ - word.length, direct, direct + this.pattern.length];
  293. if (adjacentTo == len)
  294. return [-200 /* CaseFold */ + -700 /* NotStart */ - word.length, adjacentStart, adjacentEnd];
  295. if (byWordTo == len)
  296. return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */ +
  297. (wordAdjacent ? 0 : -1100 /* Gap */), byWord, word);
  298. return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);
  299. }
  300. result(score, positions, word) {
  301. let result = [score - word.length], i = 1;
  302. for (let pos of positions) {
  303. let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
  304. if (i > 1 && result[i - 1] == pos)
  305. result[i - 1] = to;
  306. else {
  307. result[i++] = pos;
  308. result[i++] = to;
  309. }
  310. }
  311. return result;
  312. }
  313. }
  314. const completionConfig = /*@__PURE__*/Facet.define({
  315. combine(configs) {
  316. return combineConfig(configs, {
  317. activateOnTyping: true,
  318. override: null,
  319. closeOnBlur: true,
  320. maxRenderedOptions: 100,
  321. defaultKeymap: true,
  322. optionClass: () => "",
  323. aboveCursor: false,
  324. icons: true,
  325. addToOptions: []
  326. }, {
  327. defaultKeymap: (a, b) => a && b,
  328. closeOnBlur: (a, b) => a && b,
  329. icons: (a, b) => a && b,
  330. optionClass: (a, b) => c => joinClass(a(c), b(c)),
  331. addToOptions: (a, b) => a.concat(b)
  332. });
  333. }
  334. });
  335. function joinClass(a, b) {
  336. return a ? b ? a + " " + b : a : b;
  337. }
  338. function optionContent(config) {
  339. let content = config.addToOptions.slice();
  340. if (config.icons)
  341. content.push({
  342. render(completion) {
  343. let icon = document.createElement("div");
  344. icon.classList.add("cm-completionIcon");
  345. if (completion.type)
  346. icon.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
  347. icon.setAttribute("aria-hidden", "true");
  348. return icon;
  349. },
  350. position: 20
  351. });
  352. content.push({
  353. render(completion, _s, match) {
  354. let labelElt = document.createElement("span");
  355. labelElt.className = "cm-completionLabel";
  356. let { label } = completion, off = 0;
  357. for (let j = 1; j < match.length;) {
  358. let from = match[j++], to = match[j++];
  359. if (from > off)
  360. labelElt.appendChild(document.createTextNode(label.slice(off, from)));
  361. let span = labelElt.appendChild(document.createElement("span"));
  362. span.appendChild(document.createTextNode(label.slice(from, to)));
  363. span.className = "cm-completionMatchedText";
  364. off = to;
  365. }
  366. if (off < label.length)
  367. labelElt.appendChild(document.createTextNode(label.slice(off)));
  368. return labelElt;
  369. },
  370. position: 50
  371. }, {
  372. render(completion) {
  373. if (!completion.detail)
  374. return null;
  375. let detailElt = document.createElement("span");
  376. detailElt.className = "cm-completionDetail";
  377. detailElt.textContent = completion.detail;
  378. return detailElt;
  379. },
  380. position: 80
  381. });
  382. return content.sort((a, b) => a.position - b.position).map(a => a.render);
  383. }
  384. function rangeAroundSelected(total, selected, max) {
  385. if (total <= max)
  386. return { from: 0, to: total };
  387. if (selected <= (total >> 1)) {
  388. let off = Math.floor(selected / max);
  389. return { from: off * max, to: (off + 1) * max };
  390. }
  391. let off = Math.floor((total - selected) / max);
  392. return { from: total - (off + 1) * max, to: total - off * max };
  393. }
  394. class CompletionTooltip {
  395. constructor(view, stateField) {
  396. this.view = view;
  397. this.stateField = stateField;
  398. this.info = null;
  399. this.placeInfo = {
  400. read: () => this.measureInfo(),
  401. write: (pos) => this.positionInfo(pos),
  402. key: this
  403. };
  404. let cState = view.state.field(stateField);
  405. let { options, selected } = cState.open;
  406. let config = view.state.facet(completionConfig);
  407. this.optionContent = optionContent(config);
  408. this.optionClass = config.optionClass;
  409. this.range = rangeAroundSelected(options.length, selected, config.maxRenderedOptions);
  410. this.dom = document.createElement("div");
  411. this.dom.className = "cm-tooltip-autocomplete";
  412. this.dom.addEventListener("mousedown", (e) => {
  413. for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) {
  414. if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options.length) {
  415. applyCompletion(view, options[+match[1]]);
  416. e.preventDefault();
  417. return;
  418. }
  419. }
  420. });
  421. this.list = this.dom.appendChild(this.createListBox(options, cState.id, this.range));
  422. this.list.addEventListener("scroll", () => {
  423. if (this.info)
  424. this.view.requestMeasure(this.placeInfo);
  425. });
  426. }
  427. mount() { this.updateSel(); }
  428. update(update) {
  429. if (update.state.field(this.stateField) != update.startState.field(this.stateField))
  430. this.updateSel();
  431. }
  432. positioned() {
  433. if (this.info)
  434. this.view.requestMeasure(this.placeInfo);
  435. }
  436. updateSel() {
  437. let cState = this.view.state.field(this.stateField), open = cState.open;
  438. if (open.selected < this.range.from || open.selected >= this.range.to) {
  439. this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
  440. this.list.remove();
  441. this.list = this.dom.appendChild(this.createListBox(open.options, cState.id, this.range));
  442. this.list.addEventListener("scroll", () => {
  443. if (this.info)
  444. this.view.requestMeasure(this.placeInfo);
  445. });
  446. }
  447. if (this.updateSelectedOption(open.selected)) {
  448. if (this.info) {
  449. this.info.remove();
  450. this.info = null;
  451. }
  452. let { completion } = open.options[open.selected];
  453. let { info } = completion;
  454. if (!info)
  455. return;
  456. let infoResult = typeof info === 'string' ? document.createTextNode(info) : info(completion);
  457. if (!infoResult)
  458. return;
  459. if ('then' in infoResult) {
  460. infoResult.then(node => {
  461. if (node && this.view.state.field(this.stateField, false) == cState)
  462. this.addInfoPane(node);
  463. }).catch(e => logException(this.view.state, e, "completion info"));
  464. }
  465. else {
  466. this.addInfoPane(infoResult);
  467. }
  468. }
  469. }
  470. addInfoPane(content) {
  471. let dom = this.info = document.createElement("div");
  472. dom.className = "cm-tooltip cm-completionInfo";
  473. dom.appendChild(content);
  474. this.dom.appendChild(dom);
  475. this.view.requestMeasure(this.placeInfo);
  476. }
  477. updateSelectedOption(selected) {
  478. let set = null;
  479. for (let opt = this.list.firstChild, i = this.range.from; opt; opt = opt.nextSibling, i++) {
  480. if (i == selected) {
  481. if (!opt.hasAttribute("aria-selected")) {
  482. opt.setAttribute("aria-selected", "true");
  483. set = opt;
  484. }
  485. }
  486. else {
  487. if (opt.hasAttribute("aria-selected"))
  488. opt.removeAttribute("aria-selected");
  489. }
  490. }
  491. if (set)
  492. scrollIntoView(this.list, set);
  493. return set;
  494. }
  495. measureInfo() {
  496. let sel = this.dom.querySelector("[aria-selected]");
  497. if (!sel || !this.info)
  498. return null;
  499. let listRect = this.dom.getBoundingClientRect();
  500. let infoRect = this.info.getBoundingClientRect();
  501. let selRect = sel.getBoundingClientRect();
  502. if (selRect.top > Math.min(innerHeight, listRect.bottom) - 10 || selRect.bottom < Math.max(0, listRect.top) + 10)
  503. return null;
  504. let top = Math.max(0, Math.min(selRect.top, innerHeight - infoRect.height)) - listRect.top;
  505. let left = this.view.textDirection == Direction.RTL;
  506. let spaceLeft = listRect.left, spaceRight = innerWidth - listRect.right;
  507. if (left && spaceLeft < Math.min(infoRect.width, spaceRight))
  508. left = false;
  509. else if (!left && spaceRight < Math.min(infoRect.width, spaceLeft))
  510. left = true;
  511. return { top, left };
  512. }
  513. positionInfo(pos) {
  514. if (this.info) {
  515. this.info.style.top = (pos ? pos.top : -1e6) + "px";
  516. if (pos) {
  517. this.info.classList.toggle("cm-completionInfo-left", pos.left);
  518. this.info.classList.toggle("cm-completionInfo-right", !pos.left);
  519. }
  520. }
  521. }
  522. createListBox(options, id, range) {
  523. const ul = document.createElement("ul");
  524. ul.id = id;
  525. ul.setAttribute("role", "listbox");
  526. ul.setAttribute("aria-expanded", "true");
  527. ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
  528. for (let i = range.from; i < range.to; i++) {
  529. let { completion, match } = options[i];
  530. const li = ul.appendChild(document.createElement("li"));
  531. li.id = id + "-" + i;
  532. li.setAttribute("role", "option");
  533. let cls = this.optionClass(completion);
  534. if (cls)
  535. li.className = cls;
  536. for (let source of this.optionContent) {
  537. let node = source(completion, this.view.state, match);
  538. if (node)
  539. li.appendChild(node);
  540. }
  541. }
  542. if (range.from)
  543. ul.classList.add("cm-completionListIncompleteTop");
  544. if (range.to < options.length)
  545. ul.classList.add("cm-completionListIncompleteBottom");
  546. return ul;
  547. }
  548. }
  549. // We allocate a new function instance every time the completion
  550. // changes to force redrawing/repositioning of the tooltip
  551. function completionTooltip(stateField) {
  552. return (view) => new CompletionTooltip(view, stateField);
  553. }
  554. function scrollIntoView(container, element) {
  555. let parent = container.getBoundingClientRect();
  556. let self = element.getBoundingClientRect();
  557. if (self.top < parent.top)
  558. container.scrollTop -= parent.top - self.top;
  559. else if (self.bottom > parent.bottom)
  560. container.scrollTop += self.bottom - parent.bottom;
  561. }
  562. // Used to pick a preferred option when two options with the same
  563. // label occur in the result.
  564. function score(option) {
  565. return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) +
  566. (option.type ? 1 : 0);
  567. }
  568. function sortOptions(active, state) {
  569. let options = [], i = 0;
  570. for (let a of active)
  571. if (a.hasResult()) {
  572. if (a.result.filter === false) {
  573. let getMatch = a.result.getMatch;
  574. for (let option of a.result.options) {
  575. let match = [1e9 - i++];
  576. if (getMatch)
  577. for (let n of getMatch(option))
  578. match.push(n);
  579. options.push(new Option(option, a, match));
  580. }
  581. }
  582. else {
  583. let matcher = new FuzzyMatcher(state.sliceDoc(a.from, a.to)), match;
  584. for (let option of a.result.options)
  585. if (match = matcher.match(option.label)) {
  586. if (option.boost != null)
  587. match[0] += option.boost;
  588. options.push(new Option(option, a, match));
  589. }
  590. }
  591. }
  592. let result = [], prev = null;
  593. for (let opt of options.sort(cmpOption)) {
  594. if (!prev || prev.label != opt.completion.label || prev.detail != opt.completion.detail ||
  595. (prev.type != null && opt.completion.type != null && prev.type != opt.completion.type) ||
  596. prev.apply != opt.completion.apply)
  597. result.push(opt);
  598. else if (score(opt.completion) > score(prev))
  599. result[result.length - 1] = opt;
  600. prev = opt.completion;
  601. }
  602. return result;
  603. }
  604. class CompletionDialog {
  605. constructor(options, attrs, tooltip, timestamp, selected) {
  606. this.options = options;
  607. this.attrs = attrs;
  608. this.tooltip = tooltip;
  609. this.timestamp = timestamp;
  610. this.selected = selected;
  611. }
  612. setSelected(selected, id) {
  613. return selected == this.selected || selected >= this.options.length ? this
  614. : new CompletionDialog(this.options, makeAttrs(id, selected), this.tooltip, this.timestamp, selected);
  615. }
  616. static build(active, state, id, prev, conf) {
  617. let options = sortOptions(active, state);
  618. if (!options.length)
  619. return null;
  620. let selected = 0;
  621. if (prev && prev.selected) {
  622. let selectedValue = prev.options[prev.selected].completion;
  623. for (let i = 0; i < options.length; i++)
  624. if (options[i].completion == selectedValue) {
  625. selected = i;
  626. break;
  627. }
  628. }
  629. return new CompletionDialog(options, makeAttrs(id, selected), {
  630. pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
  631. create: completionTooltip(completionState),
  632. above: conf.aboveCursor,
  633. }, prev ? prev.timestamp : Date.now(), selected);
  634. }
  635. map(changes) {
  636. return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), { pos: changes.mapPos(this.tooltip.pos) }), this.timestamp, this.selected);
  637. }
  638. }
  639. class CompletionState {
  640. constructor(active, id, open) {
  641. this.active = active;
  642. this.id = id;
  643. this.open = open;
  644. }
  645. static start() {
  646. return new CompletionState(none, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
  647. }
  648. update(tr) {
  649. let { state } = tr, conf = state.facet(completionConfig);
  650. let sources = conf.override ||
  651. state.languageDataAt("autocomplete", cur(state)).map(asSource);
  652. let active = sources.map(source => {
  653. let value = this.active.find(s => s.source == source) ||
  654. new ActiveSource(source, this.active.some(a => a.state != 0 /* Inactive */) ? 1 /* Pending */ : 0 /* Inactive */);
  655. return value.update(tr, conf);
  656. });
  657. if (active.length == this.active.length && active.every((a, i) => a == this.active[i]))
  658. active = this.active;
  659. let open = tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) ||
  660. !sameResults(active, this.active) ? CompletionDialog.build(active, state, this.id, this.open, conf)
  661. : this.open && tr.docChanged ? this.open.map(tr.changes) : this.open;
  662. if (!open && active.every(a => a.state != 1 /* Pending */) && active.some(a => a.hasResult()))
  663. active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0 /* Inactive */) : a);
  664. for (let effect of tr.effects)
  665. if (effect.is(setSelectedEffect))
  666. open = open && open.setSelected(effect.value, this.id);
  667. return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
  668. }
  669. get tooltip() { return this.open ? this.open.tooltip : null; }
  670. get attrs() { return this.open ? this.open.attrs : baseAttrs; }
  671. }
  672. function sameResults(a, b) {
  673. if (a == b)
  674. return true;
  675. for (let iA = 0, iB = 0;;) {
  676. while (iA < a.length && !a[iA].hasResult)
  677. iA++;
  678. while (iB < b.length && !b[iB].hasResult)
  679. iB++;
  680. let endA = iA == a.length, endB = iB == b.length;
  681. if (endA || endB)
  682. return endA == endB;
  683. if (a[iA++].result != b[iB++].result)
  684. return false;
  685. }
  686. }
  687. const baseAttrs = {
  688. "aria-autocomplete": "list"
  689. };
  690. function makeAttrs(id, selected) {
  691. return {
  692. "aria-autocomplete": "list",
  693. "aria-haspopup": "listbox",
  694. "aria-activedescendant": id + "-" + selected,
  695. "aria-controls": id
  696. };
  697. }
  698. const none = [];
  699. function cmpOption(a, b) {
  700. let dScore = b.match[0] - a.match[0];
  701. if (dScore)
  702. return dScore;
  703. return a.completion.label.localeCompare(b.completion.label);
  704. }
  705. function getUserEvent(tr) {
  706. return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
  707. }
  708. class ActiveSource {
  709. constructor(source, state, explicitPos = -1) {
  710. this.source = source;
  711. this.state = state;
  712. this.explicitPos = explicitPos;
  713. }
  714. hasResult() { return false; }
  715. update(tr, conf) {
  716. let event = getUserEvent(tr), value = this;
  717. if (event)
  718. value = value.handleUserEvent(tr, event, conf);
  719. else if (tr.docChanged)
  720. value = value.handleChange(tr);
  721. else if (tr.selection && value.state != 0 /* Inactive */)
  722. value = new ActiveSource(value.source, 0 /* Inactive */);
  723. for (let effect of tr.effects) {
  724. if (effect.is(startCompletionEffect))
  725. value = new ActiveSource(value.source, 1 /* Pending */, effect.value ? cur(tr.state) : -1);
  726. else if (effect.is(closeCompletionEffect))
  727. value = new ActiveSource(value.source, 0 /* Inactive */);
  728. else if (effect.is(setActiveEffect))
  729. for (let active of effect.value)
  730. if (active.source == value.source)
  731. value = active;
  732. }
  733. return value;
  734. }
  735. handleUserEvent(tr, type, conf) {
  736. return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1 /* Pending */);
  737. }
  738. handleChange(tr) {
  739. return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes);
  740. }
  741. map(changes) {
  742. return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));
  743. }
  744. }
  745. class ActiveResult extends ActiveSource {
  746. constructor(source, explicitPos, result, from, to) {
  747. super(source, 2 /* Result */, explicitPos);
  748. this.result = result;
  749. this.from = from;
  750. this.to = to;
  751. }
  752. hasResult() { return true; }
  753. handleUserEvent(tr, type, conf) {
  754. var _a;
  755. let from = tr.changes.mapPos(this.from), to = tr.changes.mapPos(this.to, 1);
  756. let pos = cur(tr.state);
  757. if ((this.explicitPos < 0 ? pos <= from : pos < this.from) ||
  758. pos > to ||
  759. type == "delete" && cur(tr.startState) == this.from)
  760. return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 /* Pending */ : 0 /* Inactive */);
  761. let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos), updated;
  762. if (checkValid(this.result.validFor, tr.state, from, to))
  763. return new ActiveResult(this.source, explicitPos, this.result, from, to);
  764. if (this.result.update &&
  765. (updated = this.result.update(this.result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0))))
  766. return new ActiveResult(this.source, explicitPos, updated, updated.from, (_a = updated.to) !== null && _a !== void 0 ? _a : cur(tr.state));
  767. return new ActiveSource(this.source, 1 /* Pending */, explicitPos);
  768. }
  769. handleChange(tr) {
  770. return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0 /* Inactive */) : this.map(tr.changes);
  771. }
  772. map(mapping) {
  773. return mapping.empty ? this :
  774. new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
  775. }
  776. }
  777. function checkValid(validFor, state, from, to) {
  778. if (!validFor)
  779. return false;
  780. let text = state.sliceDoc(from, to);
  781. return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
  782. }
  783. const startCompletionEffect = /*@__PURE__*/StateEffect.define();
  784. const closeCompletionEffect = /*@__PURE__*/StateEffect.define();
  785. const setActiveEffect = /*@__PURE__*/StateEffect.define({
  786. map(sources, mapping) { return sources.map(s => s.map(mapping)); }
  787. });
  788. const setSelectedEffect = /*@__PURE__*/StateEffect.define();
  789. const completionState = /*@__PURE__*/StateField.define({
  790. create() { return CompletionState.start(); },
  791. update(value, tr) { return value.update(tr); },
  792. provide: f => [
  793. showTooltip.from(f, val => val.tooltip),
  794. EditorView.contentAttributes.from(f, state => state.attrs)
  795. ]
  796. });
  797. const CompletionInteractMargin = 75;
  798. /**
  799. Returns a command that moves the completion selection forward or
  800. backward by the given amount.
  801. */
  802. function moveCompletionSelection(forward, by = "option") {
  803. return (view) => {
  804. let cState = view.state.field(completionState, false);
  805. if (!cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin)
  806. return false;
  807. let step = 1, tooltip;
  808. if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip)))
  809. step = Math.max(2, Math.floor(tooltip.dom.offsetHeight /
  810. tooltip.dom.querySelector("li").offsetHeight) - 1);
  811. let selected = cState.open.selected + step * (forward ? 1 : -1), { length } = cState.open.options;
  812. if (selected < 0)
  813. selected = by == "page" ? 0 : length - 1;
  814. else if (selected >= length)
  815. selected = by == "page" ? length - 1 : 0;
  816. view.dispatch({ effects: setSelectedEffect.of(selected) });
  817. return true;
  818. };
  819. }
  820. /**
  821. Accept the current completion.
  822. */
  823. const acceptCompletion = (view) => {
  824. let cState = view.state.field(completionState, false);
  825. if (view.state.readOnly || !cState || !cState.open || Date.now() - cState.open.timestamp < CompletionInteractMargin)
  826. return false;
  827. applyCompletion(view, cState.open.options[cState.open.selected]);
  828. return true;
  829. };
  830. /**
  831. Explicitly start autocompletion.
  832. */
  833. const startCompletion = (view) => {
  834. let cState = view.state.field(completionState, false);
  835. if (!cState)
  836. return false;
  837. view.dispatch({ effects: startCompletionEffect.of(true) });
  838. return true;
  839. };
  840. /**
  841. Close the currently active completion.
  842. */
  843. const closeCompletion = (view) => {
  844. let cState = view.state.field(completionState, false);
  845. if (!cState || !cState.active.some(a => a.state != 0 /* Inactive */))
  846. return false;
  847. view.dispatch({ effects: closeCompletionEffect.of(null) });
  848. return true;
  849. };
  850. class RunningQuery {
  851. constructor(active, context) {
  852. this.active = active;
  853. this.context = context;
  854. this.time = Date.now();
  855. this.updates = [];
  856. // Note that 'undefined' means 'not done yet', whereas 'null' means
  857. // 'query returned null'.
  858. this.done = undefined;
  859. }
  860. }
  861. const DebounceTime = 50, MaxUpdateCount = 50, MinAbortTime = 1000;
  862. const completionPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
  863. constructor(view) {
  864. this.view = view;
  865. this.debounceUpdate = -1;
  866. this.running = [];
  867. this.debounceAccept = -1;
  868. this.composing = 0 /* None */;
  869. for (let active of view.state.field(completionState).active)
  870. if (active.state == 1 /* Pending */)
  871. this.startQuery(active);
  872. }
  873. update(update) {
  874. let cState = update.state.field(completionState);
  875. if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState)
  876. return;
  877. let doesReset = update.transactions.some(tr => {
  878. return (tr.selection || tr.docChanged) && !getUserEvent(tr);
  879. });
  880. for (let i = 0; i < this.running.length; i++) {
  881. let query = this.running[i];
  882. if (doesReset ||
  883. query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
  884. for (let handler of query.context.abortListeners) {
  885. try {
  886. handler();
  887. }
  888. catch (e) {
  889. logException(this.view.state, e);
  890. }
  891. }
  892. query.context.abortListeners = null;
  893. this.running.splice(i--, 1);
  894. }
  895. else {
  896. query.updates.push(...update.transactions);
  897. }
  898. }
  899. if (this.debounceUpdate > -1)
  900. clearTimeout(this.debounceUpdate);
  901. this.debounceUpdate = cState.active.some(a => a.state == 1 /* Pending */ && !this.running.some(q => q.active.source == a.source))
  902. ? setTimeout(() => this.startUpdate(), DebounceTime) : -1;
  903. if (this.composing != 0 /* None */)
  904. for (let tr of update.transactions) {
  905. if (getUserEvent(tr) == "input")
  906. this.composing = 2 /* Changed */;
  907. else if (this.composing == 2 /* Changed */ && tr.selection)
  908. this.composing = 3 /* ChangedAndMoved */;
  909. }
  910. }
  911. startUpdate() {
  912. this.debounceUpdate = -1;
  913. let { state } = this.view, cState = state.field(completionState);
  914. for (let active of cState.active) {
  915. if (active.state == 1 /* Pending */ && !this.running.some(r => r.active.source == active.source))
  916. this.startQuery(active);
  917. }
  918. }
  919. startQuery(active) {
  920. let { state } = this.view, pos = cur(state);
  921. let context = new CompletionContext(state, pos, active.explicitPos == pos);
  922. let pending = new RunningQuery(active, context);
  923. this.running.push(pending);
  924. Promise.resolve(active.source(context)).then(result => {
  925. if (!pending.context.aborted) {
  926. pending.done = result || null;
  927. this.scheduleAccept();
  928. }
  929. }, err => {
  930. this.view.dispatch({ effects: closeCompletionEffect.of(null) });
  931. logException(this.view.state, err);
  932. });
  933. }
  934. scheduleAccept() {
  935. if (this.running.every(q => q.done !== undefined))
  936. this.accept();
  937. else if (this.debounceAccept < 0)
  938. this.debounceAccept = setTimeout(() => this.accept(), DebounceTime);
  939. }
  940. // For each finished query in this.running, try to create a result
  941. // or, if appropriate, restart the query.
  942. accept() {
  943. var _a;
  944. if (this.debounceAccept > -1)
  945. clearTimeout(this.debounceAccept);
  946. this.debounceAccept = -1;
  947. let updated = [];
  948. let conf = this.view.state.facet(completionConfig);
  949. for (let i = 0; i < this.running.length; i++) {
  950. let query = this.running[i];
  951. if (query.done === undefined)
  952. continue;
  953. this.running.splice(i--, 1);
  954. if (query.done) {
  955. let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a = query.done.to) !== null && _a !== void 0 ? _a : cur(query.updates.length ? query.updates[0].startState : this.view.state));
  956. // Replay the transactions that happened since the start of
  957. // the request and see if that preserves the result
  958. for (let tr of query.updates)
  959. active = active.update(tr, conf);
  960. if (active.hasResult()) {
  961. updated.push(active);
  962. continue;
  963. }
  964. }
  965. let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source);
  966. if (current && current.state == 1 /* Pending */) {
  967. if (query.done == null) {
  968. // Explicitly failed. Should clear the pending status if it
  969. // hasn't been re-set in the meantime.
  970. let active = new ActiveSource(query.active.source, 0 /* Inactive */);
  971. for (let tr of query.updates)
  972. active = active.update(tr, conf);
  973. if (active.state != 1 /* Pending */)
  974. updated.push(active);
  975. }
  976. else {
  977. // Cleared by subsequent transactions. Restart.
  978. this.startQuery(current);
  979. }
  980. }
  981. }
  982. if (updated.length)
  983. this.view.dispatch({ effects: setActiveEffect.of(updated) });
  984. }
  985. }, {
  986. eventHandlers: {
  987. blur() {
  988. let state = this.view.state.field(completionState, false);
  989. if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur)
  990. this.view.dispatch({ effects: closeCompletionEffect.of(null) });
  991. },
  992. compositionstart() {
  993. this.composing = 1 /* Started */;
  994. },
  995. compositionend() {
  996. if (this.composing == 3 /* ChangedAndMoved */) {
  997. // Safari fires compositionend events synchronously, possibly
  998. // from inside an update, so dispatch asynchronously to avoid reentrancy
  999. setTimeout(() => this.view.dispatch({ effects: startCompletionEffect.of(false) }), 20);
  1000. }
  1001. this.composing = 0 /* None */;
  1002. }
  1003. }
  1004. });
  1005. const baseTheme = /*@__PURE__*/EditorView.baseTheme({
  1006. ".cm-tooltip.cm-tooltip-autocomplete": {
  1007. "& > ul": {
  1008. fontFamily: "monospace",
  1009. whiteSpace: "nowrap",
  1010. overflow: "hidden auto",
  1011. maxWidth_fallback: "700px",
  1012. maxWidth: "min(700px, 95vw)",
  1013. minWidth: "250px",
  1014. maxHeight: "10em",
  1015. listStyle: "none",
  1016. margin: 0,
  1017. padding: 0,
  1018. "& > li": {
  1019. overflowX: "hidden",
  1020. textOverflow: "ellipsis",
  1021. cursor: "pointer",
  1022. padding: "1px 3px",
  1023. lineHeight: 1.2
  1024. },
  1025. }
  1026. },
  1027. "&light .cm-tooltip-autocomplete ul li[aria-selected]": {
  1028. background: "#17c",
  1029. color: "white",
  1030. },
  1031. "&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
  1032. background: "#347",
  1033. color: "white",
  1034. },
  1035. ".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
  1036. content: '"···"',
  1037. opacity: 0.5,
  1038. display: "block",
  1039. textAlign: "center"
  1040. },
  1041. ".cm-tooltip.cm-completionInfo": {
  1042. position: "absolute",
  1043. padding: "3px 9px",
  1044. width: "max-content",
  1045. maxWidth: "300px",
  1046. },
  1047. ".cm-completionInfo.cm-completionInfo-left": { right: "100%" },
  1048. ".cm-completionInfo.cm-completionInfo-right": { left: "100%" },
  1049. "&light .cm-snippetField": { backgroundColor: "#00000022" },
  1050. "&dark .cm-snippetField": { backgroundColor: "#ffffff22" },
  1051. ".cm-snippetFieldPosition": {
  1052. verticalAlign: "text-top",
  1053. width: 0,
  1054. height: "1.15em",
  1055. margin: "0 -0.7px -.7em",
  1056. borderLeft: "1.4px dotted #888"
  1057. },
  1058. ".cm-completionMatchedText": {
  1059. textDecoration: "underline"
  1060. },
  1061. ".cm-completionDetail": {
  1062. marginLeft: "0.5em",
  1063. fontStyle: "italic"
  1064. },
  1065. ".cm-completionIcon": {
  1066. fontSize: "90%",
  1067. width: ".8em",
  1068. display: "inline-block",
  1069. textAlign: "center",
  1070. paddingRight: ".6em",
  1071. opacity: "0.6"
  1072. },
  1073. ".cm-completionIcon-function, .cm-completionIcon-method": {
  1074. "&:after": { content: "'ƒ'" }
  1075. },
  1076. ".cm-completionIcon-class": {
  1077. "&:after": { content: "'○'" }
  1078. },
  1079. ".cm-completionIcon-interface": {
  1080. "&:after": { content: "'◌'" }
  1081. },
  1082. ".cm-completionIcon-variable": {
  1083. "&:after": { content: "'𝑥'" }
  1084. },
  1085. ".cm-completionIcon-constant": {
  1086. "&:after": { content: "'𝐶'" }
  1087. },
  1088. ".cm-completionIcon-type": {
  1089. "&:after": { content: "'𝑡'" }
  1090. },
  1091. ".cm-completionIcon-enum": {
  1092. "&:after": { content: "'∪'" }
  1093. },
  1094. ".cm-completionIcon-property": {
  1095. "&:after": { content: "'□'" }
  1096. },
  1097. ".cm-completionIcon-keyword": {
  1098. "&:after": { content: "'🔑\uFE0E'" } // Disable emoji rendering
  1099. },
  1100. ".cm-completionIcon-namespace": {
  1101. "&:after": { content: "'▢'" }
  1102. },
  1103. ".cm-completionIcon-text": {
  1104. "&:after": { content: "'abc'", fontSize: "50%", verticalAlign: "middle" }
  1105. }
  1106. });
  1107. class FieldPos {
  1108. constructor(field, line, from, to) {
  1109. this.field = field;
  1110. this.line = line;
  1111. this.from = from;
  1112. this.to = to;
  1113. }
  1114. }
  1115. class FieldRange {
  1116. constructor(field, from, to) {
  1117. this.field = field;
  1118. this.from = from;
  1119. this.to = to;
  1120. }
  1121. map(changes) {
  1122. let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
  1123. let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
  1124. return from == null || to == null ? null : new FieldRange(this.field, from, to);
  1125. }
  1126. }
  1127. class Snippet {
  1128. constructor(lines, fieldPositions) {
  1129. this.lines = lines;
  1130. this.fieldPositions = fieldPositions;
  1131. }
  1132. instantiate(state, pos) {
  1133. let text = [], lineStart = [pos];
  1134. let lineObj = state.doc.lineAt(pos), baseIndent = /^\s*/.exec(lineObj.text)[0];
  1135. for (let line of this.lines) {
  1136. if (text.length) {
  1137. let indent = baseIndent, tabs = /^\t*/.exec(line)[0].length;
  1138. for (let i = 0; i < tabs; i++)
  1139. indent += state.facet(indentUnit);
  1140. lineStart.push(pos + indent.length - tabs);
  1141. line = indent + line.slice(tabs);
  1142. }
  1143. text.push(line);
  1144. pos += line.length + 1;
  1145. }
  1146. let ranges = this.fieldPositions.map(pos => new FieldRange(pos.field, lineStart[pos.line] + pos.from, lineStart[pos.line] + pos.to));
  1147. return { text, ranges };
  1148. }
  1149. static parse(template) {
  1150. let fields = [];
  1151. let lines = [], positions = [], m;
  1152. for (let line of template.split(/\r\n?|\n/)) {
  1153. while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
  1154. let seq = m[1] ? +m[1] : null, name = m[2] || m[3] || "", found = -1;
  1155. for (let i = 0; i < fields.length; i++) {
  1156. if (seq != null ? fields[i].seq == seq : name ? fields[i].name == name : false)
  1157. found = i;
  1158. }
  1159. if (found < 0) {
  1160. let i = 0;
  1161. while (i < fields.length && (seq == null || (fields[i].seq != null && fields[i].seq < seq)))
  1162. i++;
  1163. fields.splice(i, 0, { seq, name });
  1164. found = i;
  1165. for (let pos of positions)
  1166. if (pos.field >= found)
  1167. pos.field++;
  1168. }
  1169. positions.push(new FieldPos(found, lines.length, m.index, m.index + name.length));
  1170. line = line.slice(0, m.index) + name + line.slice(m.index + m[0].length);
  1171. }
  1172. for (let esc; esc = /([$#])\\{/.exec(line);) {
  1173. line = line.slice(0, esc.index) + esc[1] + "{" + line.slice(esc.index + esc[0].length);
  1174. for (let pos of positions)
  1175. if (pos.line == lines.length && pos.from > esc.index) {
  1176. pos.from--;
  1177. pos.to--;
  1178. }
  1179. }
  1180. lines.push(line);
  1181. }
  1182. return new Snippet(lines, positions);
  1183. }
  1184. }
  1185. let fieldMarker = /*@__PURE__*/Decoration.widget({ widget: /*@__PURE__*/new class extends WidgetType {
  1186. toDOM() {
  1187. let span = document.createElement("span");
  1188. span.className = "cm-snippetFieldPosition";
  1189. return span;
  1190. }
  1191. ignoreEvent() { return false; }
  1192. } });
  1193. let fieldRange = /*@__PURE__*/Decoration.mark({ class: "cm-snippetField" });
  1194. class ActiveSnippet {
  1195. constructor(ranges, active) {
  1196. this.ranges = ranges;
  1197. this.active = active;
  1198. this.deco = Decoration.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
  1199. }
  1200. map(changes) {
  1201. let ranges = [];
  1202. for (let r of this.ranges) {
  1203. let mapped = r.map(changes);
  1204. if (!mapped)
  1205. return null;
  1206. ranges.push(mapped);
  1207. }
  1208. return new ActiveSnippet(ranges, this.active);
  1209. }
  1210. selectionInsideField(sel) {
  1211. return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
  1212. }
  1213. }
  1214. const setActive = /*@__PURE__*/StateEffect.define({
  1215. map(value, changes) { return value && value.map(changes); }
  1216. });
  1217. const moveToField = /*@__PURE__*/StateEffect.define();
  1218. const snippetState = /*@__PURE__*/StateField.define({
  1219. create() { return null; },
  1220. update(value, tr) {
  1221. for (let effect of tr.effects) {
  1222. if (effect.is(setActive))
  1223. return effect.value;
  1224. if (effect.is(moveToField) && value)
  1225. return new ActiveSnippet(value.ranges, effect.value);
  1226. }
  1227. if (value && tr.docChanged)
  1228. value = value.map(tr.changes);
  1229. if (value && tr.selection && !value.selectionInsideField(tr.selection))
  1230. value = null;
  1231. return value;
  1232. },
  1233. provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration.none)
  1234. });
  1235. function fieldSelection(ranges, field) {
  1236. return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
  1237. }
  1238. /**
  1239. Convert a snippet template to a function that can
  1240. [apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
  1241. using syntax like this:
  1242. "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
  1243. Each `${}` placeholder (you may also use `#{}`) indicates a field
  1244. that the user can fill in. Its name, if any, will be the default
  1245. content for the field.
  1246. When the snippet is activated by calling the returned function,
  1247. the code is inserted at the given position. Newlines in the
  1248. template are indented by the indentation of the start line, plus
  1249. one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
  1250. the newline.
  1251. On activation, (all instances of) the first field are selected.
  1252. The user can move between fields with Tab and Shift-Tab as long as
  1253. the fields are active. Moving to the last field or moving the
  1254. cursor out of the current field deactivates the fields.
  1255. The order of fields defaults to textual order, but you can add
  1256. numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
  1257. a custom order.
  1258. To include a literal `${` or `#{` in your template, put a
  1259. backslash after the dollar or hash and before the brace (`$\\{`).
  1260. This will be removed and the sequence will not be interpreted as a
  1261. placeholder.
  1262. */
  1263. function snippet(template) {
  1264. let snippet = Snippet.parse(template);
  1265. return (editor, _completion, from, to) => {
  1266. let { text, ranges } = snippet.instantiate(editor.state, from);
  1267. let spec = {
  1268. changes: { from, to, insert: Text.of(text) },
  1269. scrollIntoView: true
  1270. };
  1271. if (ranges.length)
  1272. spec.selection = fieldSelection(ranges, 0);
  1273. if (ranges.length > 1) {
  1274. let active = new ActiveSnippet(ranges, 0);
  1275. let effects = spec.effects = [setActive.of(active)];
  1276. if (editor.state.field(snippetState, false) === undefined)
  1277. effects.push(StateEffect.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme]));
  1278. }
  1279. editor.dispatch(editor.state.update(spec));
  1280. };
  1281. }
  1282. function moveField(dir) {
  1283. return ({ state, dispatch }) => {
  1284. let active = state.field(snippetState, false);
  1285. if (!active || dir < 0 && active.active == 0)
  1286. return false;
  1287. let next = active.active + dir, last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
  1288. dispatch(state.update({
  1289. selection: fieldSelection(active.ranges, next),
  1290. effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next))
  1291. }));
  1292. return true;
  1293. };
  1294. }
  1295. /**
  1296. A command that clears the active snippet, if any.
  1297. */
  1298. const clearSnippet = ({ state, dispatch }) => {
  1299. let active = state.field(snippetState, false);
  1300. if (!active)
  1301. return false;
  1302. dispatch(state.update({ effects: setActive.of(null) }));
  1303. return true;
  1304. };
  1305. /**
  1306. Move to the next snippet field, if available.
  1307. */
  1308. const nextSnippetField = /*@__PURE__*/moveField(1);
  1309. /**
  1310. Move to the previous snippet field, if available.
  1311. */
  1312. const prevSnippetField = /*@__PURE__*/moveField(-1);
  1313. const defaultSnippetKeymap = [
  1314. { key: "Tab", run: nextSnippetField, shift: prevSnippetField },
  1315. { key: "Escape", run: clearSnippet }
  1316. ];
  1317. /**
  1318. A facet that can be used to configure the key bindings used by
  1319. snippets. The default binds Tab to
  1320. [`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
  1321. [`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
  1322. to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
  1323. */
  1324. const snippetKeymap = /*@__PURE__*/Facet.define({
  1325. combine(maps) { return maps.length ? maps[0] : defaultSnippetKeymap; }
  1326. });
  1327. const addSnippetKeymap = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
  1328. /**
  1329. Create a completion from a snippet. Returns an object with the
  1330. properties from `completion`, plus an `apply` function that
  1331. applies the snippet.
  1332. */
  1333. function snippetCompletion(template, completion) {
  1334. return Object.assign(Object.assign({}, completion), { apply: snippet(template) });
  1335. }
  1336. const snippetPointerHandler = /*@__PURE__*/EditorView.domEventHandlers({
  1337. mousedown(event, view) {
  1338. let active = view.state.field(snippetState, false), pos;
  1339. if (!active || (pos = view.posAtCoords({ x: event.clientX, y: event.clientY })) == null)
  1340. return false;
  1341. let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
  1342. if (!match || match.field == active.active)
  1343. return false;
  1344. view.dispatch({
  1345. selection: fieldSelection(active.ranges, match.field),
  1346. effects: setActive.of(active.ranges.some(r => r.field > match.field) ? new ActiveSnippet(active.ranges, match.field) : null)
  1347. });
  1348. return true;
  1349. }
  1350. });
  1351. function wordRE(wordChars) {
  1352. let escaped = wordChars.replace(/[\\[.+*?(){|^$]/g, "\\$&");
  1353. try {
  1354. return new RegExp(`[\\p{Alphabetic}\\p{Number}_${escaped}]+`, "ug");
  1355. }
  1356. catch (_a) {
  1357. return new RegExp(`[\w${escaped}]`, "g");
  1358. }
  1359. }
  1360. function mapRE(re, f) {
  1361. return new RegExp(f(re.source), re.unicode ? "u" : "");
  1362. }
  1363. const wordCaches = /*@__PURE__*/Object.create(null);
  1364. function wordCache(wordChars) {
  1365. return wordCaches[wordChars] || (wordCaches[wordChars] = new WeakMap);
  1366. }
  1367. function storeWords(doc, wordRE, result, seen, ignoreAt) {
  1368. for (let lines = doc.iterLines(), pos = 0; !lines.next().done;) {
  1369. let { value } = lines, m;
  1370. wordRE.lastIndex = 0;
  1371. while (m = wordRE.exec(value)) {
  1372. if (!seen[m[0]] && pos + m.index != ignoreAt) {
  1373. result.push({ type: "text", label: m[0] });
  1374. seen[m[0]] = true;
  1375. if (result.length >= 2000 /* MaxList */)
  1376. return;
  1377. }
  1378. }
  1379. pos += value.length + 1;
  1380. }
  1381. }
  1382. function collectWords(doc, cache, wordRE, to, ignoreAt) {
  1383. let big = doc.length >= 1000 /* MinCacheLen */;
  1384. let cached = big && cache.get(doc);
  1385. if (cached)
  1386. return cached;
  1387. let result = [], seen = Object.create(null);
  1388. if (doc.children) {
  1389. let pos = 0;
  1390. for (let ch of doc.children) {
  1391. if (ch.length >= 1000 /* MinCacheLen */) {
  1392. for (let c of collectWords(ch, cache, wordRE, to - pos, ignoreAt - pos)) {
  1393. if (!seen[c.label]) {
  1394. seen[c.label] = true;
  1395. result.push(c);
  1396. }
  1397. }
  1398. }
  1399. else {
  1400. storeWords(ch, wordRE, result, seen, ignoreAt - pos);
  1401. }
  1402. pos += ch.length + 1;
  1403. }
  1404. }
  1405. else {
  1406. storeWords(doc, wordRE, result, seen, ignoreAt);
  1407. }
  1408. if (big && result.length < 2000 /* MaxList */)
  1409. cache.set(doc, result);
  1410. return result;
  1411. }
  1412. /**
  1413. A completion source that will scan the document for words (using a
  1414. [character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
  1415. return those as completions.
  1416. */
  1417. const completeAnyWord = context => {
  1418. let wordChars = context.state.languageDataAt("wordChars", context.pos).join("");
  1419. let re = wordRE(wordChars);
  1420. let token = context.matchBefore(mapRE(re, s => s + "$"));
  1421. if (!token && !context.explicit)
  1422. return null;
  1423. let from = token ? token.from : context.pos;
  1424. let options = collectWords(context.state.doc, wordCache(wordChars), re, 50000 /* Range */, from);
  1425. return { from, options, validFor: mapRE(re, s => "^" + s) };
  1426. };
  1427. const defaults = {
  1428. brackets: ["(", "[", "{", "'", '"'],
  1429. before: ")]}:;>"
  1430. };
  1431. const closeBracketEffect = /*@__PURE__*/StateEffect.define({
  1432. map(value, mapping) {
  1433. let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
  1434. return mapped == null ? undefined : mapped;
  1435. }
  1436. });
  1437. const skipBracketEffect = /*@__PURE__*/StateEffect.define({
  1438. map(value, mapping) { return mapping.mapPos(value); }
  1439. });
  1440. const closedBracket = /*@__PURE__*/new class extends RangeValue {
  1441. };
  1442. closedBracket.startSide = 1;
  1443. closedBracket.endSide = -1;
  1444. const bracketState = /*@__PURE__*/StateField.define({
  1445. create() { return RangeSet.empty; },
  1446. update(value, tr) {
  1447. if (tr.selection) {
  1448. let lineStart = tr.state.doc.lineAt(tr.selection.main.head).from;
  1449. let prevLineStart = tr.startState.doc.lineAt(tr.startState.selection.main.head).from;
  1450. if (lineStart != tr.changes.mapPos(prevLineStart, -1))
  1451. value = RangeSet.empty;
  1452. }
  1453. value = value.map(tr.changes);
  1454. for (let effect of tr.effects) {
  1455. if (effect.is(closeBracketEffect))
  1456. value = value.update({ add: [closedBracket.range(effect.value, effect.value + 1)] });
  1457. else if (effect.is(skipBracketEffect))
  1458. value = value.update({ filter: from => from != effect.value });
  1459. }
  1460. return value;
  1461. }
  1462. });
  1463. /**
  1464. Extension to enable bracket-closing behavior. When a closeable
  1465. bracket is typed, its closing bracket is immediately inserted
  1466. after the cursor. When closing a bracket directly in front of a
  1467. closing bracket inserted by the extension, the cursor moves over
  1468. that bracket.
  1469. */
  1470. function closeBrackets() {
  1471. return [inputHandler, bracketState];
  1472. }
  1473. const definedClosing = "()[]{}<>";
  1474. function closing(ch) {
  1475. for (let i = 0; i < definedClosing.length; i += 2)
  1476. if (definedClosing.charCodeAt(i) == ch)
  1477. return definedClosing.charAt(i + 1);
  1478. return fromCodePoint(ch < 128 ? ch : ch + 1);
  1479. }
  1480. function config(state, pos) {
  1481. return state.languageDataAt("closeBrackets", pos)[0] || defaults;
  1482. }
  1483. const android = typeof navigator == "object" && /*@__PURE__*//Android\b/.test(navigator.userAgent);
  1484. const inputHandler = /*@__PURE__*/EditorView.inputHandler.of((view, from, to, insert) => {
  1485. if ((android ? view.composing : view.compositionStarted) || view.state.readOnly)
  1486. return false;
  1487. let sel = view.state.selection.main;
  1488. if (insert.length > 2 || insert.length == 2 && codePointSize(codePointAt(insert, 0)) == 1 ||
  1489. from != sel.from || to != sel.to)
  1490. return false;
  1491. let tr = insertBracket(view.state, insert);
  1492. if (!tr)
  1493. return false;
  1494. view.dispatch(tr);
  1495. return true;
  1496. });
  1497. /**
  1498. Command that implements deleting a pair of matching brackets when
  1499. the cursor is between them.
  1500. */
  1501. const deleteBracketPair = ({ state, dispatch }) => {
  1502. if (state.readOnly)
  1503. return false;
  1504. let conf = config(state, state.selection.main.head);
  1505. let tokens = conf.brackets || defaults.brackets;
  1506. let dont = null, changes = state.changeByRange(range => {
  1507. if (range.empty) {
  1508. let before = prevChar(state.doc, range.head);
  1509. for (let token of tokens) {
  1510. if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0)))
  1511. return { changes: { from: range.head - token.length, to: range.head + token.length },
  1512. range: EditorSelection.cursor(range.head - token.length),
  1513. userEvent: "delete.backward" };
  1514. }
  1515. }
  1516. return { range: dont = range };
  1517. });
  1518. if (!dont)
  1519. dispatch(state.update(changes, { scrollIntoView: true }));
  1520. return !dont;
  1521. };
  1522. /**
  1523. Close-brackets related key bindings. Binds Backspace to
  1524. [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
  1525. */
  1526. const closeBracketsKeymap = [
  1527. { key: "Backspace", run: deleteBracketPair }
  1528. ];
  1529. /**
  1530. Implements the extension's behavior on text insertion. If the
  1531. given string counts as a bracket in the language around the
  1532. selection, and replacing the selection with it requires custom
  1533. behavior (inserting a closing version or skipping past a
  1534. previously-closed bracket), this function returns a transaction
  1535. representing that custom behavior. (You only need this if you want
  1536. to programmatically insert brackets—the
  1537. [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
  1538. take care of running this for user input.)
  1539. */
  1540. function insertBracket(state, bracket) {
  1541. let conf = config(state, state.selection.main.head);
  1542. let tokens = conf.brackets || defaults.brackets;
  1543. for (let tok of tokens) {
  1544. let closed = closing(codePointAt(tok, 0));
  1545. if (bracket == tok)
  1546. return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1)
  1547. : handleOpen(state, tok, closed, conf.before || defaults.before);
  1548. if (bracket == closed && closedBracketAt(state, state.selection.main.from))
  1549. return handleClose(state, tok, closed);
  1550. }
  1551. return null;
  1552. }
  1553. function closedBracketAt(state, pos) {
  1554. let found = false;
  1555. state.field(bracketState).between(0, state.doc.length, from => {
  1556. if (from == pos)
  1557. found = true;
  1558. });
  1559. return found;
  1560. }
  1561. function nextChar(doc, pos) {
  1562. let next = doc.sliceString(pos, pos + 2);
  1563. return next.slice(0, codePointSize(codePointAt(next, 0)));
  1564. }
  1565. function prevChar(doc, pos) {
  1566. let prev = doc.sliceString(pos - 2, pos);
  1567. return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
  1568. }
  1569. function handleOpen(state, open, close, closeBefore) {
  1570. let dont = null, changes = state.changeByRange(range => {
  1571. if (!range.empty)
  1572. return { changes: [{ insert: open, from: range.from }, { insert: close, from: range.to }],
  1573. effects: closeBracketEffect.of(range.to + open.length),
  1574. range: EditorSelection.range(range.anchor + open.length, range.head + open.length) };
  1575. let next = nextChar(state.doc, range.head);
  1576. if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1)
  1577. return { changes: { insert: open + close, from: range.head },
  1578. effects: closeBracketEffect.of(range.head + open.length),
  1579. range: EditorSelection.cursor(range.head + open.length) };
  1580. return { range: dont = range };
  1581. });
  1582. return dont ? null : state.update(changes, {
  1583. scrollIntoView: true,
  1584. userEvent: "input.type"
  1585. });
  1586. }
  1587. function handleClose(state, _open, close) {
  1588. let dont = null, moved = state.selection.ranges.map(range => {
  1589. if (range.empty && nextChar(state.doc, range.head) == close)
  1590. return EditorSelection.cursor(range.head + close.length);
  1591. return dont = range;
  1592. });
  1593. return dont ? null : state.update({
  1594. selection: EditorSelection.create(moved, state.selection.mainIndex),
  1595. scrollIntoView: true,
  1596. effects: state.selection.ranges.map(({ from }) => skipBracketEffect.of(from))
  1597. });
  1598. }
  1599. // Handles cases where the open and close token are the same, and
  1600. // possibly triple quotes (as in `"""abc"""`-style quoting).
  1601. function handleSame(state, token, allowTriple) {
  1602. let dont = null, changes = state.changeByRange(range => {
  1603. if (!range.empty)
  1604. return { changes: [{ insert: token, from: range.from }, { insert: token, from: range.to }],
  1605. effects: closeBracketEffect.of(range.to + token.length),
  1606. range: EditorSelection.range(range.anchor + token.length, range.head + token.length) };
  1607. let pos = range.head, next = nextChar(state.doc, pos);
  1608. if (next == token) {
  1609. if (nodeStart(state, pos)) {
  1610. return { changes: { insert: token + token, from: pos },
  1611. effects: closeBracketEffect.of(pos + token.length),
  1612. range: EditorSelection.cursor(pos + token.length) };
  1613. }
  1614. else if (closedBracketAt(state, pos)) {
  1615. let isTriple = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token;
  1616. return { range: EditorSelection.cursor(pos + token.length * (isTriple ? 3 : 1)),
  1617. effects: skipBracketEffect.of(pos) };
  1618. }
  1619. }
  1620. else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token &&
  1621. nodeStart(state, pos - 2 * token.length)) {
  1622. return { changes: { insert: token + token + token + token, from: pos },
  1623. effects: closeBracketEffect.of(pos + token.length),
  1624. range: EditorSelection.cursor(pos + token.length) };
  1625. }
  1626. else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
  1627. let prev = state.sliceDoc(pos - 1, pos);
  1628. if (prev != token && state.charCategorizer(pos)(prev) != CharCategory.Word && !probablyInString(state, pos, token))
  1629. return { changes: { insert: token + token, from: pos },
  1630. effects: closeBracketEffect.of(pos + token.length),
  1631. range: EditorSelection.cursor(pos + token.length) };
  1632. }
  1633. return { range: dont = range };
  1634. });
  1635. return dont ? null : state.update(changes, {
  1636. scrollIntoView: true,
  1637. userEvent: "input.type"
  1638. });
  1639. }
  1640. function nodeStart(state, pos) {
  1641. let tree = syntaxTree(state).resolveInner(pos + 1);
  1642. return tree.parent && tree.from == pos;
  1643. }
  1644. function probablyInString(state, pos, quoteToken) {
  1645. let node = syntaxTree(state).resolveInner(pos, -1);
  1646. for (let i = 0; i < 5; i++) {
  1647. if (state.sliceDoc(node.from, node.from + quoteToken.length) == quoteToken) {
  1648. let first = node.firstChild;
  1649. while (first && first.from == node.from && first.to - first.from > quoteToken.length) {
  1650. if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken)
  1651. return false;
  1652. first = first.firstChild;
  1653. }
  1654. return true;
  1655. }
  1656. let parent = node.to == pos && node.parent;
  1657. if (!parent)
  1658. break;
  1659. node = parent;
  1660. }
  1661. return false;
  1662. }
  1663. /**
  1664. Returns an extension that enables autocompletion.
  1665. */
  1666. function autocompletion(config = {}) {
  1667. return [
  1668. completionState,
  1669. completionConfig.of(config),
  1670. completionPlugin,
  1671. completionKeymapExt,
  1672. baseTheme
  1673. ];
  1674. }
  1675. /**
  1676. Basic keybindings for autocompletion.
  1677. - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
  1678. - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
  1679. - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
  1680. - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
  1681. - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
  1682. - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
  1683. - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
  1684. */
  1685. const completionKeymap = [
  1686. { key: "Ctrl-Space", run: startCompletion },
  1687. { key: "Escape", run: closeCompletion },
  1688. { key: "ArrowDown", run: /*@__PURE__*/moveCompletionSelection(true) },
  1689. { key: "ArrowUp", run: /*@__PURE__*/moveCompletionSelection(false) },
  1690. { key: "PageDown", run: /*@__PURE__*/moveCompletionSelection(true, "page") },
  1691. { key: "PageUp", run: /*@__PURE__*/moveCompletionSelection(false, "page") },
  1692. { key: "Enter", run: acceptCompletion }
  1693. ];
  1694. const completionKeymapExt = /*@__PURE__*/Prec.highest(/*@__PURE__*/keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
  1695. /**
  1696. Get the current completion status. When completions are available,
  1697. this will return `"active"`. When completions are pending (in the
  1698. process of being queried), this returns `"pending"`. Otherwise, it
  1699. returns `null`.
  1700. */
  1701. function completionStatus(state) {
  1702. let cState = state.field(completionState, false);
  1703. return cState && cState.active.some(a => a.state == 1 /* Pending */) ? "pending"
  1704. : cState && cState.active.some(a => a.state != 0 /* Inactive */) ? "active" : null;
  1705. }
  1706. const completionArrayCache = /*@__PURE__*/new WeakMap;
  1707. /**
  1708. Returns the available completions as an array.
  1709. */
  1710. function currentCompletions(state) {
  1711. var _a;
  1712. let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
  1713. if (!open)
  1714. return [];
  1715. let completions = completionArrayCache.get(open.options);
  1716. if (!completions)
  1717. completionArrayCache.set(open.options, completions = open.options.map(o => o.completion));
  1718. return completions;
  1719. }
  1720. /**
  1721. Return the currently selected completion, if any.
  1722. */
  1723. function selectedCompletion(state) {
  1724. var _a;
  1725. let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
  1726. return open ? open.options[open.selected].completion : null;
  1727. }
  1728. /**
  1729. Returns the currently selected position in the active completion
  1730. list, or null if no completions are active.
  1731. */
  1732. function selectedCompletionIndex(state) {
  1733. var _a;
  1734. let open = (_a = state.field(completionState, false)) === null || _a === void 0 ? void 0 : _a.open;
  1735. return open ? open.selected : null;
  1736. }
  1737. /**
  1738. Create an effect that can be attached to a transaction to change
  1739. the currently selected completion.
  1740. */
  1741. function setSelectedCompletion(index) {
  1742. return setSelectedEffect.of(index);
  1743. }
  1744. export { CompletionContext, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };