index.cjs 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var common = require('@lezer/common');
  4. var state = require('@codemirror/state');
  5. var view = require('@codemirror/view');
  6. var highlight = require('@lezer/highlight');
  7. var styleMod = require('style-mod');
  8. var _a;
  9. /**
  10. Node prop stored in a parser's top syntax node to provide the
  11. facet that stores language-specific data for that language.
  12. */
  13. const languageDataProp = new common.NodeProp();
  14. /**
  15. Helper function to define a facet (to be added to the top syntax
  16. node(s) for a language via
  17. [`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
  18. used to associate language data with the language. You
  19. probably only need this when subclassing
  20. [`Language`](https://codemirror.net/6/docs/ref/#language.Language).
  21. */
  22. function defineLanguageFacet(baseData) {
  23. return state.Facet.define({
  24. combine: baseData ? values => values.concat(baseData) : undefined
  25. });
  26. }
  27. /**
  28. A language object manages parsing and per-language
  29. [metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
  30. managed as a [Lezer](https://lezer.codemirror.net) tree. The class
  31. can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
  32. subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
  33. via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
  34. for stream parsers.
  35. */
  36. class Language {
  37. /**
  38. Construct a language object. If you need to invoke this
  39. directly, first define a data facet with
  40. [`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
  41. configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
  42. to the language's outer syntax node.
  43. */
  44. constructor(
  45. /**
  46. The [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) facet
  47. used for this language.
  48. */
  49. data, parser, extraExtensions = []) {
  50. this.data = data;
  51. // Kludge to define EditorState.tree as a debugging helper,
  52. // without the EditorState package actually knowing about
  53. // languages and lezer trees.
  54. if (!state.EditorState.prototype.hasOwnProperty("tree"))
  55. Object.defineProperty(state.EditorState.prototype, "tree", { get() { return syntaxTree(this); } });
  56. this.parser = parser;
  57. this.extension = [
  58. language.of(this),
  59. state.EditorState.languageData.of((state, pos, side) => state.facet(languageDataFacetAt(state, pos, side)))
  60. ].concat(extraExtensions);
  61. }
  62. /**
  63. Query whether this language is active at the given position.
  64. */
  65. isActiveAt(state, pos, side = -1) {
  66. return languageDataFacetAt(state, pos, side) == this.data;
  67. }
  68. /**
  69. Find the document regions that were parsed using this language.
  70. The returned regions will _include_ any nested languages rooted
  71. in this language, when those exist.
  72. */
  73. findRegions(state) {
  74. let lang = state.facet(language);
  75. if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data)
  76. return [{ from: 0, to: state.doc.length }];
  77. if (!lang || !lang.allowsNesting)
  78. return [];
  79. let result = [];
  80. let explore = (tree, from) => {
  81. if (tree.prop(languageDataProp) == this.data) {
  82. result.push({ from, to: from + tree.length });
  83. return;
  84. }
  85. let mount = tree.prop(common.NodeProp.mounted);
  86. if (mount) {
  87. if (mount.tree.prop(languageDataProp) == this.data) {
  88. if (mount.overlay)
  89. for (let r of mount.overlay)
  90. result.push({ from: r.from + from, to: r.to + from });
  91. else
  92. result.push({ from: from, to: from + tree.length });
  93. return;
  94. }
  95. else if (mount.overlay) {
  96. let size = result.length;
  97. explore(mount.tree, mount.overlay[0].from + from);
  98. if (result.length > size)
  99. return;
  100. }
  101. }
  102. for (let i = 0; i < tree.children.length; i++) {
  103. let ch = tree.children[i];
  104. if (ch instanceof common.Tree)
  105. explore(ch, tree.positions[i] + from);
  106. }
  107. };
  108. explore(syntaxTree(state), 0);
  109. return result;
  110. }
  111. /**
  112. Indicates whether this language allows nested languages. The
  113. default implementation returns true.
  114. */
  115. get allowsNesting() { return true; }
  116. }
  117. /**
  118. @internal
  119. */
  120. Language.setState = state.StateEffect.define();
  121. function languageDataFacetAt(state, pos, side) {
  122. let topLang = state.facet(language);
  123. if (!topLang)
  124. return null;
  125. let facet = topLang.data;
  126. if (topLang.allowsNesting) {
  127. for (let node = syntaxTree(state).topNode; node; node = node.enter(pos, side, common.IterMode.ExcludeBuffers))
  128. facet = node.type.prop(languageDataProp) || facet;
  129. }
  130. return facet;
  131. }
  132. /**
  133. A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
  134. [LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
  135. parsers.
  136. */
  137. class LRLanguage extends Language {
  138. constructor(data, parser) {
  139. super(data, parser);
  140. this.parser = parser;
  141. }
  142. /**
  143. Define a language from a parser.
  144. */
  145. static define(spec) {
  146. let data = defineLanguageFacet(spec.languageData);
  147. return new LRLanguage(data, spec.parser.configure({
  148. props: [languageDataProp.add(type => type.isTop ? data : undefined)]
  149. }));
  150. }
  151. /**
  152. Create a new instance of this language with a reconfigured
  153. version of its parser.
  154. */
  155. configure(options) {
  156. return new LRLanguage(this.data, this.parser.configure(options));
  157. }
  158. get allowsNesting() { return this.parser.hasWrappers(); }
  159. }
  160. /**
  161. Get the syntax tree for a state, which is the current (possibly
  162. incomplete) parse tree of the active
  163. [language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
  164. language available.
  165. */
  166. function syntaxTree(state) {
  167. let field = state.field(Language.state, false);
  168. return field ? field.tree : common.Tree.empty;
  169. }
  170. /**
  171. Try to get a parse tree that spans at least up to `upto`. The
  172. method will do at most `timeout` milliseconds of work to parse
  173. up to that point if the tree isn't already available.
  174. */
  175. function ensureSyntaxTree(state, upto, timeout = 50) {
  176. var _a;
  177. let parse = (_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context;
  178. return !parse ? null : parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null;
  179. }
  180. /**
  181. Queries whether there is a full syntax tree available up to the
  182. given document position. If there isn't, the background parse
  183. process _might_ still be working and update the tree further, but
  184. there is no guarantee of that—the parser will [stop
  185. working](https://codemirror.net/6/docs/ref/#language.syntaxParserRunning) when it has spent a
  186. certain amount of time or has moved beyond the visible viewport.
  187. Always returns false if no language has been enabled.
  188. */
  189. function syntaxTreeAvailable(state, upto = state.doc.length) {
  190. var _a;
  191. return ((_a = state.field(Language.state, false)) === null || _a === void 0 ? void 0 : _a.context.isDone(upto)) || false;
  192. }
  193. /**
  194. Move parsing forward, and update the editor state afterwards to
  195. reflect the new tree. Will work for at most `timeout`
  196. milliseconds. Returns true if the parser managed get to the given
  197. position in that time.
  198. */
  199. function forceParsing(view, upto = view.viewport.to, timeout = 100) {
  200. let success = ensureSyntaxTree(view.state, upto, timeout);
  201. if (success != syntaxTree(view.state))
  202. view.dispatch({});
  203. return !!success;
  204. }
  205. /**
  206. Tells you whether the language parser is planning to do more
  207. parsing work (in a `requestIdleCallback` pseudo-thread) or has
  208. stopped running, either because it parsed the entire document,
  209. because it spent too much time and was cut off, or because there
  210. is no language parser enabled.
  211. */
  212. function syntaxParserRunning(view) {
  213. var _a;
  214. return ((_a = view.plugin(parseWorker)) === null || _a === void 0 ? void 0 : _a.isWorking()) || false;
  215. }
  216. // Lezer-style Input object for a Text document.
  217. class DocInput {
  218. constructor(doc, length = doc.length) {
  219. this.doc = doc;
  220. this.length = length;
  221. this.cursorPos = 0;
  222. this.string = "";
  223. this.cursor = doc.iter();
  224. }
  225. syncTo(pos) {
  226. this.string = this.cursor.next(pos - this.cursorPos).value;
  227. this.cursorPos = pos + this.string.length;
  228. return this.cursorPos - this.string.length;
  229. }
  230. chunk(pos) {
  231. this.syncTo(pos);
  232. return this.string;
  233. }
  234. get lineChunks() { return true; }
  235. read(from, to) {
  236. let stringStart = this.cursorPos - this.string.length;
  237. if (from < stringStart || to >= this.cursorPos)
  238. return this.doc.sliceString(from, to);
  239. else
  240. return this.string.slice(from - stringStart, to - stringStart);
  241. }
  242. }
  243. let currentContext = null;
  244. /**
  245. A parse context provided to parsers working on the editor content.
  246. */
  247. class ParseContext {
  248. constructor(parser,
  249. /**
  250. The current editor state.
  251. */
  252. state,
  253. /**
  254. Tree fragments that can be reused by incremental re-parses.
  255. */
  256. fragments = [],
  257. /**
  258. @internal
  259. */
  260. tree,
  261. /**
  262. @internal
  263. */
  264. treeLen,
  265. /**
  266. The current editor viewport (or some overapproximation
  267. thereof). Intended to be used for opportunistically avoiding
  268. work (in which case
  269. [`skipUntilInView`](https://codemirror.net/6/docs/ref/#language.ParseContext.skipUntilInView)
  270. should be called to make sure the parser is restarted when the
  271. skipped region becomes visible).
  272. */
  273. viewport,
  274. /**
  275. @internal
  276. */
  277. skipped,
  278. /**
  279. This is where skipping parsers can register a promise that,
  280. when resolved, will schedule a new parse. It is cleared when
  281. the parse worker picks up the promise. @internal
  282. */
  283. scheduleOn) {
  284. this.parser = parser;
  285. this.state = state;
  286. this.fragments = fragments;
  287. this.tree = tree;
  288. this.treeLen = treeLen;
  289. this.viewport = viewport;
  290. this.skipped = skipped;
  291. this.scheduleOn = scheduleOn;
  292. this.parse = null;
  293. /**
  294. @internal
  295. */
  296. this.tempSkipped = [];
  297. }
  298. /**
  299. @internal
  300. */
  301. static create(parser, state, viewport) {
  302. return new ParseContext(parser, state, [], common.Tree.empty, 0, viewport, [], null);
  303. }
  304. startParse() {
  305. return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
  306. }
  307. /**
  308. @internal
  309. */
  310. work(until, upto) {
  311. if (upto != null && upto >= this.state.doc.length)
  312. upto = undefined;
  313. if (this.tree != common.Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
  314. this.takeTree();
  315. return true;
  316. }
  317. return this.withContext(() => {
  318. var _a;
  319. if (typeof until == "number") {
  320. let endTime = Date.now() + until;
  321. until = () => Date.now() > endTime;
  322. }
  323. if (!this.parse)
  324. this.parse = this.startParse();
  325. if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) &&
  326. upto < this.state.doc.length)
  327. this.parse.stopAt(upto);
  328. for (;;) {
  329. let done = this.parse.advance();
  330. if (done) {
  331. this.fragments = this.withoutTempSkipped(common.TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
  332. this.treeLen = (_a = this.parse.stoppedAt) !== null && _a !== void 0 ? _a : this.state.doc.length;
  333. this.tree = done;
  334. this.parse = null;
  335. if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length))
  336. this.parse = this.startParse();
  337. else
  338. return true;
  339. }
  340. if (until())
  341. return false;
  342. }
  343. });
  344. }
  345. /**
  346. @internal
  347. */
  348. takeTree() {
  349. let pos, tree;
  350. if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
  351. if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos)
  352. this.parse.stopAt(pos);
  353. this.withContext(() => { while (!(tree = this.parse.advance())) { } });
  354. this.treeLen = pos;
  355. this.tree = tree;
  356. this.fragments = this.withoutTempSkipped(common.TreeFragment.addTree(this.tree, this.fragments, true));
  357. this.parse = null;
  358. }
  359. }
  360. withContext(f) {
  361. let prev = currentContext;
  362. currentContext = this;
  363. try {
  364. return f();
  365. }
  366. finally {
  367. currentContext = prev;
  368. }
  369. }
  370. withoutTempSkipped(fragments) {
  371. for (let r; r = this.tempSkipped.pop();)
  372. fragments = cutFragments(fragments, r.from, r.to);
  373. return fragments;
  374. }
  375. /**
  376. @internal
  377. */
  378. changes(changes, newState) {
  379. let { fragments, tree, treeLen, viewport, skipped } = this;
  380. this.takeTree();
  381. if (!changes.empty) {
  382. let ranges = [];
  383. changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB }));
  384. fragments = common.TreeFragment.applyChanges(fragments, ranges);
  385. tree = common.Tree.empty;
  386. treeLen = 0;
  387. viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) };
  388. if (this.skipped.length) {
  389. skipped = [];
  390. for (let r of this.skipped) {
  391. let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1);
  392. if (from < to)
  393. skipped.push({ from, to });
  394. }
  395. }
  396. }
  397. return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
  398. }
  399. /**
  400. @internal
  401. */
  402. updateViewport(viewport) {
  403. if (this.viewport.from == viewport.from && this.viewport.to == viewport.to)
  404. return false;
  405. this.viewport = viewport;
  406. let startLen = this.skipped.length;
  407. for (let i = 0; i < this.skipped.length; i++) {
  408. let { from, to } = this.skipped[i];
  409. if (from < viewport.to && to > viewport.from) {
  410. this.fragments = cutFragments(this.fragments, from, to);
  411. this.skipped.splice(i--, 1);
  412. }
  413. }
  414. if (this.skipped.length >= startLen)
  415. return false;
  416. this.reset();
  417. return true;
  418. }
  419. /**
  420. @internal
  421. */
  422. reset() {
  423. if (this.parse) {
  424. this.takeTree();
  425. this.parse = null;
  426. }
  427. }
  428. /**
  429. Notify the parse scheduler that the given region was skipped
  430. because it wasn't in view, and the parse should be restarted
  431. when it comes into view.
  432. */
  433. skipUntilInView(from, to) {
  434. this.skipped.push({ from, to });
  435. }
  436. /**
  437. Returns a parser intended to be used as placeholder when
  438. asynchronously loading a nested parser. It'll skip its input and
  439. mark it as not-really-parsed, so that the next update will parse
  440. it again.
  441. When `until` is given, a reparse will be scheduled when that
  442. promise resolves.
  443. */
  444. static getSkippingParser(until) {
  445. return new class extends common.Parser {
  446. createParse(input, fragments, ranges) {
  447. let from = ranges[0].from, to = ranges[ranges.length - 1].to;
  448. let parser = {
  449. parsedPos: from,
  450. advance() {
  451. let cx = currentContext;
  452. if (cx) {
  453. for (let r of ranges)
  454. cx.tempSkipped.push(r);
  455. if (until)
  456. cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
  457. }
  458. this.parsedPos = to;
  459. return new common.Tree(common.NodeType.none, [], [], to - from);
  460. },
  461. stoppedAt: null,
  462. stopAt() { }
  463. };
  464. return parser;
  465. }
  466. };
  467. }
  468. /**
  469. @internal
  470. */
  471. isDone(upto) {
  472. upto = Math.min(upto, this.state.doc.length);
  473. let frags = this.fragments;
  474. return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
  475. }
  476. /**
  477. Get the context for the current parse, or `null` if no editor
  478. parse is in progress.
  479. */
  480. static get() { return currentContext; }
  481. }
  482. function cutFragments(fragments, from, to) {
  483. return common.TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]);
  484. }
  485. class LanguageState {
  486. constructor(
  487. // A mutable parse state that is used to preserve work done during
  488. // the lifetime of a state when moving to the next state.
  489. context) {
  490. this.context = context;
  491. this.tree = context.tree;
  492. }
  493. apply(tr) {
  494. if (!tr.docChanged && this.tree == this.context.tree)
  495. return this;
  496. let newCx = this.context.changes(tr.changes, tr.state);
  497. // If the previous parse wasn't done, go forward only up to its
  498. // end position or the end of the viewport, to avoid slowing down
  499. // state updates with parse work beyond the viewport.
  500. let upto = this.context.treeLen == tr.startState.doc.length ? undefined
  501. : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
  502. if (!newCx.work(20 /* Apply */, upto))
  503. newCx.takeTree();
  504. return new LanguageState(newCx);
  505. }
  506. static init(state) {
  507. let vpTo = Math.min(3000 /* InitViewport */, state.doc.length);
  508. let parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo });
  509. if (!parseState.work(20 /* Apply */, vpTo))
  510. parseState.takeTree();
  511. return new LanguageState(parseState);
  512. }
  513. }
  514. Language.state = state.StateField.define({
  515. create: LanguageState.init,
  516. update(value, tr) {
  517. for (let e of tr.effects)
  518. if (e.is(Language.setState))
  519. return e.value;
  520. if (tr.startState.facet(language) != tr.state.facet(language))
  521. return LanguageState.init(tr.state);
  522. return value.apply(tr);
  523. }
  524. });
  525. let requestIdle = (callback) => {
  526. let timeout = setTimeout(() => callback(), 500 /* MaxPause */);
  527. return () => clearTimeout(timeout);
  528. };
  529. if (typeof requestIdleCallback != "undefined")
  530. requestIdle = (callback) => {
  531. let idle = -1, timeout = setTimeout(() => {
  532. idle = requestIdleCallback(callback, { timeout: 500 /* MaxPause */ - 100 /* MinPause */ });
  533. }, 100 /* MinPause */);
  534. return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
  535. };
  536. const isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending)
  537. ? () => navigator.scheduling.isInputPending() : null;
  538. const parseWorker = view.ViewPlugin.fromClass(class ParseWorker {
  539. constructor(view) {
  540. this.view = view;
  541. this.working = null;
  542. this.workScheduled = 0;
  543. // End of the current time chunk
  544. this.chunkEnd = -1;
  545. // Milliseconds of budget left for this chunk
  546. this.chunkBudget = -1;
  547. this.work = this.work.bind(this);
  548. this.scheduleWork();
  549. }
  550. update(update) {
  551. let cx = this.view.state.field(Language.state).context;
  552. if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen)
  553. this.scheduleWork();
  554. if (update.docChanged) {
  555. if (this.view.hasFocus)
  556. this.chunkBudget += 50 /* ChangeBonus */;
  557. this.scheduleWork();
  558. }
  559. this.checkAsyncSchedule(cx);
  560. }
  561. scheduleWork() {
  562. if (this.working)
  563. return;
  564. let { state } = this.view, field = state.field(Language.state);
  565. if (field.tree != field.context.tree || !field.context.isDone(state.doc.length))
  566. this.working = requestIdle(this.work);
  567. }
  568. work(deadline) {
  569. this.working = null;
  570. let now = Date.now();
  571. if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) { // Start a new chunk
  572. this.chunkEnd = now + 30000 /* ChunkTime */;
  573. this.chunkBudget = 3000 /* ChunkBudget */;
  574. }
  575. if (this.chunkBudget <= 0)
  576. return; // No more budget
  577. let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state);
  578. if (field.tree == field.context.tree && field.context.isDone(vpTo + 100000 /* MaxParseAhead */))
  579. return;
  580. let endTime = Date.now() + Math.min(this.chunkBudget, 100 /* Slice */, deadline && !isInputPending ? Math.max(25 /* MinSlice */, deadline.timeRemaining() - 5) : 1e9);
  581. let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1000;
  582. let done = field.context.work(() => {
  583. return isInputPending && isInputPending() || Date.now() > endTime;
  584. }, vpTo + (viewportFirst ? 0 : 100000 /* MaxParseAhead */));
  585. this.chunkBudget -= Date.now() - now;
  586. if (done || this.chunkBudget <= 0) {
  587. field.context.takeTree();
  588. this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) });
  589. }
  590. if (this.chunkBudget > 0 && !(done && !viewportFirst))
  591. this.scheduleWork();
  592. this.checkAsyncSchedule(field.context);
  593. }
  594. checkAsyncSchedule(cx) {
  595. if (cx.scheduleOn) {
  596. this.workScheduled++;
  597. cx.scheduleOn
  598. .then(() => this.scheduleWork())
  599. .catch(err => view.logException(this.view.state, err))
  600. .then(() => this.workScheduled--);
  601. cx.scheduleOn = null;
  602. }
  603. }
  604. destroy() {
  605. if (this.working)
  606. this.working();
  607. }
  608. isWorking() {
  609. return !!(this.working || this.workScheduled > 0);
  610. }
  611. }, {
  612. eventHandlers: { focus() { this.scheduleWork(); } }
  613. });
  614. /**
  615. The facet used to associate a language with an editor state. Used
  616. by `Language` object's `extension` property (so you don't need to
  617. manually wrap your languages in this). Can be used to access the
  618. current language on a state.
  619. */
  620. const language = state.Facet.define({
  621. combine(languages) { return languages.length ? languages[0] : null; },
  622. enables: [Language.state, parseWorker]
  623. });
  624. /**
  625. This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
  626. optional set of supporting extensions. Language packages are
  627. encouraged to export a function that optionally takes a
  628. configuration object and returns a `LanguageSupport` instance, as
  629. the main way for client code to use the package.
  630. */
  631. class LanguageSupport {
  632. /**
  633. Create a language support object.
  634. */
  635. constructor(
  636. /**
  637. The language object.
  638. */
  639. language,
  640. /**
  641. An optional set of supporting extensions. When nesting a
  642. language in another language, the outer language is encouraged
  643. to include the supporting extensions for its inner languages
  644. in its own set of support extensions.
  645. */
  646. support = []) {
  647. this.language = language;
  648. this.support = support;
  649. this.extension = [language, support];
  650. }
  651. }
  652. /**
  653. Language descriptions are used to store metadata about languages
  654. and to dynamically load them. Their main role is finding the
  655. appropriate language for a filename or dynamically loading nested
  656. parsers.
  657. */
  658. class LanguageDescription {
  659. constructor(
  660. /**
  661. The name of this language.
  662. */
  663. name,
  664. /**
  665. Alternative names for the mode (lowercased, includes `this.name`).
  666. */
  667. alias,
  668. /**
  669. File extensions associated with this language.
  670. */
  671. extensions,
  672. /**
  673. Optional filename pattern that should be associated with this
  674. language.
  675. */
  676. filename, loadFunc,
  677. /**
  678. If the language has been loaded, this will hold its value.
  679. */
  680. support = undefined) {
  681. this.name = name;
  682. this.alias = alias;
  683. this.extensions = extensions;
  684. this.filename = filename;
  685. this.loadFunc = loadFunc;
  686. this.support = support;
  687. this.loading = null;
  688. }
  689. /**
  690. Start loading the the language. Will return a promise that
  691. resolves to a [`LanguageSupport`](https://codemirror.net/6/docs/ref/#language.LanguageSupport)
  692. object when the language successfully loads.
  693. */
  694. load() {
  695. return this.loading || (this.loading = this.loadFunc().then(support => this.support = support, err => { this.loading = null; throw err; }));
  696. }
  697. /**
  698. Create a language description.
  699. */
  700. static of(spec) {
  701. let { load, support } = spec;
  702. if (!load) {
  703. if (!support)
  704. throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");
  705. load = () => Promise.resolve(support);
  706. }
  707. return new LanguageDescription(spec.name, (spec.alias || []).concat(spec.name).map(s => s.toLowerCase()), spec.extensions || [], spec.filename, load, support);
  708. }
  709. /**
  710. Look for a language in the given array of descriptions that
  711. matches the filename. Will first match
  712. [`filename`](https://codemirror.net/6/docs/ref/#language.LanguageDescription.filename) patterns,
  713. and then [extensions](https://codemirror.net/6/docs/ref/#language.LanguageDescription.extensions),
  714. and return the first language that matches.
  715. */
  716. static matchFilename(descs, filename) {
  717. for (let d of descs)
  718. if (d.filename && d.filename.test(filename))
  719. return d;
  720. let ext = /\.([^.]+)$/.exec(filename);
  721. if (ext)
  722. for (let d of descs)
  723. if (d.extensions.indexOf(ext[1]) > -1)
  724. return d;
  725. return null;
  726. }
  727. /**
  728. Look for a language whose name or alias matches the the given
  729. name (case-insensitively). If `fuzzy` is true, and no direct
  730. matchs is found, this'll also search for a language whose name
  731. or alias occurs in the string (for names shorter than three
  732. characters, only when surrounded by non-word characters).
  733. */
  734. static matchLanguageName(descs, name, fuzzy = true) {
  735. name = name.toLowerCase();
  736. for (let d of descs)
  737. if (d.alias.some(a => a == name))
  738. return d;
  739. if (fuzzy)
  740. for (let d of descs)
  741. for (let a of d.alias) {
  742. let found = name.indexOf(a);
  743. if (found > -1 && (a.length > 2 || !/\w/.test(name[found - 1]) && !/\w/.test(name[found + a.length])))
  744. return d;
  745. }
  746. return null;
  747. }
  748. }
  749. /**
  750. Facet that defines a way to provide a function that computes the
  751. appropriate indentation depth at the start of a given line, or
  752. `null` to indicate no appropriate indentation could be determined.
  753. */
  754. const indentService = state.Facet.define();
  755. /**
  756. Facet for overriding the unit by which indentation happens.
  757. Should be a string consisting either entirely of spaces or
  758. entirely of tabs. When not set, this defaults to 2 spaces.
  759. */
  760. const indentUnit = state.Facet.define({
  761. combine: values => {
  762. if (!values.length)
  763. return " ";
  764. if (!/^(?: +|\t+)$/.test(values[0]))
  765. throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
  766. return values[0];
  767. }
  768. });
  769. /**
  770. Return the _column width_ of an indent unit in the state.
  771. Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
  772. facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
  773. contains tabs.
  774. */
  775. function getIndentUnit(state) {
  776. let unit = state.facet(indentUnit);
  777. return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
  778. }
  779. /**
  780. Create an indentation string that covers columns 0 to `cols`.
  781. Will use tabs for as much of the columns as possible when the
  782. [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
  783. tabs.
  784. */
  785. function indentString(state, cols) {
  786. let result = "", ts = state.tabSize;
  787. if (state.facet(indentUnit).charCodeAt(0) == 9)
  788. while (cols >= ts) {
  789. result += "\t";
  790. cols -= ts;
  791. }
  792. for (let i = 0; i < cols; i++)
  793. result += " ";
  794. return result;
  795. }
  796. /**
  797. Get the indentation at the given position. Will first consult any
  798. [indent services](https://codemirror.net/6/docs/ref/#language.indentService) that are registered,
  799. and if none of those return an indentation, this will check the
  800. syntax tree for the [indent node prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp)
  801. and use that if found. Returns a number when an indentation could
  802. be determined, and null otherwise.
  803. */
  804. function getIndentation(context, pos) {
  805. if (context instanceof state.EditorState)
  806. context = new IndentContext(context);
  807. for (let service of context.state.facet(indentService)) {
  808. let result = service(context, pos);
  809. if (result != null)
  810. return result;
  811. }
  812. let tree = syntaxTree(context.state);
  813. return tree ? syntaxIndentation(context, tree, pos) : null;
  814. }
  815. /**
  816. Create a change set that auto-indents all lines touched by the
  817. given document range.
  818. */
  819. function indentRange(state, from, to) {
  820. let updated = Object.create(null);
  821. let context = new IndentContext(state, { overrideIndentation: start => { var _a; return (_a = updated[start]) !== null && _a !== void 0 ? _a : -1; } });
  822. let changes = [];
  823. for (let pos = from; pos <= to;) {
  824. let line = state.doc.lineAt(pos);
  825. let indent = getIndentation(context, line.from);
  826. if (indent == null)
  827. continue;
  828. if (!/\S/.test(line.text))
  829. indent = 0;
  830. let cur = /^\s*/.exec(line.text)[0];
  831. let norm = indentString(state, indent);
  832. if (cur != norm) {
  833. updated[line.from] = indent;
  834. changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
  835. }
  836. pos = line.to + 1;
  837. }
  838. return state.changes(changes);
  839. }
  840. /**
  841. Indentation contexts are used when calling [indentation
  842. services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
  843. useful in indentation logic, and can selectively override the
  844. indentation reported for some lines.
  845. */
  846. class IndentContext {
  847. /**
  848. Create an indent context.
  849. */
  850. constructor(
  851. /**
  852. The editor state.
  853. */
  854. state,
  855. /**
  856. @internal
  857. */
  858. options = {}) {
  859. this.state = state;
  860. this.options = options;
  861. this.unit = getIndentUnit(state);
  862. }
  863. /**
  864. Get a description of the line at the given position, taking
  865. [simulated line
  866. breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  867. into account. If there is such a break at `pos`, the `bias`
  868. argument determines whether the part of the line line before or
  869. after the break is used.
  870. */
  871. lineAt(pos, bias = 1) {
  872. let line = this.state.doc.lineAt(pos);
  873. let { simulateBreak, simulateDoubleBreak } = this.options;
  874. if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) {
  875. if (simulateDoubleBreak && simulateBreak == pos)
  876. return { text: "", from: pos };
  877. else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos)
  878. return { text: line.text.slice(simulateBreak - line.from), from: simulateBreak };
  879. else
  880. return { text: line.text.slice(0, simulateBreak - line.from), from: line.from };
  881. }
  882. return line;
  883. }
  884. /**
  885. Get the text directly after `pos`, either the entire line
  886. or the next 100 characters, whichever is shorter.
  887. */
  888. textAfterPos(pos, bias = 1) {
  889. if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak)
  890. return "";
  891. let { text, from } = this.lineAt(pos, bias);
  892. return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
  893. }
  894. /**
  895. Find the column for the given position.
  896. */
  897. column(pos, bias = 1) {
  898. let { text, from } = this.lineAt(pos, bias);
  899. let result = this.countColumn(text, pos - from);
  900. let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
  901. if (override > -1)
  902. result += override - this.countColumn(text, text.search(/\S|$/));
  903. return result;
  904. }
  905. /**
  906. Find the column position (taking tabs into account) of the given
  907. position in the given string.
  908. */
  909. countColumn(line, pos = line.length) {
  910. return state.countColumn(line, this.state.tabSize, pos);
  911. }
  912. /**
  913. Find the indentation column of the line at the given point.
  914. */
  915. lineIndent(pos, bias = 1) {
  916. let { text, from } = this.lineAt(pos, bias);
  917. let override = this.options.overrideIndentation;
  918. if (override) {
  919. let overriden = override(from);
  920. if (overriden > -1)
  921. return overriden;
  922. }
  923. return this.countColumn(text, text.search(/\S|$/));
  924. }
  925. /**
  926. Returns the [simulated line
  927. break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
  928. for this context, if any.
  929. */
  930. get simulatedBreak() {
  931. return this.options.simulateBreak || null;
  932. }
  933. }
  934. /**
  935. A syntax tree node prop used to associate indentation strategies
  936. with node types. Such a strategy is a function from an indentation
  937. context to a column number or null, where null indicates that no
  938. definitive indentation can be determined.
  939. */
  940. const indentNodeProp = new common.NodeProp();
  941. // Compute the indentation for a given position from the syntax tree.
  942. function syntaxIndentation(cx, ast, pos) {
  943. return indentFrom(ast.resolveInner(pos).enterUnfinishedNodesBefore(pos), pos, cx);
  944. }
  945. function ignoreClosed(cx) {
  946. return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
  947. }
  948. function indentStrategy(tree) {
  949. let strategy = tree.type.prop(indentNodeProp);
  950. if (strategy)
  951. return strategy;
  952. let first = tree.firstChild, close;
  953. if (first && (close = first.type.prop(common.NodeProp.closedBy))) {
  954. let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1;
  955. return cx => delimitedStrategy(cx, true, 1, undefined, closed && !ignoreClosed(cx) ? last.from : undefined);
  956. }
  957. return tree.parent == null ? topIndent : null;
  958. }
  959. function indentFrom(node, pos, base) {
  960. for (; node; node = node.parent) {
  961. let strategy = indentStrategy(node);
  962. if (strategy)
  963. return strategy(TreeIndentContext.create(base, pos, node));
  964. }
  965. return null;
  966. }
  967. function topIndent() { return 0; }
  968. /**
  969. Objects of this type provide context information and helper
  970. methods to indentation functions registered on syntax nodes.
  971. */
  972. class TreeIndentContext extends IndentContext {
  973. constructor(base,
  974. /**
  975. The position at which indentation is being computed.
  976. */
  977. pos,
  978. /**
  979. The syntax tree node to which the indentation strategy
  980. applies.
  981. */
  982. node) {
  983. super(base.state, base.options);
  984. this.base = base;
  985. this.pos = pos;
  986. this.node = node;
  987. }
  988. /**
  989. @internal
  990. */
  991. static create(base, pos, node) {
  992. return new TreeIndentContext(base, pos, node);
  993. }
  994. /**
  995. Get the text directly after `this.pos`, either the entire line
  996. or the next 100 characters, whichever is shorter.
  997. */
  998. get textAfter() {
  999. return this.textAfterPos(this.pos);
  1000. }
  1001. /**
  1002. Get the indentation at the reference line for `this.node`, which
  1003. is the line on which it starts, unless there is a node that is
  1004. _not_ a parent of this node covering the start of that line. If
  1005. so, the line at the start of that node is tried, again skipping
  1006. on if it is covered by another such node.
  1007. */
  1008. get baseIndent() {
  1009. let line = this.state.doc.lineAt(this.node.from);
  1010. // Skip line starts that are covered by a sibling (or cousin, etc)
  1011. for (;;) {
  1012. let atBreak = this.node.resolve(line.from);
  1013. while (atBreak.parent && atBreak.parent.from == atBreak.from)
  1014. atBreak = atBreak.parent;
  1015. if (isParent(atBreak, this.node))
  1016. break;
  1017. line = this.state.doc.lineAt(atBreak.from);
  1018. }
  1019. return this.lineIndent(line.from);
  1020. }
  1021. /**
  1022. Continue looking for indentations in the node's parent nodes,
  1023. and return the result of that.
  1024. */
  1025. continue() {
  1026. let parent = this.node.parent;
  1027. return parent ? indentFrom(parent, this.pos, this.base) : 0;
  1028. }
  1029. }
  1030. function isParent(parent, of) {
  1031. for (let cur = of; cur; cur = cur.parent)
  1032. if (parent == cur)
  1033. return true;
  1034. return false;
  1035. }
  1036. // Check whether a delimited node is aligned (meaning there are
  1037. // non-skipped nodes on the same line as the opening delimiter). And
  1038. // if so, return the opening token.
  1039. function bracketedAligned(context) {
  1040. let tree = context.node;
  1041. let openToken = tree.childAfter(tree.from), last = tree.lastChild;
  1042. if (!openToken)
  1043. return null;
  1044. let sim = context.options.simulateBreak;
  1045. let openLine = context.state.doc.lineAt(openToken.from);
  1046. let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
  1047. for (let pos = openToken.to;;) {
  1048. let next = tree.childAfter(pos);
  1049. if (!next || next == last)
  1050. return null;
  1051. if (!next.type.isSkipped)
  1052. return next.from < lineEnd ? openToken : null;
  1053. pos = next.to;
  1054. }
  1055. }
  1056. /**
  1057. An indentation strategy for delimited (usually bracketed) nodes.
  1058. Will, by default, indent one unit more than the parent's base
  1059. indent unless the line starts with a closing token. When `align`
  1060. is true and there are non-skipped nodes on the node's opening
  1061. line, the content of the node will be aligned with the end of the
  1062. opening node, like this:
  1063. foo(bar,
  1064. baz)
  1065. */
  1066. function delimitedIndent({ closing, align = true, units = 1 }) {
  1067. return (context) => delimitedStrategy(context, align, units, closing);
  1068. }
  1069. function delimitedStrategy(context, align, units, closing, closedAt) {
  1070. let after = context.textAfter, space = after.match(/^\s*/)[0].length;
  1071. let closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space;
  1072. let aligned = align ? bracketedAligned(context) : null;
  1073. if (aligned)
  1074. return closed ? context.column(aligned.from) : context.column(aligned.to);
  1075. return context.baseIndent + (closed ? 0 : context.unit * units);
  1076. }
  1077. /**
  1078. An indentation strategy that aligns a node's content to its base
  1079. indentation.
  1080. */
  1081. const flatIndent = (context) => context.baseIndent;
  1082. /**
  1083. Creates an indentation strategy that, by default, indents
  1084. continued lines one unit more than the node's base indentation.
  1085. You can provide `except` to prevent indentation of lines that
  1086. match a pattern (for example `/^else\b/` in `if`/`else`
  1087. constructs), and you can change the amount of units used with the
  1088. `units` option.
  1089. */
  1090. function continuedIndent({ except, units = 1 } = {}) {
  1091. return (context) => {
  1092. let matchExcept = except && except.test(context.textAfter);
  1093. return context.baseIndent + (matchExcept ? 0 : units * context.unit);
  1094. };
  1095. }
  1096. const DontIndentBeyond = 200;
  1097. /**
  1098. Enables reindentation on input. When a language defines an
  1099. `indentOnInput` field in its [language
  1100. data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
  1101. expression, the line at the cursor will be reindented whenever new
  1102. text is typed and the input from the start of the line up to the
  1103. cursor matches that regexp.
  1104. To avoid unneccesary reindents, it is recommended to start the
  1105. regexp with `^` (usually followed by `\s*`), and end it with `$`.
  1106. For example, `/^\s*\}$/` will reindent when a closing brace is
  1107. added at the start of a line.
  1108. */
  1109. function indentOnInput() {
  1110. return state.EditorState.transactionFilter.of(tr => {
  1111. if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete"))
  1112. return tr;
  1113. let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
  1114. if (!rules.length)
  1115. return tr;
  1116. let doc = tr.newDoc, { head } = tr.newSelection.main, line = doc.lineAt(head);
  1117. if (head > line.from + DontIndentBeyond)
  1118. return tr;
  1119. let lineStart = doc.sliceString(line.from, head);
  1120. if (!rules.some(r => r.test(lineStart)))
  1121. return tr;
  1122. let { state } = tr, last = -1, changes = [];
  1123. for (let { head } of state.selection.ranges) {
  1124. let line = state.doc.lineAt(head);
  1125. if (line.from == last)
  1126. continue;
  1127. last = line.from;
  1128. let indent = getIndentation(state, line.from);
  1129. if (indent == null)
  1130. continue;
  1131. let cur = /^\s*/.exec(line.text)[0];
  1132. let norm = indentString(state, indent);
  1133. if (cur != norm)
  1134. changes.push({ from: line.from, to: line.from + cur.length, insert: norm });
  1135. }
  1136. return changes.length ? [tr, { changes, sequential: true }] : tr;
  1137. });
  1138. }
  1139. /**
  1140. A facet that registers a code folding service. When called with
  1141. the extent of a line, such a function should return a foldable
  1142. range that starts on that line (but continues beyond it), if one
  1143. can be found.
  1144. */
  1145. const foldService = state.Facet.define();
  1146. /**
  1147. This node prop is used to associate folding information with
  1148. syntax node types. Given a syntax node, it should check whether
  1149. that tree is foldable and return the range that can be collapsed
  1150. when it is.
  1151. */
  1152. const foldNodeProp = new common.NodeProp();
  1153. /**
  1154. [Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
  1155. the first and the last child of a syntax node. Useful for nodes
  1156. that start and end with delimiters.
  1157. */
  1158. function foldInside(node) {
  1159. let first = node.firstChild, last = node.lastChild;
  1160. return first && first.to < last.from ? { from: first.to, to: last.type.isError ? node.to : last.from } : null;
  1161. }
  1162. function syntaxFolding(state, start, end) {
  1163. let tree = syntaxTree(state);
  1164. if (tree.length < end)
  1165. return null;
  1166. let inner = tree.resolveInner(end);
  1167. let found = null;
  1168. for (let cur = inner; cur; cur = cur.parent) {
  1169. if (cur.to <= end || cur.from > end)
  1170. continue;
  1171. if (found && cur.from < start)
  1172. break;
  1173. let prop = cur.type.prop(foldNodeProp);
  1174. if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) {
  1175. let value = prop(cur, state);
  1176. if (value && value.from <= end && value.from >= start && value.to > end)
  1177. found = value;
  1178. }
  1179. }
  1180. return found;
  1181. }
  1182. function isUnfinished(node) {
  1183. let ch = node.lastChild;
  1184. return ch && ch.to == node.to && ch.type.isError;
  1185. }
  1186. /**
  1187. Check whether the given line is foldable. First asks any fold
  1188. services registered through
  1189. [`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
  1190. a result, tries to query the [fold node
  1191. prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
  1192. of the line.
  1193. */
  1194. function foldable(state, lineStart, lineEnd) {
  1195. for (let service of state.facet(foldService)) {
  1196. let result = service(state, lineStart, lineEnd);
  1197. if (result)
  1198. return result;
  1199. }
  1200. return syntaxFolding(state, lineStart, lineEnd);
  1201. }
  1202. function mapRange(range, mapping) {
  1203. let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1);
  1204. return from >= to ? undefined : { from, to };
  1205. }
  1206. /**
  1207. State effect that can be attached to a transaction to fold the
  1208. given range. (You probably only need this in exceptional
  1209. circumstances—usually you'll just want to let
  1210. [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
  1211. gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
  1212. */
  1213. const foldEffect = state.StateEffect.define({ map: mapRange });
  1214. /**
  1215. State effect that unfolds the given range (if it was folded).
  1216. */
  1217. const unfoldEffect = state.StateEffect.define({ map: mapRange });
  1218. function selectedLines(view) {
  1219. let lines = [];
  1220. for (let { head } of view.state.selection.ranges) {
  1221. if (lines.some(l => l.from <= head && l.to >= head))
  1222. continue;
  1223. lines.push(view.lineBlockAt(head));
  1224. }
  1225. return lines;
  1226. }
  1227. /**
  1228. The state field that stores the folded ranges (as a [decoration
  1229. set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
  1230. [`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
  1231. [`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
  1232. state.
  1233. */
  1234. const foldState = state.StateField.define({
  1235. create() {
  1236. return view.Decoration.none;
  1237. },
  1238. update(folded, tr) {
  1239. folded = folded.map(tr.changes);
  1240. for (let e of tr.effects) {
  1241. if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to))
  1242. folded = folded.update({ add: [foldWidget.range(e.value.from, e.value.to)] });
  1243. else if (e.is(unfoldEffect))
  1244. folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to,
  1245. filterFrom: e.value.from, filterTo: e.value.to });
  1246. }
  1247. // Clear folded ranges that cover the selection head
  1248. if (tr.selection) {
  1249. let onSelection = false, { head } = tr.selection.main;
  1250. folded.between(head, head, (a, b) => { if (a < head && b > head)
  1251. onSelection = true; });
  1252. if (onSelection)
  1253. folded = folded.update({
  1254. filterFrom: head,
  1255. filterTo: head,
  1256. filter: (a, b) => b <= head || a >= head
  1257. });
  1258. }
  1259. return folded;
  1260. },
  1261. provide: f => view.EditorView.decorations.from(f),
  1262. toJSON(folded, state) {
  1263. let ranges = [];
  1264. folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to); });
  1265. return ranges;
  1266. },
  1267. fromJSON(value) {
  1268. if (!Array.isArray(value) || value.length % 2)
  1269. throw new RangeError("Invalid JSON for fold state");
  1270. let ranges = [];
  1271. for (let i = 0; i < value.length;) {
  1272. let from = value[i++], to = value[i++];
  1273. if (typeof from != "number" || typeof to != "number")
  1274. throw new RangeError("Invalid JSON for fold state");
  1275. ranges.push(foldWidget.range(from, to));
  1276. }
  1277. return view.Decoration.set(ranges, true);
  1278. }
  1279. });
  1280. /**
  1281. Get a [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) containing the folded ranges
  1282. in the given state.
  1283. */
  1284. function foldedRanges(state$1) {
  1285. return state$1.field(foldState, false) || state.RangeSet.empty;
  1286. }
  1287. function findFold(state, from, to) {
  1288. var _a;
  1289. let found = null;
  1290. (_a = state.field(foldState, false)) === null || _a === void 0 ? void 0 : _a.between(from, to, (from, to) => {
  1291. if (!found || found.from > from)
  1292. found = { from, to };
  1293. });
  1294. return found;
  1295. }
  1296. function foldExists(folded, from, to) {
  1297. let found = false;
  1298. folded.between(from, from, (a, b) => { if (a == from && b == to)
  1299. found = true; });
  1300. return found;
  1301. }
  1302. function maybeEnable(state$1, other) {
  1303. return state$1.field(foldState, false) ? other : other.concat(state.StateEffect.appendConfig.of(codeFolding()));
  1304. }
  1305. /**
  1306. Fold the lines that are selected, if possible.
  1307. */
  1308. const foldCode = view => {
  1309. for (let line of selectedLines(view)) {
  1310. let range = foldable(view.state, line.from, line.to);
  1311. if (range) {
  1312. view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) });
  1313. return true;
  1314. }
  1315. }
  1316. return false;
  1317. };
  1318. /**
  1319. Unfold folded ranges on selected lines.
  1320. */
  1321. const unfoldCode = view => {
  1322. if (!view.state.field(foldState, false))
  1323. return false;
  1324. let effects = [];
  1325. for (let line of selectedLines(view)) {
  1326. let folded = findFold(view.state, line.from, line.to);
  1327. if (folded)
  1328. effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
  1329. }
  1330. if (effects.length)
  1331. view.dispatch({ effects });
  1332. return effects.length > 0;
  1333. };
  1334. function announceFold(view$1, range, fold = true) {
  1335. let lineFrom = view$1.state.doc.lineAt(range.from).number, lineTo = view$1.state.doc.lineAt(range.to).number;
  1336. return view.EditorView.announce.of(`${view$1.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view$1.state.phrase("to")} ${lineTo}.`);
  1337. }
  1338. /**
  1339. Fold all top-level foldable ranges. Note that, in most cases,
  1340. folding information will depend on the [syntax
  1341. tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
  1342. reliably when the document hasn't been fully parsed (either
  1343. because the editor state was only just initialized, or because the
  1344. document is so big that the parser decided not to parse it
  1345. entirely).
  1346. */
  1347. const foldAll = view => {
  1348. let { state } = view, effects = [];
  1349. for (let pos = 0; pos < state.doc.length;) {
  1350. let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to);
  1351. if (range)
  1352. effects.push(foldEffect.of(range));
  1353. pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
  1354. }
  1355. if (effects.length)
  1356. view.dispatch({ effects: maybeEnable(view.state, effects) });
  1357. return !!effects.length;
  1358. };
  1359. /**
  1360. Unfold all folded code.
  1361. */
  1362. const unfoldAll = view => {
  1363. let field = view.state.field(foldState, false);
  1364. if (!field || !field.size)
  1365. return false;
  1366. let effects = [];
  1367. field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
  1368. view.dispatch({ effects });
  1369. return true;
  1370. };
  1371. /**
  1372. Default fold-related key bindings.
  1373. - Ctrl-Shift-[ (Cmd-Alt-[ on macOS): [`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode).
  1374. - Ctrl-Shift-] (Cmd-Alt-] on macOS): [`unfoldCode`](https://codemirror.net/6/docs/ref/#language.unfoldCode).
  1375. - Ctrl-Alt-[: [`foldAll`](https://codemirror.net/6/docs/ref/#language.foldAll).
  1376. - Ctrl-Alt-]: [`unfoldAll`](https://codemirror.net/6/docs/ref/#language.unfoldAll).
  1377. */
  1378. const foldKeymap = [
  1379. { key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode },
  1380. { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode },
  1381. { key: "Ctrl-Alt-[", run: foldAll },
  1382. { key: "Ctrl-Alt-]", run: unfoldAll }
  1383. ];
  1384. const defaultConfig = {
  1385. placeholderDOM: null,
  1386. placeholderText: "…"
  1387. };
  1388. const foldConfig = state.Facet.define({
  1389. combine(values) { return state.combineConfig(values, defaultConfig); }
  1390. });
  1391. /**
  1392. Create an extension that configures code folding.
  1393. */
  1394. function codeFolding(config) {
  1395. let result = [foldState, baseTheme$1];
  1396. if (config)
  1397. result.push(foldConfig.of(config));
  1398. return result;
  1399. }
  1400. const foldWidget = view.Decoration.replace({ widget: new class extends view.WidgetType {
  1401. toDOM(view) {
  1402. let { state } = view, conf = state.facet(foldConfig);
  1403. let onclick = (event) => {
  1404. let line = view.lineBlockAt(view.posAtDOM(event.target));
  1405. let folded = findFold(view.state, line.from, line.to);
  1406. if (folded)
  1407. view.dispatch({ effects: unfoldEffect.of(folded) });
  1408. event.preventDefault();
  1409. };
  1410. if (conf.placeholderDOM)
  1411. return conf.placeholderDOM(view, onclick);
  1412. let element = document.createElement("span");
  1413. element.textContent = conf.placeholderText;
  1414. element.setAttribute("aria-label", state.phrase("folded code"));
  1415. element.title = state.phrase("unfold");
  1416. element.className = "cm-foldPlaceholder";
  1417. element.onclick = onclick;
  1418. return element;
  1419. }
  1420. } });
  1421. const foldGutterDefaults = {
  1422. openText: "⌄",
  1423. closedText: "›",
  1424. markerDOM: null,
  1425. domEventHandlers: {},
  1426. foldingChanged: () => false
  1427. };
  1428. class FoldMarker extends view.GutterMarker {
  1429. constructor(config, open) {
  1430. super();
  1431. this.config = config;
  1432. this.open = open;
  1433. }
  1434. eq(other) { return this.config == other.config && this.open == other.open; }
  1435. toDOM(view) {
  1436. if (this.config.markerDOM)
  1437. return this.config.markerDOM(this.open);
  1438. let span = document.createElement("span");
  1439. span.textContent = this.open ? this.config.openText : this.config.closedText;
  1440. span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
  1441. return span;
  1442. }
  1443. }
  1444. /**
  1445. Create an extension that registers a fold gutter, which shows a
  1446. fold status indicator before foldable lines (which can be clicked
  1447. to fold or unfold the line).
  1448. */
  1449. function foldGutter(config = {}) {
  1450. let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config);
  1451. let canFold = new FoldMarker(fullConfig, true), canUnfold = new FoldMarker(fullConfig, false);
  1452. let markers = view.ViewPlugin.fromClass(class {
  1453. constructor(view) {
  1454. this.from = view.viewport.from;
  1455. this.markers = this.buildMarkers(view);
  1456. }
  1457. update(update) {
  1458. if (update.docChanged || update.viewportChanged ||
  1459. update.startState.facet(language) != update.state.facet(language) ||
  1460. update.startState.field(foldState, false) != update.state.field(foldState, false) ||
  1461. syntaxTree(update.startState) != syntaxTree(update.state) ||
  1462. fullConfig.foldingChanged(update))
  1463. this.markers = this.buildMarkers(update.view);
  1464. }
  1465. buildMarkers(view) {
  1466. let builder = new state.RangeSetBuilder();
  1467. for (let line of view.viewportLineBlocks) {
  1468. let mark = findFold(view.state, line.from, line.to) ? canUnfold
  1469. : foldable(view.state, line.from, line.to) ? canFold : null;
  1470. if (mark)
  1471. builder.add(line.from, line.from, mark);
  1472. }
  1473. return builder.finish();
  1474. }
  1475. });
  1476. let { domEventHandlers } = fullConfig;
  1477. return [
  1478. markers,
  1479. view.gutter({
  1480. class: "cm-foldGutter",
  1481. markers(view) { var _a; return ((_a = view.plugin(markers)) === null || _a === void 0 ? void 0 : _a.markers) || state.RangeSet.empty; },
  1482. initialSpacer() {
  1483. return new FoldMarker(fullConfig, false);
  1484. },
  1485. domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), { click: (view, line, event) => {
  1486. if (domEventHandlers.click && domEventHandlers.click(view, line, event))
  1487. return true;
  1488. let folded = findFold(view.state, line.from, line.to);
  1489. if (folded) {
  1490. view.dispatch({ effects: unfoldEffect.of(folded) });
  1491. return true;
  1492. }
  1493. let range = foldable(view.state, line.from, line.to);
  1494. if (range) {
  1495. view.dispatch({ effects: foldEffect.of(range) });
  1496. return true;
  1497. }
  1498. return false;
  1499. } })
  1500. }),
  1501. codeFolding()
  1502. ];
  1503. }
  1504. const baseTheme$1 = view.EditorView.baseTheme({
  1505. ".cm-foldPlaceholder": {
  1506. backgroundColor: "#eee",
  1507. border: "1px solid #ddd",
  1508. color: "#888",
  1509. borderRadius: ".2em",
  1510. margin: "0 1px",
  1511. padding: "0 1px",
  1512. cursor: "pointer"
  1513. },
  1514. ".cm-foldGutter span": {
  1515. padding: "0 1px",
  1516. cursor: "pointer"
  1517. }
  1518. });
  1519. /**
  1520. A highlight style associates CSS styles with higlighting
  1521. [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
  1522. */
  1523. class HighlightStyle {
  1524. constructor(spec, options) {
  1525. let modSpec;
  1526. function def(spec) {
  1527. let cls = styleMod.StyleModule.newName();
  1528. (modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
  1529. return cls;
  1530. }
  1531. const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : undefined;
  1532. const scopeOpt = options.scope;
  1533. this.scope = scopeOpt instanceof Language ? (type) => type.prop(languageDataProp) == scopeOpt.data
  1534. : scopeOpt ? (type) => type == scopeOpt : undefined;
  1535. this.style = highlight.tagHighlighter(spec.map(style => ({
  1536. tag: style.tag,
  1537. class: style.class || def(Object.assign({}, style, { tag: null }))
  1538. })), {
  1539. all,
  1540. }).style;
  1541. this.module = modSpec ? new styleMod.StyleModule(modSpec) : null;
  1542. this.themeType = options.themeType;
  1543. }
  1544. /**
  1545. Create a highlighter style that associates the given styles to
  1546. the given tags. The specs must be objects that hold a style tag
  1547. or array of tags in their `tag` property, and either a single
  1548. `class` property providing a static CSS class (for highlighter
  1549. that rely on external styling), or a
  1550. [`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
  1551. set of CSS properties (which define the styling for those tags).
  1552. The CSS rules created for a highlighter will be emitted in the
  1553. order of the spec's properties. That means that for elements that
  1554. have multiple tags associated with them, styles defined further
  1555. down in the list will have a higher CSS precedence than styles
  1556. defined earlier.
  1557. */
  1558. static define(specs, options) {
  1559. return new HighlightStyle(specs, options || {});
  1560. }
  1561. }
  1562. const highlighterFacet = state.Facet.define();
  1563. const fallbackHighlighter = state.Facet.define({
  1564. combine(values) { return values.length ? [values[0]] : null; }
  1565. });
  1566. function getHighlighters(state) {
  1567. let main = state.facet(highlighterFacet);
  1568. return main.length ? main : state.facet(fallbackHighlighter);
  1569. }
  1570. /**
  1571. Wrap a highlighter in an editor extension that uses it to apply
  1572. syntax highlighting to the editor content.
  1573. When multiple (non-fallback) styles are provided, the styling
  1574. applied is the union of the classes they emit.
  1575. */
  1576. function syntaxHighlighting(highlighter, options) {
  1577. let ext = [treeHighlighter], themeType;
  1578. if (highlighter instanceof HighlightStyle) {
  1579. if (highlighter.module)
  1580. ext.push(view.EditorView.styleModule.of(highlighter.module));
  1581. themeType = highlighter.themeType;
  1582. }
  1583. if (options === null || options === void 0 ? void 0 : options.fallback)
  1584. ext.push(fallbackHighlighter.of(highlighter));
  1585. else if (themeType)
  1586. ext.push(highlighterFacet.computeN([view.EditorView.darkTheme], state => {
  1587. return state.facet(view.EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
  1588. }));
  1589. else
  1590. ext.push(highlighterFacet.of(highlighter));
  1591. return ext;
  1592. }
  1593. /**
  1594. Returns the CSS classes (if any) that the highlighters active in
  1595. the state would assign to the given style
  1596. [tags](https://lezer.codemirror.net/docs/ref#highlight.Tag) and
  1597. (optional) language
  1598. [scope](https://codemirror.net/6/docs/ref/#language.HighlightStyle^define^options.scope).
  1599. */
  1600. function highlightingFor(state, tags, scope) {
  1601. let highlighters = getHighlighters(state);
  1602. let result = null;
  1603. if (highlighters)
  1604. for (let highlighter of highlighters) {
  1605. if (!highlighter.scope || scope && highlighter.scope(scope)) {
  1606. let cls = highlighter.style(tags);
  1607. if (cls)
  1608. result = result ? result + " " + cls : cls;
  1609. }
  1610. }
  1611. return result;
  1612. }
  1613. class TreeHighlighter {
  1614. constructor(view) {
  1615. this.markCache = Object.create(null);
  1616. this.tree = syntaxTree(view.state);
  1617. this.decorations = this.buildDeco(view, getHighlighters(view.state));
  1618. }
  1619. update(update) {
  1620. let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state);
  1621. let styleChange = highlighters != getHighlighters(update.startState);
  1622. if (tree.length < update.view.viewport.to && !styleChange && tree.type == this.tree.type) {
  1623. this.decorations = this.decorations.map(update.changes);
  1624. }
  1625. else if (tree != this.tree || update.viewportChanged || styleChange) {
  1626. this.tree = tree;
  1627. this.decorations = this.buildDeco(update.view, highlighters);
  1628. }
  1629. }
  1630. buildDeco(view$1, highlighters) {
  1631. if (!highlighters || !this.tree.length)
  1632. return view.Decoration.none;
  1633. let builder = new state.RangeSetBuilder();
  1634. for (let { from, to } of view$1.visibleRanges) {
  1635. highlight.highlightTree(this.tree, highlighters, (from, to, style) => {
  1636. builder.add(from, to, this.markCache[style] || (this.markCache[style] = view.Decoration.mark({ class: style })));
  1637. }, from, to);
  1638. }
  1639. return builder.finish();
  1640. }
  1641. }
  1642. const treeHighlighter = state.Prec.high(view.ViewPlugin.fromClass(TreeHighlighter, {
  1643. decorations: v => v.decorations
  1644. }));
  1645. /**
  1646. A default highlight style (works well with light themes).
  1647. */
  1648. const defaultHighlightStyle = HighlightStyle.define([
  1649. { tag: highlight.tags.meta,
  1650. color: "#7a757a" },
  1651. { tag: highlight.tags.link,
  1652. textDecoration: "underline" },
  1653. { tag: highlight.tags.heading,
  1654. textDecoration: "underline",
  1655. fontWeight: "bold" },
  1656. { tag: highlight.tags.emphasis,
  1657. fontStyle: "italic" },
  1658. { tag: highlight.tags.strong,
  1659. fontWeight: "bold" },
  1660. { tag: highlight.tags.strikethrough,
  1661. textDecoration: "line-through" },
  1662. { tag: highlight.tags.keyword,
  1663. color: "#708" },
  1664. { tag: [highlight.tags.atom, highlight.tags.bool, highlight.tags.url, highlight.tags.contentSeparator, highlight.tags.labelName],
  1665. color: "#219" },
  1666. { tag: [highlight.tags.literal, highlight.tags.inserted],
  1667. color: "#164" },
  1668. { tag: [highlight.tags.string, highlight.tags.deleted],
  1669. color: "#a11" },
  1670. { tag: [highlight.tags.regexp, highlight.tags.escape, highlight.tags.special(highlight.tags.string)],
  1671. color: "#e40" },
  1672. { tag: highlight.tags.definition(highlight.tags.variableName),
  1673. color: "#00f" },
  1674. { tag: highlight.tags.local(highlight.tags.variableName),
  1675. color: "#30a" },
  1676. { tag: [highlight.tags.typeName, highlight.tags.namespace],
  1677. color: "#085" },
  1678. { tag: highlight.tags.className,
  1679. color: "#167" },
  1680. { tag: [highlight.tags.special(highlight.tags.variableName), highlight.tags.macroName],
  1681. color: "#256" },
  1682. { tag: highlight.tags.definition(highlight.tags.propertyName),
  1683. color: "#00c" },
  1684. { tag: highlight.tags.comment,
  1685. color: "#940" },
  1686. { tag: highlight.tags.invalid,
  1687. color: "#f00" }
  1688. ]);
  1689. const baseTheme = view.EditorView.baseTheme({
  1690. "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" },
  1691. "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" }
  1692. });
  1693. const DefaultScanDist = 10000, DefaultBrackets = "()[]{}";
  1694. const bracketMatchingConfig = state.Facet.define({
  1695. combine(configs) {
  1696. return state.combineConfig(configs, {
  1697. afterCursor: true,
  1698. brackets: DefaultBrackets,
  1699. maxScanDistance: DefaultScanDist,
  1700. renderMatch: defaultRenderMatch
  1701. });
  1702. }
  1703. });
  1704. const matchingMark = view.Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = view.Decoration.mark({ class: "cm-nonmatchingBracket" });
  1705. function defaultRenderMatch(match) {
  1706. let decorations = [];
  1707. let mark = match.matched ? matchingMark : nonmatchingMark;
  1708. decorations.push(mark.range(match.start.from, match.start.to));
  1709. if (match.end)
  1710. decorations.push(mark.range(match.end.from, match.end.to));
  1711. return decorations;
  1712. }
  1713. const bracketMatchingState = state.StateField.define({
  1714. create() { return view.Decoration.none; },
  1715. update(deco, tr) {
  1716. if (!tr.docChanged && !tr.selection)
  1717. return deco;
  1718. let decorations = [];
  1719. let config = tr.state.facet(bracketMatchingConfig);
  1720. for (let range of tr.state.selection.ranges) {
  1721. if (!range.empty)
  1722. continue;
  1723. let match = matchBrackets(tr.state, range.head, -1, config)
  1724. || (range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config))
  1725. || (config.afterCursor &&
  1726. (matchBrackets(tr.state, range.head, 1, config) ||
  1727. (range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config))));
  1728. if (match)
  1729. decorations = decorations.concat(config.renderMatch(match, tr.state));
  1730. }
  1731. return view.Decoration.set(decorations, true);
  1732. },
  1733. provide: f => view.EditorView.decorations.from(f)
  1734. });
  1735. const bracketMatchingUnique = [
  1736. bracketMatchingState,
  1737. baseTheme
  1738. ];
  1739. /**
  1740. Create an extension that enables bracket matching. Whenever the
  1741. cursor is next to a bracket, that bracket and the one it matches
  1742. are highlighted. Or, when no matching bracket is found, another
  1743. highlighting style is used to indicate this.
  1744. */
  1745. function bracketMatching(config = {}) {
  1746. return [bracketMatchingConfig.of(config), bracketMatchingUnique];
  1747. }
  1748. function matchingNodes(node, dir, brackets) {
  1749. let byProp = node.prop(dir < 0 ? common.NodeProp.openedBy : common.NodeProp.closedBy);
  1750. if (byProp)
  1751. return byProp;
  1752. if (node.name.length == 1) {
  1753. let index = brackets.indexOf(node.name);
  1754. if (index > -1 && index % 2 == (dir < 0 ? 1 : 0))
  1755. return [brackets[index + dir]];
  1756. }
  1757. return null;
  1758. }
  1759. /**
  1760. Find the matching bracket for the token at `pos`, scanning
  1761. direction `dir`. Only the `brackets` and `maxScanDistance`
  1762. properties are used from `config`, if given. Returns null if no
  1763. bracket was found at `pos`, or a match result otherwise.
  1764. */
  1765. function matchBrackets(state, pos, dir, config = {}) {
  1766. let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets;
  1767. let tree = syntaxTree(state), node = tree.resolveInner(pos, dir);
  1768. for (let cur = node; cur; cur = cur.parent) {
  1769. let matches = matchingNodes(cur.type, dir, brackets);
  1770. if (matches && cur.from < cur.to)
  1771. return matchMarkedBrackets(state, pos, dir, cur, matches, brackets);
  1772. }
  1773. return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
  1774. }
  1775. function matchMarkedBrackets(_state, _pos, dir, token, matching, brackets) {
  1776. let parent = token.parent, firstToken = { from: token.from, to: token.to };
  1777. let depth = 0, cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
  1778. if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to)))
  1779. do {
  1780. if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
  1781. if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
  1782. return { start: firstToken, end: { from: cursor.from, to: cursor.to }, matched: true };
  1783. }
  1784. else if (matchingNodes(cursor.type, dir, brackets)) {
  1785. depth++;
  1786. }
  1787. else if (matchingNodes(cursor.type, -dir, brackets)) {
  1788. depth--;
  1789. if (depth == 0)
  1790. return {
  1791. start: firstToken,
  1792. end: cursor.from == cursor.to ? undefined : { from: cursor.from, to: cursor.to },
  1793. matched: false
  1794. };
  1795. }
  1796. }
  1797. } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
  1798. return { start: firstToken, matched: false };
  1799. }
  1800. function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
  1801. let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
  1802. let bracket = brackets.indexOf(startCh);
  1803. if (bracket < 0 || (bracket % 2 == 0) != (dir > 0))
  1804. return null;
  1805. let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos };
  1806. let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth = 0;
  1807. for (let distance = 0; !(iter.next()).done && distance <= maxScanDistance;) {
  1808. let text = iter.value;
  1809. if (dir < 0)
  1810. distance += text.length;
  1811. let basePos = pos + distance * dir;
  1812. for (let pos = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos != end; pos += dir) {
  1813. let found = brackets.indexOf(text[pos]);
  1814. if (found < 0 || tree.resolveInner(basePos + pos, 1).type != tokenType)
  1815. continue;
  1816. if ((found % 2 == 0) == (dir > 0)) {
  1817. depth++;
  1818. }
  1819. else if (depth == 1) { // Closing
  1820. return { start: startToken, end: { from: basePos + pos, to: basePos + pos + 1 }, matched: (found >> 1) == (bracket >> 1) };
  1821. }
  1822. else {
  1823. depth--;
  1824. }
  1825. }
  1826. if (dir > 0)
  1827. distance += text.length;
  1828. }
  1829. return iter.done ? { start: startToken, matched: false } : null;
  1830. }
  1831. // Counts the column offset in a string, taking tabs into account.
  1832. // Used mostly to find indentation.
  1833. function countCol(string, end, tabSize, startIndex = 0, startValue = 0) {
  1834. if (end == null) {
  1835. end = string.search(/[^\s\u00a0]/);
  1836. if (end == -1)
  1837. end = string.length;
  1838. }
  1839. let n = startValue;
  1840. for (let i = startIndex; i < end; i++) {
  1841. if (string.charCodeAt(i) == 9)
  1842. n += tabSize - (n % tabSize);
  1843. else
  1844. n++;
  1845. }
  1846. return n;
  1847. }
  1848. /**
  1849. Encapsulates a single line of input. Given to stream syntax code,
  1850. which uses it to tokenize the content.
  1851. */
  1852. class StringStream {
  1853. /**
  1854. Create a stream.
  1855. */
  1856. constructor(
  1857. /**
  1858. The line.
  1859. */
  1860. string, tabSize,
  1861. /**
  1862. The current indent unit size.
  1863. */
  1864. indentUnit) {
  1865. this.string = string;
  1866. this.tabSize = tabSize;
  1867. this.indentUnit = indentUnit;
  1868. /**
  1869. The current position on the line.
  1870. */
  1871. this.pos = 0;
  1872. /**
  1873. The start position of the current token.
  1874. */
  1875. this.start = 0;
  1876. this.lastColumnPos = 0;
  1877. this.lastColumnValue = 0;
  1878. }
  1879. /**
  1880. True if we are at the end of the line.
  1881. */
  1882. eol() { return this.pos >= this.string.length; }
  1883. /**
  1884. True if we are at the start of the line.
  1885. */
  1886. sol() { return this.pos == 0; }
  1887. /**
  1888. Get the next code unit after the current position, or undefined
  1889. if we're at the end of the line.
  1890. */
  1891. peek() { return this.string.charAt(this.pos) || undefined; }
  1892. /**
  1893. Read the next code unit and advance `this.pos`.
  1894. */
  1895. next() {
  1896. if (this.pos < this.string.length)
  1897. return this.string.charAt(this.pos++);
  1898. }
  1899. /**
  1900. Match the next character against the given string, regular
  1901. expression, or predicate. Consume and return it if it matches.
  1902. */
  1903. eat(match) {
  1904. let ch = this.string.charAt(this.pos);
  1905. let ok;
  1906. if (typeof match == "string")
  1907. ok = ch == match;
  1908. else
  1909. ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch));
  1910. if (ok) {
  1911. ++this.pos;
  1912. return ch;
  1913. }
  1914. }
  1915. /**
  1916. Continue matching characters that match the given string,
  1917. regular expression, or predicate function. Return true if any
  1918. characters were consumed.
  1919. */
  1920. eatWhile(match) {
  1921. let start = this.pos;
  1922. while (this.eat(match)) { }
  1923. return this.pos > start;
  1924. }
  1925. /**
  1926. Consume whitespace ahead of `this.pos`. Return true if any was
  1927. found.
  1928. */
  1929. eatSpace() {
  1930. let start = this.pos;
  1931. while (/[\s\u00a0]/.test(this.string.charAt(this.pos)))
  1932. ++this.pos;
  1933. return this.pos > start;
  1934. }
  1935. /**
  1936. Move to the end of the line.
  1937. */
  1938. skipToEnd() { this.pos = this.string.length; }
  1939. /**
  1940. Move to directly before the given character, if found on the
  1941. current line.
  1942. */
  1943. skipTo(ch) {
  1944. let found = this.string.indexOf(ch, this.pos);
  1945. if (found > -1) {
  1946. this.pos = found;
  1947. return true;
  1948. }
  1949. }
  1950. /**
  1951. Move back `n` characters.
  1952. */
  1953. backUp(n) { this.pos -= n; }
  1954. /**
  1955. Get the column position at `this.pos`.
  1956. */
  1957. column() {
  1958. if (this.lastColumnPos < this.start) {
  1959. this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  1960. this.lastColumnPos = this.start;
  1961. }
  1962. return this.lastColumnValue;
  1963. }
  1964. /**
  1965. Get the indentation column of the current line.
  1966. */
  1967. indentation() {
  1968. return countCol(this.string, null, this.tabSize);
  1969. }
  1970. /**
  1971. Match the input against the given string or regular expression
  1972. (which should start with a `^`). Return true or the regexp match
  1973. if it matches.
  1974. Unless `consume` is set to `false`, this will move `this.pos`
  1975. past the matched text.
  1976. When matching a string `caseInsensitive` can be set to true to
  1977. make the match case-insensitive.
  1978. */
  1979. match(pattern, consume, caseInsensitive) {
  1980. if (typeof pattern == "string") {
  1981. let cased = (str) => caseInsensitive ? str.toLowerCase() : str;
  1982. let substr = this.string.substr(this.pos, pattern.length);
  1983. if (cased(substr) == cased(pattern)) {
  1984. if (consume !== false)
  1985. this.pos += pattern.length;
  1986. return true;
  1987. }
  1988. else
  1989. return null;
  1990. }
  1991. else {
  1992. let match = this.string.slice(this.pos).match(pattern);
  1993. if (match && match.index > 0)
  1994. return null;
  1995. if (match && consume !== false)
  1996. this.pos += match[0].length;
  1997. return match;
  1998. }
  1999. }
  2000. /**
  2001. Get the current token.
  2002. */
  2003. current() { return this.string.slice(this.start, this.pos); }
  2004. }
  2005. function fullParser(spec) {
  2006. return {
  2007. token: spec.token,
  2008. blankLine: spec.blankLine || (() => { }),
  2009. startState: spec.startState || (() => true),
  2010. copyState: spec.copyState || defaultCopyState,
  2011. indent: spec.indent || (() => null),
  2012. languageData: spec.languageData || {},
  2013. tokenTable: spec.tokenTable || noTokens
  2014. };
  2015. }
  2016. function defaultCopyState(state) {
  2017. if (typeof state != "object")
  2018. return state;
  2019. let newState = {};
  2020. for (let prop in state) {
  2021. let val = state[prop];
  2022. newState[prop] = (val instanceof Array ? val.slice() : val);
  2023. }
  2024. return newState;
  2025. }
  2026. /**
  2027. A [language](https://codemirror.net/6/docs/ref/#language.Language) class based on a CodeMirror
  2028. 5-style [streaming parser](https://codemirror.net/6/docs/ref/#language.StreamParser).
  2029. */
  2030. class StreamLanguage extends Language {
  2031. constructor(parser) {
  2032. let data = defineLanguageFacet(parser.languageData);
  2033. let p = fullParser(parser), self;
  2034. let impl = new class extends common.Parser {
  2035. createParse(input, fragments, ranges) {
  2036. return new Parse(self, input, fragments, ranges);
  2037. }
  2038. };
  2039. super(data, impl, [indentService.of((cx, pos) => this.getIndent(cx, pos))]);
  2040. this.topNode = docID(data);
  2041. self = this;
  2042. this.streamParser = p;
  2043. this.stateAfter = new common.NodeProp({ perNode: true });
  2044. this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable;
  2045. }
  2046. /**
  2047. Define a stream language.
  2048. */
  2049. static define(spec) { return new StreamLanguage(spec); }
  2050. getIndent(cx, pos) {
  2051. let tree = syntaxTree(cx.state), at = tree.resolve(pos);
  2052. while (at && at.type != this.topNode)
  2053. at = at.parent;
  2054. if (!at)
  2055. return null;
  2056. let start = findState(this, tree, 0, at.from, pos), statePos, state;
  2057. if (start) {
  2058. state = start.state;
  2059. statePos = start.pos + 1;
  2060. }
  2061. else {
  2062. state = this.streamParser.startState(cx.unit);
  2063. statePos = 0;
  2064. }
  2065. if (pos - statePos > 10000 /* MaxIndentScanDist */)
  2066. return null;
  2067. while (statePos < pos) {
  2068. let line = cx.state.doc.lineAt(statePos), end = Math.min(pos, line.to);
  2069. if (line.length) {
  2070. let stream = new StringStream(line.text, cx.state.tabSize, cx.unit);
  2071. while (stream.pos < end - line.from)
  2072. readToken(this.streamParser.token, stream, state);
  2073. }
  2074. else {
  2075. this.streamParser.blankLine(state, cx.unit);
  2076. }
  2077. if (end == pos)
  2078. break;
  2079. statePos = line.to + 1;
  2080. }
  2081. let { text } = cx.lineAt(pos);
  2082. return this.streamParser.indent(state, /^\s*(.*)/.exec(text)[1], cx);
  2083. }
  2084. get allowsNesting() { return false; }
  2085. }
  2086. function findState(lang, tree, off, startPos, before) {
  2087. let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter);
  2088. if (state)
  2089. return { state: lang.streamParser.copyState(state), pos: off + tree.length };
  2090. for (let i = tree.children.length - 1; i >= 0; i--) {
  2091. let child = tree.children[i], pos = off + tree.positions[i];
  2092. let found = child instanceof common.Tree && pos < before && findState(lang, child, pos, startPos, before);
  2093. if (found)
  2094. return found;
  2095. }
  2096. return null;
  2097. }
  2098. function cutTree(lang, tree, from, to, inside) {
  2099. if (inside && from <= 0 && to >= tree.length)
  2100. return tree;
  2101. if (!inside && tree.type == lang.topNode)
  2102. inside = true;
  2103. for (let i = tree.children.length - 1; i >= 0; i--) {
  2104. let pos = tree.positions[i], child = tree.children[i], inner;
  2105. if (pos < to && child instanceof common.Tree) {
  2106. if (!(inner = cutTree(lang, child, from - pos, to - pos, inside)))
  2107. break;
  2108. return !inside ? inner
  2109. : new common.Tree(tree.type, tree.children.slice(0, i).concat(inner), tree.positions.slice(0, i + 1), pos + inner.length);
  2110. }
  2111. }
  2112. return null;
  2113. }
  2114. function findStartInFragments(lang, fragments, startPos, editorState) {
  2115. for (let f of fragments) {
  2116. let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0);
  2117. let found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree;
  2118. if (found && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, false)))
  2119. return { state: found.state, tree };
  2120. }
  2121. return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: common.Tree.empty };
  2122. }
  2123. class Parse {
  2124. constructor(lang, input, fragments, ranges) {
  2125. this.lang = lang;
  2126. this.input = input;
  2127. this.fragments = fragments;
  2128. this.ranges = ranges;
  2129. this.stoppedAt = null;
  2130. this.chunks = [];
  2131. this.chunkPos = [];
  2132. this.chunk = [];
  2133. this.chunkReused = undefined;
  2134. this.rangeIndex = 0;
  2135. this.to = ranges[ranges.length - 1].to;
  2136. let context = ParseContext.get(), from = ranges[0].from;
  2137. let { state, tree } = findStartInFragments(lang, fragments, from, context === null || context === void 0 ? void 0 : context.state);
  2138. this.state = state;
  2139. this.parsedPos = this.chunkStart = from + tree.length;
  2140. for (let i = 0; i < tree.children.length; i++) {
  2141. this.chunks.push(tree.children[i]);
  2142. this.chunkPos.push(tree.positions[i]);
  2143. }
  2144. if (context && this.parsedPos < context.viewport.from - 100000 /* MaxDistanceBeforeViewport */) {
  2145. this.state = this.lang.streamParser.startState(getIndentUnit(context.state));
  2146. context.skipUntilInView(this.parsedPos, context.viewport.from);
  2147. this.parsedPos = context.viewport.from;
  2148. }
  2149. this.moveRangeIndex();
  2150. }
  2151. advance() {
  2152. let context = ParseContext.get();
  2153. let parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt);
  2154. let end = Math.min(parseEnd, this.chunkStart + 2048 /* ChunkSize */);
  2155. if (context)
  2156. end = Math.min(end, context.viewport.to);
  2157. while (this.parsedPos < end)
  2158. this.parseLine(context);
  2159. if (this.chunkStart < this.parsedPos)
  2160. this.finishChunk();
  2161. if (this.parsedPos >= parseEnd)
  2162. return this.finish();
  2163. if (context && this.parsedPos >= context.viewport.to) {
  2164. context.skipUntilInView(this.parsedPos, parseEnd);
  2165. return this.finish();
  2166. }
  2167. return null;
  2168. }
  2169. stopAt(pos) {
  2170. this.stoppedAt = pos;
  2171. }
  2172. lineAfter(pos) {
  2173. let chunk = this.input.chunk(pos);
  2174. if (!this.input.lineChunks) {
  2175. let eol = chunk.indexOf("\n");
  2176. if (eol > -1)
  2177. chunk = chunk.slice(0, eol);
  2178. }
  2179. else if (chunk == "\n") {
  2180. chunk = "";
  2181. }
  2182. return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos);
  2183. }
  2184. nextLine() {
  2185. let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length;
  2186. for (let index = this.rangeIndex;;) {
  2187. let rangeEnd = this.ranges[index].to;
  2188. if (rangeEnd >= end)
  2189. break;
  2190. line = line.slice(0, rangeEnd - (end - line.length));
  2191. index++;
  2192. if (index == this.ranges.length)
  2193. break;
  2194. let rangeStart = this.ranges[index].from;
  2195. let after = this.lineAfter(rangeStart);
  2196. line += after;
  2197. end = rangeStart + after.length;
  2198. }
  2199. return { line, end };
  2200. }
  2201. skipGapsTo(pos, offset, side) {
  2202. for (;;) {
  2203. let end = this.ranges[this.rangeIndex].to, offPos = pos + offset;
  2204. if (side > 0 ? end > offPos : end >= offPos)
  2205. break;
  2206. let start = this.ranges[++this.rangeIndex].from;
  2207. offset += start - end;
  2208. }
  2209. return offset;
  2210. }
  2211. moveRangeIndex() {
  2212. while (this.ranges[this.rangeIndex].to < this.parsedPos)
  2213. this.rangeIndex++;
  2214. }
  2215. emitToken(id, from, to, size, offset) {
  2216. if (this.ranges.length > 1) {
  2217. offset = this.skipGapsTo(from, offset, 1);
  2218. from += offset;
  2219. let len0 = this.chunk.length;
  2220. offset = this.skipGapsTo(to, offset, -1);
  2221. to += offset;
  2222. size += this.chunk.length - len0;
  2223. }
  2224. this.chunk.push(id, from, to, size);
  2225. return offset;
  2226. }
  2227. parseLine(context) {
  2228. let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang;
  2229. let stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2);
  2230. if (stream.eol()) {
  2231. streamParser.blankLine(this.state, stream.indentUnit);
  2232. }
  2233. else {
  2234. while (!stream.eol()) {
  2235. let token = readToken(streamParser.token, stream, this.state);
  2236. if (token)
  2237. offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, 4, offset);
  2238. if (stream.start > 10000 /* MaxLineLength */)
  2239. break;
  2240. }
  2241. }
  2242. this.parsedPos = end;
  2243. this.moveRangeIndex();
  2244. if (this.parsedPos < this.to)
  2245. this.parsedPos++;
  2246. }
  2247. finishChunk() {
  2248. let tree = common.Tree.build({
  2249. buffer: this.chunk,
  2250. start: this.chunkStart,
  2251. length: this.parsedPos - this.chunkStart,
  2252. nodeSet,
  2253. topID: 0,
  2254. maxBufferLength: 2048 /* ChunkSize */,
  2255. reused: this.chunkReused
  2256. });
  2257. tree = new common.Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]);
  2258. this.chunks.push(tree);
  2259. this.chunkPos.push(this.chunkStart - this.ranges[0].from);
  2260. this.chunk = [];
  2261. this.chunkReused = undefined;
  2262. this.chunkStart = this.parsedPos;
  2263. }
  2264. finish() {
  2265. return new common.Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance();
  2266. }
  2267. }
  2268. function readToken(token, stream, state) {
  2269. stream.start = stream.pos;
  2270. for (let i = 0; i < 10; i++) {
  2271. let result = token(stream, state);
  2272. if (stream.pos > stream.start)
  2273. return result;
  2274. }
  2275. throw new Error("Stream parser failed to advance stream.");
  2276. }
  2277. const noTokens = Object.create(null);
  2278. const typeArray = [common.NodeType.none];
  2279. const nodeSet = new common.NodeSet(typeArray);
  2280. const warned = [];
  2281. const defaultTable = Object.create(null);
  2282. for (let [legacyName, name] of [
  2283. ["variable", "variableName"],
  2284. ["variable-2", "variableName.special"],
  2285. ["string-2", "string.special"],
  2286. ["def", "variableName.definition"],
  2287. ["tag", "tagName"],
  2288. ["attribute", "attributeName"],
  2289. ["type", "typeName"],
  2290. ["builtin", "variableName.standard"],
  2291. ["qualifier", "modifier"],
  2292. ["error", "invalid"],
  2293. ["header", "heading"],
  2294. ["property", "propertyName"]
  2295. ])
  2296. defaultTable[legacyName] = createTokenType(noTokens, name);
  2297. class TokenTable {
  2298. constructor(extra) {
  2299. this.extra = extra;
  2300. this.table = Object.assign(Object.create(null), defaultTable);
  2301. }
  2302. resolve(tag) {
  2303. return !tag ? 0 : this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag));
  2304. }
  2305. }
  2306. const defaultTokenTable = new TokenTable(noTokens);
  2307. function warnForPart(part, msg) {
  2308. if (warned.indexOf(part) > -1)
  2309. return;
  2310. warned.push(part);
  2311. console.warn(msg);
  2312. }
  2313. function createTokenType(extra, tagStr) {
  2314. let tag = null;
  2315. for (let part of tagStr.split(".")) {
  2316. let value = (extra[part] || highlight.tags[part]);
  2317. if (!value) {
  2318. warnForPart(part, `Unknown highlighting tag ${part}`);
  2319. }
  2320. else if (typeof value == "function") {
  2321. if (!tag)
  2322. warnForPart(part, `Modifier ${part} used at start of tag`);
  2323. else
  2324. tag = value(tag);
  2325. }
  2326. else {
  2327. if (tag)
  2328. warnForPart(part, `Tag ${part} used as modifier`);
  2329. else
  2330. tag = value;
  2331. }
  2332. }
  2333. if (!tag)
  2334. return 0;
  2335. let name = tagStr.replace(/ /g, "_"), type = common.NodeType.define({
  2336. id: typeArray.length,
  2337. name,
  2338. props: [highlight.styleTags({ [name]: tag })]
  2339. });
  2340. typeArray.push(type);
  2341. return type.id;
  2342. }
  2343. function docID(data) {
  2344. let type = common.NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data)] });
  2345. typeArray.push(type);
  2346. return type;
  2347. }
  2348. exports.HighlightStyle = HighlightStyle;
  2349. exports.IndentContext = IndentContext;
  2350. exports.LRLanguage = LRLanguage;
  2351. exports.Language = Language;
  2352. exports.LanguageDescription = LanguageDescription;
  2353. exports.LanguageSupport = LanguageSupport;
  2354. exports.ParseContext = ParseContext;
  2355. exports.StreamLanguage = StreamLanguage;
  2356. exports.StringStream = StringStream;
  2357. exports.TreeIndentContext = TreeIndentContext;
  2358. exports.bracketMatching = bracketMatching;
  2359. exports.codeFolding = codeFolding;
  2360. exports.continuedIndent = continuedIndent;
  2361. exports.defaultHighlightStyle = defaultHighlightStyle;
  2362. exports.defineLanguageFacet = defineLanguageFacet;
  2363. exports.delimitedIndent = delimitedIndent;
  2364. exports.ensureSyntaxTree = ensureSyntaxTree;
  2365. exports.flatIndent = flatIndent;
  2366. exports.foldAll = foldAll;
  2367. exports.foldCode = foldCode;
  2368. exports.foldEffect = foldEffect;
  2369. exports.foldGutter = foldGutter;
  2370. exports.foldInside = foldInside;
  2371. exports.foldKeymap = foldKeymap;
  2372. exports.foldNodeProp = foldNodeProp;
  2373. exports.foldService = foldService;
  2374. exports.foldState = foldState;
  2375. exports.foldable = foldable;
  2376. exports.foldedRanges = foldedRanges;
  2377. exports.forceParsing = forceParsing;
  2378. exports.getIndentUnit = getIndentUnit;
  2379. exports.getIndentation = getIndentation;
  2380. exports.highlightingFor = highlightingFor;
  2381. exports.indentNodeProp = indentNodeProp;
  2382. exports.indentOnInput = indentOnInput;
  2383. exports.indentRange = indentRange;
  2384. exports.indentService = indentService;
  2385. exports.indentString = indentString;
  2386. exports.indentUnit = indentUnit;
  2387. exports.language = language;
  2388. exports.languageDataProp = languageDataProp;
  2389. exports.matchBrackets = matchBrackets;
  2390. exports.syntaxHighlighting = syntaxHighlighting;
  2391. exports.syntaxParserRunning = syntaxParserRunning;
  2392. exports.syntaxTree = syntaxTree;
  2393. exports.syntaxTreeAvailable = syntaxTreeAvailable;
  2394. exports.unfoldAll = unfoldAll;
  2395. exports.unfoldCode = unfoldCode;
  2396. exports.unfoldEffect = unfoldEffect;