index.js 87 KB

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