index.cjs 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. /**
  4. The data structure for documents. @nonabstract
  5. */
  6. class Text {
  7. /**
  8. @internal
  9. */
  10. constructor() { }
  11. /**
  12. Get the line description around the given position.
  13. */
  14. lineAt(pos) {
  15. if (pos < 0 || pos > this.length)
  16. throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
  17. return this.lineInner(pos, false, 1, 0);
  18. }
  19. /**
  20. Get the description for the given (1-based) line number.
  21. */
  22. line(n) {
  23. if (n < 1 || n > this.lines)
  24. throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
  25. return this.lineInner(n, true, 1, 0);
  26. }
  27. /**
  28. Replace a range of the text with the given content.
  29. */
  30. replace(from, to, text) {
  31. let parts = [];
  32. this.decompose(0, from, parts, 2 /* To */);
  33. if (text.length)
  34. text.decompose(0, text.length, parts, 1 /* From */ | 2 /* To */);
  35. this.decompose(to, this.length, parts, 1 /* From */);
  36. return TextNode.from(parts, this.length - (to - from) + text.length);
  37. }
  38. /**
  39. Append another document to this one.
  40. */
  41. append(other) {
  42. return this.replace(this.length, this.length, other);
  43. }
  44. /**
  45. Retrieve the text between the given points.
  46. */
  47. slice(from, to = this.length) {
  48. let parts = [];
  49. this.decompose(from, to, parts, 0);
  50. return TextNode.from(parts, to - from);
  51. }
  52. /**
  53. Test whether this text is equal to another instance.
  54. */
  55. eq(other) {
  56. if (other == this)
  57. return true;
  58. if (other.length != this.length || other.lines != this.lines)
  59. return false;
  60. let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);
  61. let a = new RawTextCursor(this), b = new RawTextCursor(other);
  62. for (let skip = start, pos = start;;) {
  63. a.next(skip);
  64. b.next(skip);
  65. skip = 0;
  66. if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)
  67. return false;
  68. pos += a.value.length;
  69. if (a.done || pos >= end)
  70. return true;
  71. }
  72. }
  73. /**
  74. Iterate over the text. When `dir` is `-1`, iteration happens
  75. from end to start. This will return lines and the breaks between
  76. them as separate strings.
  77. */
  78. iter(dir = 1) { return new RawTextCursor(this, dir); }
  79. /**
  80. Iterate over a range of the text. When `from` > `to`, the
  81. iterator will run in reverse.
  82. */
  83. iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }
  84. /**
  85. Return a cursor that iterates over the given range of lines,
  86. _without_ returning the line breaks between, and yielding empty
  87. strings for empty lines.
  88. When `from` and `to` are given, they should be 1-based line numbers.
  89. */
  90. iterLines(from, to) {
  91. let inner;
  92. if (from == null) {
  93. inner = this.iter();
  94. }
  95. else {
  96. if (to == null)
  97. to = this.lines + 1;
  98. let start = this.line(from).from;
  99. inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
  100. }
  101. return new LineCursor(inner);
  102. }
  103. /**
  104. @internal
  105. */
  106. toString() { return this.sliceString(0); }
  107. /**
  108. Convert the document to an array of lines (which can be
  109. deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
  110. */
  111. toJSON() {
  112. let lines = [];
  113. this.flatten(lines);
  114. return lines;
  115. }
  116. /**
  117. Create a `Text` instance for the given array of lines.
  118. */
  119. static of(text) {
  120. if (text.length == 0)
  121. throw new RangeError("A document must have at least one line");
  122. if (text.length == 1 && !text[0])
  123. return Text.empty;
  124. return text.length <= 32 /* Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
  125. }
  126. }
  127. // Leaves store an array of line strings. There are always line breaks
  128. // between these strings. Leaves are limited in size and have to be
  129. // contained in TextNode instances for bigger documents.
  130. class TextLeaf extends Text {
  131. constructor(text, length = textLength(text)) {
  132. super();
  133. this.text = text;
  134. this.length = length;
  135. }
  136. get lines() { return this.text.length; }
  137. get children() { return null; }
  138. lineInner(target, isLine, line, offset) {
  139. for (let i = 0;; i++) {
  140. let string = this.text[i], end = offset + string.length;
  141. if ((isLine ? line : end) >= target)
  142. return new Line(offset, end, line, string);
  143. offset = end + 1;
  144. line++;
  145. }
  146. }
  147. decompose(from, to, target, open) {
  148. let text = from <= 0 && to >= this.length ? this
  149. : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
  150. if (open & 1 /* From */) {
  151. let prev = target.pop();
  152. let joined = appendText(text.text, prev.text.slice(), 0, text.length);
  153. if (joined.length <= 32 /* Branch */) {
  154. target.push(new TextLeaf(joined, prev.length + text.length));
  155. }
  156. else {
  157. let mid = joined.length >> 1;
  158. target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
  159. }
  160. }
  161. else {
  162. target.push(text);
  163. }
  164. }
  165. replace(from, to, text) {
  166. if (!(text instanceof TextLeaf))
  167. return super.replace(from, to, text);
  168. let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
  169. let newLen = this.length + text.length - (to - from);
  170. if (lines.length <= 32 /* Branch */)
  171. return new TextLeaf(lines, newLen);
  172. return TextNode.from(TextLeaf.split(lines, []), newLen);
  173. }
  174. sliceString(from, to = this.length, lineSep = "\n") {
  175. let result = "";
  176. for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {
  177. let line = this.text[i], end = pos + line.length;
  178. if (pos > from && i)
  179. result += lineSep;
  180. if (from < end && to > pos)
  181. result += line.slice(Math.max(0, from - pos), to - pos);
  182. pos = end + 1;
  183. }
  184. return result;
  185. }
  186. flatten(target) {
  187. for (let line of this.text)
  188. target.push(line);
  189. }
  190. scanIdentical() { return 0; }
  191. static split(text, target) {
  192. let part = [], len = -1;
  193. for (let line of text) {
  194. part.push(line);
  195. len += line.length + 1;
  196. if (part.length == 32 /* Branch */) {
  197. target.push(new TextLeaf(part, len));
  198. part = [];
  199. len = -1;
  200. }
  201. }
  202. if (len > -1)
  203. target.push(new TextLeaf(part, len));
  204. return target;
  205. }
  206. }
  207. // Nodes provide the tree structure of the `Text` type. They store a
  208. // number of other nodes or leaves, taking care to balance themselves
  209. // on changes. There are implied line breaks _between_ the children of
  210. // a node (but not before the first or after the last child).
  211. class TextNode extends Text {
  212. constructor(children, length) {
  213. super();
  214. this.children = children;
  215. this.length = length;
  216. this.lines = 0;
  217. for (let child of children)
  218. this.lines += child.lines;
  219. }
  220. lineInner(target, isLine, line, offset) {
  221. for (let i = 0;; i++) {
  222. let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;
  223. if ((isLine ? endLine : end) >= target)
  224. return child.lineInner(target, isLine, line, offset);
  225. offset = end + 1;
  226. line = endLine + 1;
  227. }
  228. }
  229. decompose(from, to, target, open) {
  230. for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {
  231. let child = this.children[i], end = pos + child.length;
  232. if (from <= end && to >= pos) {
  233. let childOpen = open & ((pos <= from ? 1 /* From */ : 0) | (end >= to ? 2 /* To */ : 0));
  234. if (pos >= from && end <= to && !childOpen)
  235. target.push(child);
  236. else
  237. child.decompose(from - pos, to - pos, target, childOpen);
  238. }
  239. pos = end + 1;
  240. }
  241. }
  242. replace(from, to, text) {
  243. if (text.lines < this.lines)
  244. for (let i = 0, pos = 0; i < this.children.length; i++) {
  245. let child = this.children[i], end = pos + child.length;
  246. // Fast path: if the change only affects one child and the
  247. // child's size remains in the acceptable range, only update
  248. // that child
  249. if (from >= pos && to <= end) {
  250. let updated = child.replace(from - pos, to - pos, text);
  251. let totalLines = this.lines - child.lines + updated.lines;
  252. if (updated.lines < (totalLines >> (5 /* BranchShift */ - 1)) &&
  253. updated.lines > (totalLines >> (5 /* BranchShift */ + 1))) {
  254. let copy = this.children.slice();
  255. copy[i] = updated;
  256. return new TextNode(copy, this.length - (to - from) + text.length);
  257. }
  258. return super.replace(pos, end, updated);
  259. }
  260. pos = end + 1;
  261. }
  262. return super.replace(from, to, text);
  263. }
  264. sliceString(from, to = this.length, lineSep = "\n") {
  265. let result = "";
  266. for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {
  267. let child = this.children[i], end = pos + child.length;
  268. if (pos > from && i)
  269. result += lineSep;
  270. if (from < end && to > pos)
  271. result += child.sliceString(from - pos, to - pos, lineSep);
  272. pos = end + 1;
  273. }
  274. return result;
  275. }
  276. flatten(target) {
  277. for (let child of this.children)
  278. child.flatten(target);
  279. }
  280. scanIdentical(other, dir) {
  281. if (!(other instanceof TextNode))
  282. return 0;
  283. let length = 0;
  284. let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]
  285. : [this.children.length - 1, other.children.length - 1, -1, -1];
  286. for (;; iA += dir, iB += dir) {
  287. if (iA == eA || iB == eB)
  288. return length;
  289. let chA = this.children[iA], chB = other.children[iB];
  290. if (chA != chB)
  291. return length + chA.scanIdentical(chB, dir);
  292. length += chA.length + 1;
  293. }
  294. }
  295. static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
  296. let lines = 0;
  297. for (let ch of children)
  298. lines += ch.lines;
  299. if (lines < 32 /* Branch */) {
  300. let flat = [];
  301. for (let ch of children)
  302. ch.flatten(flat);
  303. return new TextLeaf(flat, length);
  304. }
  305. let chunk = Math.max(32 /* Branch */, lines >> 5 /* BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;
  306. let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];
  307. function add(child) {
  308. let last;
  309. if (child.lines > maxChunk && child instanceof TextNode) {
  310. for (let node of child.children)
  311. add(node);
  312. }
  313. else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
  314. flush();
  315. chunked.push(child);
  316. }
  317. else if (child instanceof TextLeaf && currentLines &&
  318. (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&
  319. child.lines + last.lines <= 32 /* Branch */) {
  320. currentLines += child.lines;
  321. currentLen += child.length + 1;
  322. currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
  323. }
  324. else {
  325. if (currentLines + child.lines > chunk)
  326. flush();
  327. currentLines += child.lines;
  328. currentLen += child.length + 1;
  329. currentChunk.push(child);
  330. }
  331. }
  332. function flush() {
  333. if (currentLines == 0)
  334. return;
  335. chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
  336. currentLen = -1;
  337. currentLines = currentChunk.length = 0;
  338. }
  339. for (let child of children)
  340. add(child);
  341. flush();
  342. return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
  343. }
  344. }
  345. Text.empty = new TextLeaf([""], 0);
  346. function textLength(text) {
  347. let length = -1;
  348. for (let line of text)
  349. length += line.length + 1;
  350. return length;
  351. }
  352. function appendText(text, target, from = 0, to = 1e9) {
  353. for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {
  354. let line = text[i], end = pos + line.length;
  355. if (end >= from) {
  356. if (end > to)
  357. line = line.slice(0, to - pos);
  358. if (pos < from)
  359. line = line.slice(from - pos);
  360. if (first) {
  361. target[target.length - 1] += line;
  362. first = false;
  363. }
  364. else
  365. target.push(line);
  366. }
  367. pos = end + 1;
  368. }
  369. return target;
  370. }
  371. function sliceText(text, from, to) {
  372. return appendText(text, [""], from, to);
  373. }
  374. class RawTextCursor {
  375. constructor(text, dir = 1) {
  376. this.dir = dir;
  377. this.done = false;
  378. this.lineBreak = false;
  379. this.value = "";
  380. this.nodes = [text];
  381. this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
  382. }
  383. nextInner(skip, dir) {
  384. this.done = this.lineBreak = false;
  385. for (;;) {
  386. let last = this.nodes.length - 1;
  387. let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;
  388. let size = top instanceof TextLeaf ? top.text.length : top.children.length;
  389. if (offset == (dir > 0 ? size : 0)) {
  390. if (last == 0) {
  391. this.done = true;
  392. this.value = "";
  393. return this;
  394. }
  395. if (dir > 0)
  396. this.offsets[last - 1]++;
  397. this.nodes.pop();
  398. this.offsets.pop();
  399. }
  400. else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
  401. this.offsets[last] += dir;
  402. if (skip == 0) {
  403. this.lineBreak = true;
  404. this.value = "\n";
  405. return this;
  406. }
  407. skip--;
  408. }
  409. else if (top instanceof TextLeaf) {
  410. // Move to the next string
  411. let next = top.text[offset + (dir < 0 ? -1 : 0)];
  412. this.offsets[last] += dir;
  413. if (next.length > Math.max(0, skip)) {
  414. this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
  415. return this;
  416. }
  417. skip -= next.length;
  418. }
  419. else {
  420. let next = top.children[offset + (dir < 0 ? -1 : 0)];
  421. if (skip > next.length) {
  422. skip -= next.length;
  423. this.offsets[last] += dir;
  424. }
  425. else {
  426. if (dir < 0)
  427. this.offsets[last]--;
  428. this.nodes.push(next);
  429. this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
  430. }
  431. }
  432. }
  433. }
  434. next(skip = 0) {
  435. if (skip < 0) {
  436. this.nextInner(-skip, (-this.dir));
  437. skip = this.value.length;
  438. }
  439. return this.nextInner(skip, this.dir);
  440. }
  441. }
  442. class PartialTextCursor {
  443. constructor(text, start, end) {
  444. this.value = "";
  445. this.done = false;
  446. this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
  447. this.pos = start > end ? text.length : 0;
  448. this.from = Math.min(start, end);
  449. this.to = Math.max(start, end);
  450. }
  451. nextInner(skip, dir) {
  452. if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
  453. this.value = "";
  454. this.done = true;
  455. return this;
  456. }
  457. skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
  458. let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
  459. if (skip > limit)
  460. skip = limit;
  461. limit -= skip;
  462. let { value } = this.cursor.next(skip);
  463. this.pos += (value.length + skip) * dir;
  464. this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
  465. this.done = !this.value;
  466. return this;
  467. }
  468. next(skip = 0) {
  469. if (skip < 0)
  470. skip = Math.max(skip, this.from - this.pos);
  471. else if (skip > 0)
  472. skip = Math.min(skip, this.to - this.pos);
  473. return this.nextInner(skip, this.cursor.dir);
  474. }
  475. get lineBreak() { return this.cursor.lineBreak && this.value != ""; }
  476. }
  477. class LineCursor {
  478. constructor(inner) {
  479. this.inner = inner;
  480. this.afterBreak = true;
  481. this.value = "";
  482. this.done = false;
  483. }
  484. next(skip = 0) {
  485. let { done, lineBreak, value } = this.inner.next(skip);
  486. if (done) {
  487. this.done = true;
  488. this.value = "";
  489. }
  490. else if (lineBreak) {
  491. if (this.afterBreak) {
  492. this.value = "";
  493. }
  494. else {
  495. this.afterBreak = true;
  496. this.next();
  497. }
  498. }
  499. else {
  500. this.value = value;
  501. this.afterBreak = false;
  502. }
  503. return this;
  504. }
  505. get lineBreak() { return false; }
  506. }
  507. if (typeof Symbol != "undefined") {
  508. Text.prototype[Symbol.iterator] = function () { return this.iter(); };
  509. RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =
  510. LineCursor.prototype[Symbol.iterator] = function () { return this; };
  511. }
  512. /**
  513. This type describes a line in the document. It is created
  514. on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
  515. */
  516. class Line {
  517. /**
  518. @internal
  519. */
  520. constructor(
  521. /**
  522. The position of the start of the line.
  523. */
  524. from,
  525. /**
  526. The position at the end of the line (_before_ the line break,
  527. or at the end of document for the last line).
  528. */
  529. to,
  530. /**
  531. This line's line number (1-based).
  532. */
  533. number,
  534. /**
  535. The line's content.
  536. */
  537. text) {
  538. this.from = from;
  539. this.to = to;
  540. this.number = number;
  541. this.text = text;
  542. }
  543. /**
  544. The length of the line (not including any line break after it).
  545. */
  546. get length() { return this.to - this.from; }
  547. }
  548. // Compressed representation of the Grapheme_Cluster_Break=Extend
  549. // information from
  550. // http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.
  551. // Each pair of elements represents a range, as an offet from the
  552. // previous range and a length. Numbers are in base-36, with the empty
  553. // string being a shorthand for 1.
  554. let extend = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1);
  555. // Convert offsets into absolute values
  556. for (let i = 1; i < extend.length; i++)
  557. extend[i] += extend[i - 1];
  558. function isExtendingChar(code) {
  559. for (let i = 1; i < extend.length; i += 2)
  560. if (extend[i] > code)
  561. return extend[i - 1] <= code;
  562. return false;
  563. }
  564. function isRegionalIndicator(code) {
  565. return code >= 0x1F1E6 && code <= 0x1F1FF;
  566. }
  567. const ZWJ = 0x200d;
  568. /**
  569. Returns a next grapheme cluster break _after_ (not equal to)
  570. `pos`, if `forward` is true, or before otherwise. Returns `pos`
  571. itself if no further cluster break is available in the string.
  572. Moves across surrogate pairs, extending characters (when
  573. `includeExtending` is true), characters joined with zero-width
  574. joiners, and flag emoji.
  575. */
  576. function findClusterBreak(str, pos, forward = true, includeExtending = true) {
  577. return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
  578. }
  579. function nextClusterBreak(str, pos, includeExtending) {
  580. if (pos == str.length)
  581. return pos;
  582. // If pos is in the middle of a surrogate pair, move to its start
  583. if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
  584. pos--;
  585. let prev = codePointAt(str, pos);
  586. pos += codePointSize(prev);
  587. while (pos < str.length) {
  588. let next = codePointAt(str, pos);
  589. if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
  590. pos += codePointSize(next);
  591. prev = next;
  592. }
  593. else if (isRegionalIndicator(next)) {
  594. let countBefore = 0, i = pos - 2;
  595. while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
  596. countBefore++;
  597. i -= 2;
  598. }
  599. if (countBefore % 2 == 0)
  600. break;
  601. else
  602. pos += 2;
  603. }
  604. else {
  605. break;
  606. }
  607. }
  608. return pos;
  609. }
  610. function prevClusterBreak(str, pos, includeExtending) {
  611. while (pos > 0) {
  612. let found = nextClusterBreak(str, pos - 2, includeExtending);
  613. if (found < pos)
  614. return found;
  615. pos--;
  616. }
  617. return 0;
  618. }
  619. function surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }
  620. function surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }
  621. /**
  622. Find the code point at the given position in a string (like the
  623. [`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
  624. string method).
  625. */
  626. function codePointAt(str, pos) {
  627. let code0 = str.charCodeAt(pos);
  628. if (!surrogateHigh(code0) || pos + 1 == str.length)
  629. return code0;
  630. let code1 = str.charCodeAt(pos + 1);
  631. if (!surrogateLow(code1))
  632. return code0;
  633. return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;
  634. }
  635. /**
  636. Given a Unicode codepoint, return the JavaScript string that
  637. respresents it (like
  638. [`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
  639. */
  640. function fromCodePoint(code) {
  641. if (code <= 0xffff)
  642. return String.fromCharCode(code);
  643. code -= 0x10000;
  644. return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);
  645. }
  646. /**
  647. The amount of positions a character takes up a JavaScript string.
  648. */
  649. function codePointSize(code) { return code < 0x10000 ? 1 : 2; }
  650. const DefaultSplit = /\r\n?|\n/;
  651. /**
  652. Distinguishes different ways in which positions can be mapped.
  653. */
  654. exports.MapMode = void 0;
  655. (function (MapMode) {
  656. /**
  657. Map a position to a valid new position, even when its context
  658. was deleted.
  659. */
  660. MapMode[MapMode["Simple"] = 0] = "Simple";
  661. /**
  662. Return null if deletion happens across the position.
  663. */
  664. MapMode[MapMode["TrackDel"] = 1] = "TrackDel";
  665. /**
  666. Return null if the character _before_ the position is deleted.
  667. */
  668. MapMode[MapMode["TrackBefore"] = 2] = "TrackBefore";
  669. /**
  670. Return null if the character _after_ the position is deleted.
  671. */
  672. MapMode[MapMode["TrackAfter"] = 3] = "TrackAfter";
  673. })(exports.MapMode || (exports.MapMode = {}));
  674. /**
  675. A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
  676. that doesn't store the inserted text. As such, it can't be
  677. applied, but is cheaper to store and manipulate.
  678. */
  679. class ChangeDesc {
  680. // Sections are encoded as pairs of integers. The first is the
  681. // length in the current document, and the second is -1 for
  682. // unaffected sections, and the length of the replacement content
  683. // otherwise. So an insertion would be (0, n>0), a deletion (n>0,
  684. // 0), and a replacement two positive numbers.
  685. /**
  686. @internal
  687. */
  688. constructor(
  689. /**
  690. @internal
  691. */
  692. sections) {
  693. this.sections = sections;
  694. }
  695. /**
  696. The length of the document before the change.
  697. */
  698. get length() {
  699. let result = 0;
  700. for (let i = 0; i < this.sections.length; i += 2)
  701. result += this.sections[i];
  702. return result;
  703. }
  704. /**
  705. The length of the document after the change.
  706. */
  707. get newLength() {
  708. let result = 0;
  709. for (let i = 0; i < this.sections.length; i += 2) {
  710. let ins = this.sections[i + 1];
  711. result += ins < 0 ? this.sections[i] : ins;
  712. }
  713. return result;
  714. }
  715. /**
  716. False when there are actual changes in this set.
  717. */
  718. get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }
  719. /**
  720. Iterate over the unchanged parts left by these changes. `posA`
  721. provides the position of the range in the old document, `posB`
  722. the new position in the changed document.
  723. */
  724. iterGaps(f) {
  725. for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {
  726. let len = this.sections[i++], ins = this.sections[i++];
  727. if (ins < 0) {
  728. f(posA, posB, len);
  729. posB += len;
  730. }
  731. else {
  732. posB += ins;
  733. }
  734. posA += len;
  735. }
  736. }
  737. /**
  738. Iterate over the ranges changed by these changes. (See
  739. [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
  740. variant that also provides you with the inserted text.)
  741. `fromA`/`toA` provides the extent of the change in the starting
  742. document, `fromB`/`toB` the extent of the replacement in the
  743. changed document.
  744. When `individual` is true, adjacent changes (which are kept
  745. separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
  746. reported separately.
  747. */
  748. iterChangedRanges(f, individual = false) {
  749. iterChanges(this, f, individual);
  750. }
  751. /**
  752. Get a description of the inverted form of these changes.
  753. */
  754. get invertedDesc() {
  755. let sections = [];
  756. for (let i = 0; i < this.sections.length;) {
  757. let len = this.sections[i++], ins = this.sections[i++];
  758. if (ins < 0)
  759. sections.push(len, ins);
  760. else
  761. sections.push(ins, len);
  762. }
  763. return new ChangeDesc(sections);
  764. }
  765. /**
  766. Compute the combined effect of applying another set of changes
  767. after this one. The length of the document after this set should
  768. match the length before `other`.
  769. */
  770. composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }
  771. /**
  772. Map this description, which should start with the same document
  773. as `other`, over another set of changes, so that it can be
  774. applied after it. When `before` is true, map as if the changes
  775. in `other` happened before the ones in `this`.
  776. */
  777. mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }
  778. mapPos(pos, assoc = -1, mode = exports.MapMode.Simple) {
  779. let posA = 0, posB = 0;
  780. for (let i = 0; i < this.sections.length;) {
  781. let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;
  782. if (ins < 0) {
  783. if (endA > pos)
  784. return posB + (pos - posA);
  785. posB += len;
  786. }
  787. else {
  788. if (mode != exports.MapMode.Simple && endA >= pos &&
  789. (mode == exports.MapMode.TrackDel && posA < pos && endA > pos ||
  790. mode == exports.MapMode.TrackBefore && posA < pos ||
  791. mode == exports.MapMode.TrackAfter && endA > pos))
  792. return null;
  793. if (endA > pos || endA == pos && assoc < 0 && !len)
  794. return pos == posA || assoc < 0 ? posB : posB + ins;
  795. posB += ins;
  796. }
  797. posA = endA;
  798. }
  799. if (pos > posA)
  800. throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
  801. return posB;
  802. }
  803. /**
  804. Check whether these changes touch a given range. When one of the
  805. changes entirely covers the range, the string `"cover"` is
  806. returned.
  807. */
  808. touchesRange(from, to = from) {
  809. for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {
  810. let len = this.sections[i++], ins = this.sections[i++], end = pos + len;
  811. if (ins >= 0 && pos <= to && end >= from)
  812. return pos < from && end > to ? "cover" : true;
  813. pos = end;
  814. }
  815. return false;
  816. }
  817. /**
  818. @internal
  819. */
  820. toString() {
  821. let result = "";
  822. for (let i = 0; i < this.sections.length;) {
  823. let len = this.sections[i++], ins = this.sections[i++];
  824. result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
  825. }
  826. return result;
  827. }
  828. /**
  829. Serialize this change desc to a JSON-representable value.
  830. */
  831. toJSON() { return this.sections; }
  832. /**
  833. Create a change desc from its JSON representation (as produced
  834. by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
  835. */
  836. static fromJSON(json) {
  837. if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number"))
  838. throw new RangeError("Invalid JSON representation of ChangeDesc");
  839. return new ChangeDesc(json);
  840. }
  841. /**
  842. @internal
  843. */
  844. static create(sections) { return new ChangeDesc(sections); }
  845. }
  846. /**
  847. A change set represents a group of modifications to a document. It
  848. stores the document length, and can only be applied to documents
  849. with exactly that length.
  850. */
  851. class ChangeSet extends ChangeDesc {
  852. constructor(sections,
  853. /**
  854. @internal
  855. */
  856. inserted) {
  857. super(sections);
  858. this.inserted = inserted;
  859. }
  860. /**
  861. Apply the changes to a document, returning the modified
  862. document.
  863. */
  864. apply(doc) {
  865. if (this.length != doc.length)
  866. throw new RangeError("Applying change set to a document with the wrong length");
  867. iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);
  868. return doc;
  869. }
  870. mapDesc(other, before = false) { return mapSet(this, other, before, true); }
  871. /**
  872. Given the document as it existed _before_ the changes, return a
  873. change set that represents the inverse of this set, which could
  874. be used to go from the document created by the changes back to
  875. the document as it existed before the changes.
  876. */
  877. invert(doc) {
  878. let sections = this.sections.slice(), inserted = [];
  879. for (let i = 0, pos = 0; i < sections.length; i += 2) {
  880. let len = sections[i], ins = sections[i + 1];
  881. if (ins >= 0) {
  882. sections[i] = ins;
  883. sections[i + 1] = len;
  884. let index = i >> 1;
  885. while (inserted.length < index)
  886. inserted.push(Text.empty);
  887. inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);
  888. }
  889. pos += len;
  890. }
  891. return new ChangeSet(sections, inserted);
  892. }
  893. /**
  894. Combine two subsequent change sets into a single set. `other`
  895. must start in the document produced by `this`. If `this` goes
  896. `docA` → `docB` and `other` represents `docB` → `docC`, the
  897. returned value will represent the change `docA` → `docC`.
  898. */
  899. compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }
  900. /**
  901. Given another change set starting in the same document, maps this
  902. change set over the other, producing a new change set that can be
  903. applied to the document produced by applying `other`. When
  904. `before` is `true`, order changes as if `this` comes before
  905. `other`, otherwise (the default) treat `other` as coming first.
  906. Given two changes `A` and `B`, `A.compose(B.map(A))` and
  907. `B.compose(A.map(B, true))` will produce the same document. This
  908. provides a basic form of [operational
  909. transformation](https://en.wikipedia.org/wiki/Operational_transformation),
  910. and can be used for collaborative editing.
  911. */
  912. map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }
  913. /**
  914. Iterate over the changed ranges in the document, calling `f` for
  915. each, with the range in the original document (`fromA`-`toA`)
  916. and the range that replaces it in the new document
  917. (`fromB`-`toB`).
  918. When `individual` is true, adjacent changes are reported
  919. separately.
  920. */
  921. iterChanges(f, individual = false) {
  922. iterChanges(this, f, individual);
  923. }
  924. /**
  925. Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
  926. set.
  927. */
  928. get desc() { return ChangeDesc.create(this.sections); }
  929. /**
  930. @internal
  931. */
  932. filter(ranges) {
  933. let resultSections = [], resultInserted = [], filteredSections = [];
  934. let iter = new SectionIter(this);
  935. done: for (let i = 0, pos = 0;;) {
  936. let next = i == ranges.length ? 1e9 : ranges[i++];
  937. while (pos < next || pos == next && iter.len == 0) {
  938. if (iter.done)
  939. break done;
  940. let len = Math.min(iter.len, next - pos);
  941. addSection(filteredSections, len, -1);
  942. let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
  943. addSection(resultSections, len, ins);
  944. if (ins > 0)
  945. addInsert(resultInserted, resultSections, iter.text);
  946. iter.forward(len);
  947. pos += len;
  948. }
  949. let end = ranges[i++];
  950. while (pos < end) {
  951. if (iter.done)
  952. break done;
  953. let len = Math.min(iter.len, end - pos);
  954. addSection(resultSections, len, -1);
  955. addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
  956. iter.forward(len);
  957. pos += len;
  958. }
  959. }
  960. return { changes: new ChangeSet(resultSections, resultInserted),
  961. filtered: ChangeDesc.create(filteredSections) };
  962. }
  963. /**
  964. Serialize this change set to a JSON-representable value.
  965. */
  966. toJSON() {
  967. let parts = [];
  968. for (let i = 0; i < this.sections.length; i += 2) {
  969. let len = this.sections[i], ins = this.sections[i + 1];
  970. if (ins < 0)
  971. parts.push(len);
  972. else if (ins == 0)
  973. parts.push([len]);
  974. else
  975. parts.push([len].concat(this.inserted[i >> 1].toJSON()));
  976. }
  977. return parts;
  978. }
  979. /**
  980. Create a change set for the given changes, for a document of the
  981. given length, using `lineSep` as line separator.
  982. */
  983. static of(changes, length, lineSep) {
  984. let sections = [], inserted = [], pos = 0;
  985. let total = null;
  986. function flush(force = false) {
  987. if (!force && !sections.length)
  988. return;
  989. if (pos < length)
  990. addSection(sections, length - pos, -1);
  991. let set = new ChangeSet(sections, inserted);
  992. total = total ? total.compose(set.map(total)) : set;
  993. sections = [];
  994. inserted = [];
  995. pos = 0;
  996. }
  997. function process(spec) {
  998. if (Array.isArray(spec)) {
  999. for (let sub of spec)
  1000. process(sub);
  1001. }
  1002. else if (spec instanceof ChangeSet) {
  1003. if (spec.length != length)
  1004. throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
  1005. flush();
  1006. total = total ? total.compose(spec.map(total)) : spec;
  1007. }
  1008. else {
  1009. let { from, to = from, insert } = spec;
  1010. if (from > to || from < 0 || to > length)
  1011. throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
  1012. let insText = !insert ? Text.empty : typeof insert == "string" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;
  1013. let insLen = insText.length;
  1014. if (from == to && insLen == 0)
  1015. return;
  1016. if (from < pos)
  1017. flush();
  1018. if (from > pos)
  1019. addSection(sections, from - pos, -1);
  1020. addSection(sections, to - from, insLen);
  1021. addInsert(inserted, sections, insText);
  1022. pos = to;
  1023. }
  1024. }
  1025. process(changes);
  1026. flush(!total);
  1027. return total;
  1028. }
  1029. /**
  1030. Create an empty changeset of the given length.
  1031. */
  1032. static empty(length) {
  1033. return new ChangeSet(length ? [length, -1] : [], []);
  1034. }
  1035. /**
  1036. Create a changeset from its JSON representation (as produced by
  1037. [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
  1038. */
  1039. static fromJSON(json) {
  1040. if (!Array.isArray(json))
  1041. throw new RangeError("Invalid JSON representation of ChangeSet");
  1042. let sections = [], inserted = [];
  1043. for (let i = 0; i < json.length; i++) {
  1044. let part = json[i];
  1045. if (typeof part == "number") {
  1046. sections.push(part, -1);
  1047. }
  1048. else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i) => i && typeof e != "string")) {
  1049. throw new RangeError("Invalid JSON representation of ChangeSet");
  1050. }
  1051. else if (part.length == 1) {
  1052. sections.push(part[0], 0);
  1053. }
  1054. else {
  1055. while (inserted.length < i)
  1056. inserted.push(Text.empty);
  1057. inserted[i] = Text.of(part.slice(1));
  1058. sections.push(part[0], inserted[i].length);
  1059. }
  1060. }
  1061. return new ChangeSet(sections, inserted);
  1062. }
  1063. /**
  1064. @internal
  1065. */
  1066. static createSet(sections, inserted) {
  1067. return new ChangeSet(sections, inserted);
  1068. }
  1069. }
  1070. function addSection(sections, len, ins, forceJoin = false) {
  1071. if (len == 0 && ins <= 0)
  1072. return;
  1073. let last = sections.length - 2;
  1074. if (last >= 0 && ins <= 0 && ins == sections[last + 1])
  1075. sections[last] += len;
  1076. else if (len == 0 && sections[last] == 0)
  1077. sections[last + 1] += ins;
  1078. else if (forceJoin) {
  1079. sections[last] += len;
  1080. sections[last + 1] += ins;
  1081. }
  1082. else
  1083. sections.push(len, ins);
  1084. }
  1085. function addInsert(values, sections, value) {
  1086. if (value.length == 0)
  1087. return;
  1088. let index = (sections.length - 2) >> 1;
  1089. if (index < values.length) {
  1090. values[values.length - 1] = values[values.length - 1].append(value);
  1091. }
  1092. else {
  1093. while (values.length < index)
  1094. values.push(Text.empty);
  1095. values.push(value);
  1096. }
  1097. }
  1098. function iterChanges(desc, f, individual) {
  1099. let inserted = desc.inserted;
  1100. for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {
  1101. let len = desc.sections[i++], ins = desc.sections[i++];
  1102. if (ins < 0) {
  1103. posA += len;
  1104. posB += len;
  1105. }
  1106. else {
  1107. let endA = posA, endB = posB, text = Text.empty;
  1108. for (;;) {
  1109. endA += len;
  1110. endB += ins;
  1111. if (ins && inserted)
  1112. text = text.append(inserted[(i - 2) >> 1]);
  1113. if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)
  1114. break;
  1115. len = desc.sections[i++];
  1116. ins = desc.sections[i++];
  1117. }
  1118. f(posA, endA, posB, endB, text);
  1119. posA = endA;
  1120. posB = endB;
  1121. }
  1122. }
  1123. }
  1124. function mapSet(setA, setB, before, mkSet = false) {
  1125. // Produce a copy of setA that applies to the document after setB
  1126. // has been applied (assuming both start at the same document).
  1127. let sections = [], insert = mkSet ? [] : null;
  1128. let a = new SectionIter(setA), b = new SectionIter(setB);
  1129. // Iterate over both sets in parallel. inserted tracks, for changes
  1130. // in A that have to be processed piece-by-piece, whether their
  1131. // content has been inserted already, and refers to the section
  1132. // index.
  1133. for (let inserted = -1;;) {
  1134. if (a.ins == -1 && b.ins == -1) {
  1135. // Move across ranges skipped by both sets.
  1136. let len = Math.min(a.len, b.len);
  1137. addSection(sections, len, -1);
  1138. a.forward(len);
  1139. b.forward(len);
  1140. }
  1141. else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
  1142. // If there's a change in B that comes before the next change in
  1143. // A (ordered by start pos, then len, then before flag), skip
  1144. // that (and process any changes in A it covers).
  1145. let len = b.len;
  1146. addSection(sections, b.ins, -1);
  1147. while (len) {
  1148. let piece = Math.min(a.len, len);
  1149. if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
  1150. addSection(sections, 0, a.ins);
  1151. if (insert)
  1152. addInsert(insert, sections, a.text);
  1153. inserted = a.i;
  1154. }
  1155. a.forward(piece);
  1156. len -= piece;
  1157. }
  1158. b.next();
  1159. }
  1160. else if (a.ins >= 0) {
  1161. // Process the part of a change in A up to the start of the next
  1162. // non-deletion change in B (if overlapping).
  1163. let len = 0, left = a.len;
  1164. while (left) {
  1165. if (b.ins == -1) {
  1166. let piece = Math.min(left, b.len);
  1167. len += piece;
  1168. left -= piece;
  1169. b.forward(piece);
  1170. }
  1171. else if (b.ins == 0 && b.len < left) {
  1172. left -= b.len;
  1173. b.next();
  1174. }
  1175. else {
  1176. break;
  1177. }
  1178. }
  1179. addSection(sections, len, inserted < a.i ? a.ins : 0);
  1180. if (insert && inserted < a.i)
  1181. addInsert(insert, sections, a.text);
  1182. inserted = a.i;
  1183. a.forward(a.len - left);
  1184. }
  1185. else if (a.done && b.done) {
  1186. return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
  1187. }
  1188. else {
  1189. throw new Error("Mismatched change set lengths");
  1190. }
  1191. }
  1192. }
  1193. function composeSets(setA, setB, mkSet = false) {
  1194. let sections = [];
  1195. let insert = mkSet ? [] : null;
  1196. let a = new SectionIter(setA), b = new SectionIter(setB);
  1197. for (let open = false;;) {
  1198. if (a.done && b.done) {
  1199. return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);
  1200. }
  1201. else if (a.ins == 0) { // Deletion in A
  1202. addSection(sections, a.len, 0, open);
  1203. a.next();
  1204. }
  1205. else if (b.len == 0 && !b.done) { // Insertion in B
  1206. addSection(sections, 0, b.ins, open);
  1207. if (insert)
  1208. addInsert(insert, sections, b.text);
  1209. b.next();
  1210. }
  1211. else if (a.done || b.done) {
  1212. throw new Error("Mismatched change set lengths");
  1213. }
  1214. else {
  1215. let len = Math.min(a.len2, b.len), sectionLen = sections.length;
  1216. if (a.ins == -1) {
  1217. let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
  1218. addSection(sections, len, insB, open);
  1219. if (insert && insB)
  1220. addInsert(insert, sections, b.text);
  1221. }
  1222. else if (b.ins == -1) {
  1223. addSection(sections, a.off ? 0 : a.len, len, open);
  1224. if (insert)
  1225. addInsert(insert, sections, a.textBit(len));
  1226. }
  1227. else {
  1228. addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
  1229. if (insert && !b.off)
  1230. addInsert(insert, sections, b.text);
  1231. }
  1232. open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
  1233. a.forward2(len);
  1234. b.forward(len);
  1235. }
  1236. }
  1237. }
  1238. class SectionIter {
  1239. constructor(set) {
  1240. this.set = set;
  1241. this.i = 0;
  1242. this.next();
  1243. }
  1244. next() {
  1245. let { sections } = this.set;
  1246. if (this.i < sections.length) {
  1247. this.len = sections[this.i++];
  1248. this.ins = sections[this.i++];
  1249. }
  1250. else {
  1251. this.len = 0;
  1252. this.ins = -2;
  1253. }
  1254. this.off = 0;
  1255. }
  1256. get done() { return this.ins == -2; }
  1257. get len2() { return this.ins < 0 ? this.len : this.ins; }
  1258. get text() {
  1259. let { inserted } = this.set, index = (this.i - 2) >> 1;
  1260. return index >= inserted.length ? Text.empty : inserted[index];
  1261. }
  1262. textBit(len) {
  1263. let { inserted } = this.set, index = (this.i - 2) >> 1;
  1264. return index >= inserted.length && !len ? Text.empty
  1265. : inserted[index].slice(this.off, len == null ? undefined : this.off + len);
  1266. }
  1267. forward(len) {
  1268. if (len == this.len)
  1269. this.next();
  1270. else {
  1271. this.len -= len;
  1272. this.off += len;
  1273. }
  1274. }
  1275. forward2(len) {
  1276. if (this.ins == -1)
  1277. this.forward(len);
  1278. else if (len == this.ins)
  1279. this.next();
  1280. else {
  1281. this.ins -= len;
  1282. this.off += len;
  1283. }
  1284. }
  1285. }
  1286. /**
  1287. A single selection range. When
  1288. [`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
  1289. is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
  1290. multiple ranges. By default, selections hold exactly one range.
  1291. */
  1292. class SelectionRange {
  1293. constructor(
  1294. /**
  1295. The lower boundary of the range.
  1296. */
  1297. from,
  1298. /**
  1299. The upper boundary of the range.
  1300. */
  1301. to, flags) {
  1302. this.from = from;
  1303. this.to = to;
  1304. this.flags = flags;
  1305. }
  1306. /**
  1307. The anchor of the range—the side that doesn't move when you
  1308. extend it.
  1309. */
  1310. get anchor() { return this.flags & 16 /* Inverted */ ? this.to : this.from; }
  1311. /**
  1312. The head of the range, which is moved when the range is
  1313. [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
  1314. */
  1315. get head() { return this.flags & 16 /* Inverted */ ? this.from : this.to; }
  1316. /**
  1317. True when `anchor` and `head` are at the same position.
  1318. */
  1319. get empty() { return this.from == this.to; }
  1320. /**
  1321. If this is a cursor that is explicitly associated with the
  1322. character on one of its sides, this returns the side. -1 means
  1323. the character before its position, 1 the character after, and 0
  1324. means no association.
  1325. */
  1326. get assoc() { return this.flags & 4 /* AssocBefore */ ? -1 : this.flags & 8 /* AssocAfter */ ? 1 : 0; }
  1327. /**
  1328. The bidirectional text level associated with this cursor, if
  1329. any.
  1330. */
  1331. get bidiLevel() {
  1332. let level = this.flags & 3 /* BidiLevelMask */;
  1333. return level == 3 ? null : level;
  1334. }
  1335. /**
  1336. The goal column (stored vertical offset) associated with a
  1337. cursor. This is used to preserve the vertical position when
  1338. [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
  1339. lines of different length.
  1340. */
  1341. get goalColumn() {
  1342. let value = this.flags >> 5 /* GoalColumnOffset */;
  1343. return value == 33554431 /* NoGoalColumn */ ? undefined : value;
  1344. }
  1345. /**
  1346. Map this range through a change, producing a valid range in the
  1347. updated document.
  1348. */
  1349. map(change, assoc = -1) {
  1350. let from, to;
  1351. if (this.empty) {
  1352. from = to = change.mapPos(this.from, assoc);
  1353. }
  1354. else {
  1355. from = change.mapPos(this.from, 1);
  1356. to = change.mapPos(this.to, -1);
  1357. }
  1358. return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
  1359. }
  1360. /**
  1361. Extend this range to cover at least `from` to `to`.
  1362. */
  1363. extend(from, to = from) {
  1364. if (from <= this.anchor && to >= this.anchor)
  1365. return EditorSelection.range(from, to);
  1366. let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
  1367. return EditorSelection.range(this.anchor, head);
  1368. }
  1369. /**
  1370. Compare this range to another range.
  1371. */
  1372. eq(other) {
  1373. return this.anchor == other.anchor && this.head == other.head;
  1374. }
  1375. /**
  1376. Return a JSON-serializable object representing the range.
  1377. */
  1378. toJSON() { return { anchor: this.anchor, head: this.head }; }
  1379. /**
  1380. Convert a JSON representation of a range to a `SelectionRange`
  1381. instance.
  1382. */
  1383. static fromJSON(json) {
  1384. if (!json || typeof json.anchor != "number" || typeof json.head != "number")
  1385. throw new RangeError("Invalid JSON representation for SelectionRange");
  1386. return EditorSelection.range(json.anchor, json.head);
  1387. }
  1388. /**
  1389. @internal
  1390. */
  1391. static create(from, to, flags) {
  1392. return new SelectionRange(from, to, flags);
  1393. }
  1394. }
  1395. /**
  1396. An editor selection holds one or more selection ranges.
  1397. */
  1398. class EditorSelection {
  1399. constructor(
  1400. /**
  1401. The ranges in the selection, sorted by position. Ranges cannot
  1402. overlap (but they may touch, if they aren't empty).
  1403. */
  1404. ranges,
  1405. /**
  1406. The index of the _main_ range in the selection (which is
  1407. usually the range that was added last).
  1408. */
  1409. mainIndex) {
  1410. this.ranges = ranges;
  1411. this.mainIndex = mainIndex;
  1412. }
  1413. /**
  1414. Map a selection through a change. Used to adjust the selection
  1415. position for changes.
  1416. */
  1417. map(change, assoc = -1) {
  1418. if (change.empty)
  1419. return this;
  1420. return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
  1421. }
  1422. /**
  1423. Compare this selection to another selection.
  1424. */
  1425. eq(other) {
  1426. if (this.ranges.length != other.ranges.length ||
  1427. this.mainIndex != other.mainIndex)
  1428. return false;
  1429. for (let i = 0; i < this.ranges.length; i++)
  1430. if (!this.ranges[i].eq(other.ranges[i]))
  1431. return false;
  1432. return true;
  1433. }
  1434. /**
  1435. Get the primary selection range. Usually, you should make sure
  1436. your code applies to _all_ ranges, by using methods like
  1437. [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
  1438. */
  1439. get main() { return this.ranges[this.mainIndex]; }
  1440. /**
  1441. Make sure the selection only has one range. Returns a selection
  1442. holding only the main range from this selection.
  1443. */
  1444. asSingle() {
  1445. return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
  1446. }
  1447. /**
  1448. Extend this selection with an extra range.
  1449. */
  1450. addRange(range, main = true) {
  1451. return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
  1452. }
  1453. /**
  1454. Replace a given range with another range, and then normalize the
  1455. selection to merge and sort ranges if necessary.
  1456. */
  1457. replaceRange(range, which = this.mainIndex) {
  1458. let ranges = this.ranges.slice();
  1459. ranges[which] = range;
  1460. return EditorSelection.create(ranges, this.mainIndex);
  1461. }
  1462. /**
  1463. Convert this selection to an object that can be serialized to
  1464. JSON.
  1465. */
  1466. toJSON() {
  1467. return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };
  1468. }
  1469. /**
  1470. Create a selection from a JSON representation.
  1471. */
  1472. static fromJSON(json) {
  1473. if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length)
  1474. throw new RangeError("Invalid JSON representation for EditorSelection");
  1475. return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);
  1476. }
  1477. /**
  1478. Create a selection holding a single range.
  1479. */
  1480. static single(anchor, head = anchor) {
  1481. return new EditorSelection([EditorSelection.range(anchor, head)], 0);
  1482. }
  1483. /**
  1484. Sort and merge the given set of ranges, creating a valid
  1485. selection.
  1486. */
  1487. static create(ranges, mainIndex = 0) {
  1488. if (ranges.length == 0)
  1489. throw new RangeError("A selection needs at least one range");
  1490. for (let pos = 0, i = 0; i < ranges.length; i++) {
  1491. let range = ranges[i];
  1492. if (range.empty ? range.from <= pos : range.from < pos)
  1493. return EditorSelection.normalized(ranges.slice(), mainIndex);
  1494. pos = range.to;
  1495. }
  1496. return new EditorSelection(ranges, mainIndex);
  1497. }
  1498. /**
  1499. Create a cursor selection range at the given position. You can
  1500. safely ignore the optional arguments in most situations.
  1501. */
  1502. static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
  1503. return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 4 /* AssocBefore */ : 8 /* AssocAfter */) |
  1504. (bidiLevel == null ? 3 : Math.min(2, bidiLevel)) |
  1505. ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */));
  1506. }
  1507. /**
  1508. Create a selection range.
  1509. */
  1510. static range(anchor, head, goalColumn) {
  1511. let goal = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 33554431 /* NoGoalColumn */) << 5 /* GoalColumnOffset */;
  1512. return head < anchor ? SelectionRange.create(head, anchor, 16 /* Inverted */ | goal | 8 /* AssocAfter */)
  1513. : SelectionRange.create(anchor, head, goal | (head > anchor ? 4 /* AssocBefore */ : 0));
  1514. }
  1515. /**
  1516. @internal
  1517. */
  1518. static normalized(ranges, mainIndex = 0) {
  1519. let main = ranges[mainIndex];
  1520. ranges.sort((a, b) => a.from - b.from);
  1521. mainIndex = ranges.indexOf(main);
  1522. for (let i = 1; i < ranges.length; i++) {
  1523. let range = ranges[i], prev = ranges[i - 1];
  1524. if (range.empty ? range.from <= prev.to : range.from < prev.to) {
  1525. let from = prev.from, to = Math.max(range.to, prev.to);
  1526. if (i <= mainIndex)
  1527. mainIndex--;
  1528. ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
  1529. }
  1530. }
  1531. return new EditorSelection(ranges, mainIndex);
  1532. }
  1533. }
  1534. function checkSelection(selection, docLength) {
  1535. for (let range of selection.ranges)
  1536. if (range.to > docLength)
  1537. throw new RangeError("Selection points outside of document");
  1538. }
  1539. let nextID = 0;
  1540. /**
  1541. A facet is a labeled value that is associated with an editor
  1542. state. It takes inputs from any number of extensions, and combines
  1543. those into a single output value.
  1544. Examples of uses of facets are the [tab
  1545. size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
  1546. attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
  1547. listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
  1548. */
  1549. class Facet {
  1550. constructor(
  1551. /**
  1552. @internal
  1553. */
  1554. combine,
  1555. /**
  1556. @internal
  1557. */
  1558. compareInput,
  1559. /**
  1560. @internal
  1561. */
  1562. compare, isStatic, enables) {
  1563. this.combine = combine;
  1564. this.compareInput = compareInput;
  1565. this.compare = compare;
  1566. this.isStatic = isStatic;
  1567. /**
  1568. @internal
  1569. */
  1570. this.id = nextID++;
  1571. this.default = combine([]);
  1572. this.extensions = typeof enables == "function" ? enables(this) : enables;
  1573. }
  1574. /**
  1575. Define a new facet.
  1576. */
  1577. static define(config = {}) {
  1578. return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables);
  1579. }
  1580. /**
  1581. Returns an extension that adds the given value to this facet.
  1582. */
  1583. of(value) {
  1584. return new FacetProvider([], this, 0 /* Static */, value);
  1585. }
  1586. /**
  1587. Create an extension that computes a value for the facet from a
  1588. state. You must take care to declare the parts of the state that
  1589. this value depends on, since your function is only called again
  1590. for a new state when one of those parts changed.
  1591. In cases where your value depends only on a single field, you'll
  1592. want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
  1593. */
  1594. compute(deps, get) {
  1595. if (this.isStatic)
  1596. throw new Error("Can't compute a static facet");
  1597. return new FacetProvider(deps, this, 1 /* Single */, get);
  1598. }
  1599. /**
  1600. Create an extension that computes zero or more values for this
  1601. facet from a state.
  1602. */
  1603. computeN(deps, get) {
  1604. if (this.isStatic)
  1605. throw new Error("Can't compute a static facet");
  1606. return new FacetProvider(deps, this, 2 /* Multi */, get);
  1607. }
  1608. from(field, get) {
  1609. if (!get)
  1610. get = x => x;
  1611. return this.compute([field], state => get(state.field(field)));
  1612. }
  1613. }
  1614. function sameArray(a, b) {
  1615. return a == b || a.length == b.length && a.every((e, i) => e === b[i]);
  1616. }
  1617. class FacetProvider {
  1618. constructor(dependencies, facet, type, value) {
  1619. this.dependencies = dependencies;
  1620. this.facet = facet;
  1621. this.type = type;
  1622. this.value = value;
  1623. this.id = nextID++;
  1624. }
  1625. dynamicSlot(addresses) {
  1626. var _a;
  1627. let getter = this.value;
  1628. let compare = this.facet.compareInput;
  1629. let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Multi */;
  1630. let depDoc = false, depSel = false, depAddrs = [];
  1631. for (let dep of this.dependencies) {
  1632. if (dep == "doc")
  1633. depDoc = true;
  1634. else if (dep == "selection")
  1635. depSel = true;
  1636. else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)
  1637. depAddrs.push(addresses[dep.id]);
  1638. }
  1639. return {
  1640. create(state) {
  1641. state.values[idx] = getter(state);
  1642. return 1 /* Changed */;
  1643. },
  1644. update(state, tr) {
  1645. if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {
  1646. let newVal = getter(state);
  1647. if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {
  1648. state.values[idx] = newVal;
  1649. return 1 /* Changed */;
  1650. }
  1651. }
  1652. return 0;
  1653. },
  1654. reconfigure: (state, oldState) => {
  1655. let newVal = getter(state);
  1656. let oldAddr = oldState.config.address[id];
  1657. if (oldAddr != null) {
  1658. let oldVal = getAddr(oldState, oldAddr);
  1659. if (this.dependencies.every(dep => {
  1660. return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :
  1661. dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
  1662. }) || (multi ? compareArray(newVal, oldVal, compare) : compare(newVal, oldVal))) {
  1663. state.values[idx] = oldVal;
  1664. return 0;
  1665. }
  1666. }
  1667. state.values[idx] = newVal;
  1668. return 1 /* Changed */;
  1669. }
  1670. };
  1671. }
  1672. }
  1673. function compareArray(a, b, compare) {
  1674. if (a.length != b.length)
  1675. return false;
  1676. for (let i = 0; i < a.length; i++)
  1677. if (!compare(a[i], b[i]))
  1678. return false;
  1679. return true;
  1680. }
  1681. function ensureAll(state, addrs) {
  1682. let changed = false;
  1683. for (let addr of addrs)
  1684. if (ensureAddr(state, addr) & 1 /* Changed */)
  1685. changed = true;
  1686. return changed;
  1687. }
  1688. function dynamicFacetSlot(addresses, facet, providers) {
  1689. let providerAddrs = providers.map(p => addresses[p.id]);
  1690. let providerTypes = providers.map(p => p.type);
  1691. let dynamic = providerAddrs.filter(p => !(p & 1));
  1692. let idx = addresses[facet.id] >> 1;
  1693. function get(state) {
  1694. let values = [];
  1695. for (let i = 0; i < providerAddrs.length; i++) {
  1696. let value = getAddr(state, providerAddrs[i]);
  1697. if (providerTypes[i] == 2 /* Multi */)
  1698. for (let val of value)
  1699. values.push(val);
  1700. else
  1701. values.push(value);
  1702. }
  1703. return facet.combine(values);
  1704. }
  1705. return {
  1706. create(state) {
  1707. for (let addr of providerAddrs)
  1708. ensureAddr(state, addr);
  1709. state.values[idx] = get(state);
  1710. return 1 /* Changed */;
  1711. },
  1712. update(state, tr) {
  1713. if (!ensureAll(state, dynamic))
  1714. return 0;
  1715. let value = get(state);
  1716. if (facet.compare(value, state.values[idx]))
  1717. return 0;
  1718. state.values[idx] = value;
  1719. return 1 /* Changed */;
  1720. },
  1721. reconfigure(state, oldState) {
  1722. let depChanged = ensureAll(state, providerAddrs);
  1723. let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);
  1724. if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
  1725. state.values[idx] = oldValue;
  1726. return 0;
  1727. }
  1728. let value = get(state);
  1729. if (facet.compare(value, oldValue)) {
  1730. state.values[idx] = oldValue;
  1731. return 0;
  1732. }
  1733. state.values[idx] = value;
  1734. return 1 /* Changed */;
  1735. }
  1736. };
  1737. }
  1738. const initField = Facet.define({ static: true });
  1739. /**
  1740. Fields can store additional information in an editor state, and
  1741. keep it in sync with the rest of the state.
  1742. */
  1743. class StateField {
  1744. constructor(
  1745. /**
  1746. @internal
  1747. */
  1748. id, createF, updateF, compareF,
  1749. /**
  1750. @internal
  1751. */
  1752. spec) {
  1753. this.id = id;
  1754. this.createF = createF;
  1755. this.updateF = updateF;
  1756. this.compareF = compareF;
  1757. this.spec = spec;
  1758. /**
  1759. @internal
  1760. */
  1761. this.provides = undefined;
  1762. }
  1763. /**
  1764. Define a state field.
  1765. */
  1766. static define(config) {
  1767. let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);
  1768. if (config.provide)
  1769. field.provides = config.provide(field);
  1770. return field;
  1771. }
  1772. create(state) {
  1773. let init = state.facet(initField).find(i => i.field == this);
  1774. return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
  1775. }
  1776. /**
  1777. @internal
  1778. */
  1779. slot(addresses) {
  1780. let idx = addresses[this.id] >> 1;
  1781. return {
  1782. create: (state) => {
  1783. state.values[idx] = this.create(state);
  1784. return 1 /* Changed */;
  1785. },
  1786. update: (state, tr) => {
  1787. let oldVal = state.values[idx];
  1788. let value = this.updateF(oldVal, tr);
  1789. if (this.compareF(oldVal, value))
  1790. return 0;
  1791. state.values[idx] = value;
  1792. return 1 /* Changed */;
  1793. },
  1794. reconfigure: (state, oldState) => {
  1795. if (oldState.config.address[this.id] != null) {
  1796. state.values[idx] = oldState.field(this);
  1797. return 0;
  1798. }
  1799. state.values[idx] = this.create(state);
  1800. return 1 /* Changed */;
  1801. }
  1802. };
  1803. }
  1804. /**
  1805. Returns an extension that enables this field and overrides the
  1806. way it is initialized. Can be useful when you need to provide a
  1807. non-default starting value for the field.
  1808. */
  1809. init(create) {
  1810. return [this, initField.of({ field: this, create })];
  1811. }
  1812. /**
  1813. State field instances can be used as
  1814. [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
  1815. given state.
  1816. */
  1817. get extension() { return this; }
  1818. }
  1819. const Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };
  1820. function prec(value) {
  1821. return (ext) => new PrecExtension(ext, value);
  1822. }
  1823. /**
  1824. By default extensions are registered in the order they are found
  1825. in the flattened form of nested array that was provided.
  1826. Individual extension values can be assigned a precedence to
  1827. override this. Extensions that do not have a precedence set get
  1828. the precedence of the nearest parent with a precedence, or
  1829. [`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
  1830. final ordering of extensions is determined by first sorting by
  1831. precedence and then by order within each precedence.
  1832. */
  1833. const Prec = {
  1834. /**
  1835. The highest precedence level, for extensions that should end up
  1836. near the start of the precedence ordering.
  1837. */
  1838. highest: prec(Prec_.highest),
  1839. /**
  1840. A higher-than-default precedence, for extensions that should
  1841. come before those with default precedence.
  1842. */
  1843. high: prec(Prec_.high),
  1844. /**
  1845. The default precedence, which is also used for extensions
  1846. without an explicit precedence.
  1847. */
  1848. default: prec(Prec_.default),
  1849. /**
  1850. A lower-than-default precedence.
  1851. */
  1852. low: prec(Prec_.low),
  1853. /**
  1854. The lowest precedence level. Meant for things that should end up
  1855. near the end of the extension order.
  1856. */
  1857. lowest: prec(Prec_.lowest)
  1858. };
  1859. class PrecExtension {
  1860. constructor(inner, prec) {
  1861. this.inner = inner;
  1862. this.prec = prec;
  1863. }
  1864. }
  1865. /**
  1866. Extension compartments can be used to make a configuration
  1867. dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
  1868. configuration in a compartment, you can later
  1869. [replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
  1870. transaction.
  1871. */
  1872. class Compartment {
  1873. /**
  1874. Create an instance of this compartment to add to your [state
  1875. configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
  1876. */
  1877. of(ext) { return new CompartmentInstance(this, ext); }
  1878. /**
  1879. Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
  1880. reconfigures this compartment.
  1881. */
  1882. reconfigure(content) {
  1883. return Compartment.reconfigure.of({ compartment: this, extension: content });
  1884. }
  1885. /**
  1886. Get the current content of the compartment in the state, or
  1887. `undefined` if it isn't present.
  1888. */
  1889. get(state) {
  1890. return state.config.compartments.get(this);
  1891. }
  1892. }
  1893. class CompartmentInstance {
  1894. constructor(compartment, inner) {
  1895. this.compartment = compartment;
  1896. this.inner = inner;
  1897. }
  1898. }
  1899. class Configuration {
  1900. constructor(base, compartments, dynamicSlots, address, staticValues, facets) {
  1901. this.base = base;
  1902. this.compartments = compartments;
  1903. this.dynamicSlots = dynamicSlots;
  1904. this.address = address;
  1905. this.staticValues = staticValues;
  1906. this.facets = facets;
  1907. this.statusTemplate = [];
  1908. while (this.statusTemplate.length < dynamicSlots.length)
  1909. this.statusTemplate.push(0 /* Unresolved */);
  1910. }
  1911. staticFacet(facet) {
  1912. let addr = this.address[facet.id];
  1913. return addr == null ? facet.default : this.staticValues[addr >> 1];
  1914. }
  1915. static resolve(base, compartments, oldState) {
  1916. let fields = [];
  1917. let facets = Object.create(null);
  1918. let newCompartments = new Map();
  1919. for (let ext of flatten(base, compartments, newCompartments)) {
  1920. if (ext instanceof StateField)
  1921. fields.push(ext);
  1922. else
  1923. (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
  1924. }
  1925. let address = Object.create(null);
  1926. let staticValues = [];
  1927. let dynamicSlots = [];
  1928. for (let field of fields) {
  1929. address[field.id] = dynamicSlots.length << 1;
  1930. dynamicSlots.push(a => field.slot(a));
  1931. }
  1932. let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
  1933. for (let id in facets) {
  1934. let providers = facets[id], facet = providers[0].facet;
  1935. let oldProviders = oldFacets && oldFacets[id] || [];
  1936. if (providers.every(p => p.type == 0 /* Static */)) {
  1937. address[facet.id] = (staticValues.length << 1) | 1;
  1938. if (sameArray(oldProviders, providers)) {
  1939. staticValues.push(oldState.facet(facet));
  1940. }
  1941. else {
  1942. let value = facet.combine(providers.map(p => p.value));
  1943. staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
  1944. }
  1945. }
  1946. else {
  1947. for (let p of providers) {
  1948. if (p.type == 0 /* Static */) {
  1949. address[p.id] = (staticValues.length << 1) | 1;
  1950. staticValues.push(p.value);
  1951. }
  1952. else {
  1953. address[p.id] = dynamicSlots.length << 1;
  1954. dynamicSlots.push(a => p.dynamicSlot(a));
  1955. }
  1956. }
  1957. address[facet.id] = dynamicSlots.length << 1;
  1958. dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
  1959. }
  1960. }
  1961. let dynamic = dynamicSlots.map(f => f(address));
  1962. return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);
  1963. }
  1964. }
  1965. function flatten(extension, compartments, newCompartments) {
  1966. let result = [[], [], [], [], []];
  1967. let seen = new Map();
  1968. function inner(ext, prec) {
  1969. let known = seen.get(ext);
  1970. if (known != null) {
  1971. if (known <= prec)
  1972. return;
  1973. let found = result[known].indexOf(ext);
  1974. if (found > -1)
  1975. result[known].splice(found, 1);
  1976. if (ext instanceof CompartmentInstance)
  1977. newCompartments.delete(ext.compartment);
  1978. }
  1979. seen.set(ext, prec);
  1980. if (Array.isArray(ext)) {
  1981. for (let e of ext)
  1982. inner(e, prec);
  1983. }
  1984. else if (ext instanceof CompartmentInstance) {
  1985. if (newCompartments.has(ext.compartment))
  1986. throw new RangeError(`Duplicate use of compartment in extensions`);
  1987. let content = compartments.get(ext.compartment) || ext.inner;
  1988. newCompartments.set(ext.compartment, content);
  1989. inner(content, prec);
  1990. }
  1991. else if (ext instanceof PrecExtension) {
  1992. inner(ext.inner, ext.prec);
  1993. }
  1994. else if (ext instanceof StateField) {
  1995. result[prec].push(ext);
  1996. if (ext.provides)
  1997. inner(ext.provides, prec);
  1998. }
  1999. else if (ext instanceof FacetProvider) {
  2000. result[prec].push(ext);
  2001. if (ext.facet.extensions)
  2002. inner(ext.facet.extensions, prec);
  2003. }
  2004. else {
  2005. let content = ext.extension;
  2006. if (!content)
  2007. throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
  2008. inner(content, prec);
  2009. }
  2010. }
  2011. inner(extension, Prec_.default);
  2012. return result.reduce((a, b) => a.concat(b));
  2013. }
  2014. function ensureAddr(state, addr) {
  2015. if (addr & 1)
  2016. return 2 /* Computed */;
  2017. let idx = addr >> 1;
  2018. let status = state.status[idx];
  2019. if (status == 4 /* Computing */)
  2020. throw new Error("Cyclic dependency between fields and/or facets");
  2021. if (status & 2 /* Computed */)
  2022. return status;
  2023. state.status[idx] = 4 /* Computing */;
  2024. let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
  2025. return state.status[idx] = 2 /* Computed */ | changed;
  2026. }
  2027. function getAddr(state, addr) {
  2028. return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
  2029. }
  2030. const languageData = Facet.define();
  2031. const allowMultipleSelections = Facet.define({
  2032. combine: values => values.some(v => v),
  2033. static: true
  2034. });
  2035. const lineSeparator = Facet.define({
  2036. combine: values => values.length ? values[0] : undefined,
  2037. static: true
  2038. });
  2039. const changeFilter = Facet.define();
  2040. const transactionFilter = Facet.define();
  2041. const transactionExtender = Facet.define();
  2042. const readOnly = Facet.define({
  2043. combine: values => values.length ? values[0] : false
  2044. });
  2045. /**
  2046. Annotations are tagged values that are used to add metadata to
  2047. transactions in an extensible way. They should be used to model
  2048. things that effect the entire transaction (such as its [time
  2049. stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
  2050. [origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
  2051. _alongside_ the other changes made by the transaction, [state
  2052. effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
  2053. */
  2054. class Annotation {
  2055. /**
  2056. @internal
  2057. */
  2058. constructor(
  2059. /**
  2060. The annotation type.
  2061. */
  2062. type,
  2063. /**
  2064. The value of this annotation.
  2065. */
  2066. value) {
  2067. this.type = type;
  2068. this.value = value;
  2069. }
  2070. /**
  2071. Define a new type of annotation.
  2072. */
  2073. static define() { return new AnnotationType(); }
  2074. }
  2075. /**
  2076. Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
  2077. */
  2078. class AnnotationType {
  2079. /**
  2080. Create an instance of this annotation.
  2081. */
  2082. of(value) { return new Annotation(this, value); }
  2083. }
  2084. /**
  2085. Representation of a type of state effect. Defined with
  2086. [`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
  2087. */
  2088. class StateEffectType {
  2089. /**
  2090. @internal
  2091. */
  2092. constructor(
  2093. // The `any` types in these function types are there to work
  2094. // around TypeScript issue #37631, where the type guard on
  2095. // `StateEffect.is` mysteriously stops working when these properly
  2096. // have type `Value`.
  2097. /**
  2098. @internal
  2099. */
  2100. map) {
  2101. this.map = map;
  2102. }
  2103. /**
  2104. Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
  2105. type.
  2106. */
  2107. of(value) { return new StateEffect(this, value); }
  2108. }
  2109. /**
  2110. State effects can be used to represent additional effects
  2111. associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
  2112. are often useful to model changes to custom [state
  2113. fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
  2114. document or selection changes.
  2115. */
  2116. class StateEffect {
  2117. /**
  2118. @internal
  2119. */
  2120. constructor(
  2121. /**
  2122. @internal
  2123. */
  2124. type,
  2125. /**
  2126. The value of this effect.
  2127. */
  2128. value) {
  2129. this.type = type;
  2130. this.value = value;
  2131. }
  2132. /**
  2133. Map this effect through a position mapping. Will return
  2134. `undefined` when that ends up deleting the effect.
  2135. */
  2136. map(mapping) {
  2137. let mapped = this.type.map(this.value, mapping);
  2138. return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);
  2139. }
  2140. /**
  2141. Tells you whether this effect object is of a given
  2142. [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
  2143. */
  2144. is(type) { return this.type == type; }
  2145. /**
  2146. Define a new effect type. The type parameter indicates the type
  2147. of values that his effect holds.
  2148. */
  2149. static define(spec = {}) {
  2150. return new StateEffectType(spec.map || (v => v));
  2151. }
  2152. /**
  2153. Map an array of effects through a change set.
  2154. */
  2155. static mapEffects(effects, mapping) {
  2156. if (!effects.length)
  2157. return effects;
  2158. let result = [];
  2159. for (let effect of effects) {
  2160. let mapped = effect.map(mapping);
  2161. if (mapped)
  2162. result.push(mapped);
  2163. }
  2164. return result;
  2165. }
  2166. }
  2167. /**
  2168. This effect can be used to reconfigure the root extensions of
  2169. the editor. Doing this will discard any extensions
  2170. [appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
  2171. the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
  2172. compartments.
  2173. */
  2174. StateEffect.reconfigure = StateEffect.define();
  2175. /**
  2176. Append extensions to the top-level configuration of the editor.
  2177. */
  2178. StateEffect.appendConfig = StateEffect.define();
  2179. /**
  2180. Changes to the editor state are grouped into transactions.
  2181. Typically, a user action creates a single transaction, which may
  2182. contain any number of document changes, may change the selection,
  2183. or have other effects. Create a transaction by calling
  2184. [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
  2185. dispatch one by calling
  2186. [`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
  2187. */
  2188. class Transaction {
  2189. constructor(
  2190. /**
  2191. The state from which the transaction starts.
  2192. */
  2193. startState,
  2194. /**
  2195. The document changes made by this transaction.
  2196. */
  2197. changes,
  2198. /**
  2199. The selection set by this transaction, or undefined if it
  2200. doesn't explicitly set a selection.
  2201. */
  2202. selection,
  2203. /**
  2204. The effects added to the transaction.
  2205. */
  2206. effects,
  2207. /**
  2208. @internal
  2209. */
  2210. annotations,
  2211. /**
  2212. Whether the selection should be scrolled into view after this
  2213. transaction is dispatched.
  2214. */
  2215. scrollIntoView) {
  2216. this.startState = startState;
  2217. this.changes = changes;
  2218. this.selection = selection;
  2219. this.effects = effects;
  2220. this.annotations = annotations;
  2221. this.scrollIntoView = scrollIntoView;
  2222. /**
  2223. @internal
  2224. */
  2225. this._doc = null;
  2226. /**
  2227. @internal
  2228. */
  2229. this._state = null;
  2230. if (selection)
  2231. checkSelection(selection, changes.newLength);
  2232. if (!annotations.some((a) => a.type == Transaction.time))
  2233. this.annotations = annotations.concat(Transaction.time.of(Date.now()));
  2234. }
  2235. /**
  2236. @internal
  2237. */
  2238. static create(startState, changes, selection, effects, annotations, scrollIntoView) {
  2239. return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);
  2240. }
  2241. /**
  2242. The new document produced by the transaction. Contrary to
  2243. [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
  2244. force the entire new state to be computed right away, so it is
  2245. recommended that [transaction
  2246. filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
  2247. when they need to look at the new document.
  2248. */
  2249. get newDoc() {
  2250. return this._doc || (this._doc = this.changes.apply(this.startState.doc));
  2251. }
  2252. /**
  2253. The new selection produced by the transaction. If
  2254. [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
  2255. this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
  2256. current selection through the changes made by the transaction.
  2257. */
  2258. get newSelection() {
  2259. return this.selection || this.startState.selection.map(this.changes);
  2260. }
  2261. /**
  2262. The new state created by the transaction. Computed on demand
  2263. (but retained for subsequent access), so it is recommended not to
  2264. access it in [transaction
  2265. filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
  2266. */
  2267. get state() {
  2268. if (!this._state)
  2269. this.startState.applyTransaction(this);
  2270. return this._state;
  2271. }
  2272. /**
  2273. Get the value of the given annotation type, if any.
  2274. */
  2275. annotation(type) {
  2276. for (let ann of this.annotations)
  2277. if (ann.type == type)
  2278. return ann.value;
  2279. return undefined;
  2280. }
  2281. /**
  2282. Indicates whether the transaction changed the document.
  2283. */
  2284. get docChanged() { return !this.changes.empty; }
  2285. /**
  2286. Indicates whether this transaction reconfigures the state
  2287. (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
  2288. with a top-level configuration
  2289. [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
  2290. */
  2291. get reconfigured() { return this.startState.config != this.state.config; }
  2292. /**
  2293. Returns true if the transaction has a [user
  2294. event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
  2295. or more specific than `event`. For example, if the transaction
  2296. has `"select.pointer"` as user event, `"select"` and
  2297. `"select.pointer"` will match it.
  2298. */
  2299. isUserEvent(event) {
  2300. let e = this.annotation(Transaction.userEvent);
  2301. return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
  2302. }
  2303. }
  2304. /**
  2305. Annotation used to store transaction timestamps. Automatically
  2306. added to every transaction, holding `Date.now()`.
  2307. */
  2308. Transaction.time = Annotation.define();
  2309. /**
  2310. Annotation used to associate a transaction with a user interface
  2311. event. Holds a string identifying the event, using a
  2312. dot-separated format to support attaching more specific
  2313. information. The events used by the core libraries are:
  2314. - `"input"` when content is entered
  2315. - `"input.type"` for typed input
  2316. - `"input.type.compose"` for composition
  2317. - `"input.paste"` for pasted input
  2318. - `"input.drop"` when adding content with drag-and-drop
  2319. - `"input.complete"` when autocompleting
  2320. - `"delete"` when the user deletes content
  2321. - `"delete.selection"` when deleting the selection
  2322. - `"delete.forward"` when deleting forward from the selection
  2323. - `"delete.backward"` when deleting backward from the selection
  2324. - `"delete.cut"` when cutting to the clipboard
  2325. - `"move"` when content is moved
  2326. - `"move.drop"` when content is moved within the editor through drag-and-drop
  2327. - `"select"` when explicitly changing the selection
  2328. - `"select.pointer"` when selecting with a mouse or other pointing device
  2329. - `"undo"` and `"redo"` for history actions
  2330. Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
  2331. whether the annotation matches a given event.
  2332. */
  2333. Transaction.userEvent = Annotation.define();
  2334. /**
  2335. Annotation indicating whether a transaction should be added to
  2336. the undo history or not.
  2337. */
  2338. Transaction.addToHistory = Annotation.define();
  2339. /**
  2340. Annotation indicating (when present and true) that a transaction
  2341. represents a change made by some other actor, not the user. This
  2342. is used, for example, to tag other people's changes in
  2343. collaborative editing.
  2344. */
  2345. Transaction.remote = Annotation.define();
  2346. function joinRanges(a, b) {
  2347. let result = [];
  2348. for (let iA = 0, iB = 0;;) {
  2349. let from, to;
  2350. if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
  2351. from = a[iA++];
  2352. to = a[iA++];
  2353. }
  2354. else if (iB < b.length) {
  2355. from = b[iB++];
  2356. to = b[iB++];
  2357. }
  2358. else
  2359. return result;
  2360. if (!result.length || result[result.length - 1] < from)
  2361. result.push(from, to);
  2362. else if (result[result.length - 1] < to)
  2363. result[result.length - 1] = to;
  2364. }
  2365. }
  2366. function mergeTransaction(a, b, sequential) {
  2367. var _a;
  2368. let mapForA, mapForB, changes;
  2369. if (sequential) {
  2370. mapForA = b.changes;
  2371. mapForB = ChangeSet.empty(b.changes.length);
  2372. changes = a.changes.compose(b.changes);
  2373. }
  2374. else {
  2375. mapForA = b.changes.map(a.changes);
  2376. mapForB = a.changes.mapDesc(b.changes, true);
  2377. changes = a.changes.compose(mapForA);
  2378. }
  2379. return {
  2380. changes,
  2381. selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),
  2382. effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
  2383. annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
  2384. scrollIntoView: a.scrollIntoView || b.scrollIntoView
  2385. };
  2386. }
  2387. function resolveTransactionInner(state, spec, docSize) {
  2388. let sel = spec.selection, annotations = asArray(spec.annotations);
  2389. if (spec.userEvent)
  2390. annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
  2391. return {
  2392. changes: spec.changes instanceof ChangeSet ? spec.changes
  2393. : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),
  2394. selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
  2395. effects: asArray(spec.effects),
  2396. annotations,
  2397. scrollIntoView: !!spec.scrollIntoView
  2398. };
  2399. }
  2400. function resolveTransaction(state, specs, filter) {
  2401. let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
  2402. if (specs.length && specs[0].filter === false)
  2403. filter = false;
  2404. for (let i = 1; i < specs.length; i++) {
  2405. if (specs[i].filter === false)
  2406. filter = false;
  2407. let seq = !!specs[i].sequential;
  2408. s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);
  2409. }
  2410. let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
  2411. return extendTransaction(filter ? filterTransaction(tr) : tr);
  2412. }
  2413. // Finish a transaction by applying filters if necessary.
  2414. function filterTransaction(tr) {
  2415. let state = tr.startState;
  2416. // Change filters
  2417. let result = true;
  2418. for (let filter of state.facet(changeFilter)) {
  2419. let value = filter(tr);
  2420. if (value === false) {
  2421. result = false;
  2422. break;
  2423. }
  2424. if (Array.isArray(value))
  2425. result = result === true ? value : joinRanges(result, value);
  2426. }
  2427. if (result !== true) {
  2428. let changes, back;
  2429. if (result === false) {
  2430. back = tr.changes.invertedDesc;
  2431. changes = ChangeSet.empty(state.doc.length);
  2432. }
  2433. else {
  2434. let filtered = tr.changes.filter(result);
  2435. changes = filtered.changes;
  2436. back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
  2437. }
  2438. tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
  2439. }
  2440. // Transaction filters
  2441. let filters = state.facet(transactionFilter);
  2442. for (let i = filters.length - 1; i >= 0; i--) {
  2443. let filtered = filters[i](tr);
  2444. if (filtered instanceof Transaction)
  2445. tr = filtered;
  2446. else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)
  2447. tr = filtered[0];
  2448. else
  2449. tr = resolveTransaction(state, asArray(filtered), false);
  2450. }
  2451. return tr;
  2452. }
  2453. function extendTransaction(tr) {
  2454. let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;
  2455. for (let i = extenders.length - 1; i >= 0; i--) {
  2456. let extension = extenders[i](tr);
  2457. if (extension && Object.keys(extension).length)
  2458. spec = mergeTransaction(tr, resolveTransactionInner(state, extension, tr.changes.newLength), true);
  2459. }
  2460. return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
  2461. }
  2462. const none = [];
  2463. function asArray(value) {
  2464. return value == null ? none : Array.isArray(value) ? value : [value];
  2465. }
  2466. /**
  2467. The categories produced by a [character
  2468. categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
  2469. do things like selecting by word.
  2470. */
  2471. exports.CharCategory = void 0;
  2472. (function (CharCategory) {
  2473. /**
  2474. Word characters.
  2475. */
  2476. CharCategory[CharCategory["Word"] = 0] = "Word";
  2477. /**
  2478. Whitespace.
  2479. */
  2480. CharCategory[CharCategory["Space"] = 1] = "Space";
  2481. /**
  2482. Anything else.
  2483. */
  2484. CharCategory[CharCategory["Other"] = 2] = "Other";
  2485. })(exports.CharCategory || (exports.CharCategory = {}));
  2486. const nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  2487. let wordChar;
  2488. try {
  2489. wordChar = new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
  2490. }
  2491. catch (_) { }
  2492. function hasWordChar(str) {
  2493. if (wordChar)
  2494. return wordChar.test(str);
  2495. for (let i = 0; i < str.length; i++) {
  2496. let ch = str[i];
  2497. if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))
  2498. return true;
  2499. }
  2500. return false;
  2501. }
  2502. function makeCategorizer(wordChars) {
  2503. return (char) => {
  2504. if (!/\S/.test(char))
  2505. return exports.CharCategory.Space;
  2506. if (hasWordChar(char))
  2507. return exports.CharCategory.Word;
  2508. for (let i = 0; i < wordChars.length; i++)
  2509. if (char.indexOf(wordChars[i]) > -1)
  2510. return exports.CharCategory.Word;
  2511. return exports.CharCategory.Other;
  2512. };
  2513. }
  2514. /**
  2515. The editor state class is a persistent (immutable) data structure.
  2516. To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
  2517. [transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
  2518. instance, without modifying the original object.
  2519. As such, _never_ mutate properties of a state directly. That'll
  2520. just break things.
  2521. */
  2522. class EditorState {
  2523. constructor(
  2524. /**
  2525. @internal
  2526. */
  2527. config,
  2528. /**
  2529. The current document.
  2530. */
  2531. doc,
  2532. /**
  2533. The current selection.
  2534. */
  2535. selection,
  2536. /**
  2537. @internal
  2538. */
  2539. values, computeSlot, tr) {
  2540. this.config = config;
  2541. this.doc = doc;
  2542. this.selection = selection;
  2543. this.values = values;
  2544. this.status = config.statusTemplate.slice();
  2545. this.computeSlot = computeSlot;
  2546. // Fill in the computed state immediately, so that further queries
  2547. // for it made during the update return this state
  2548. if (tr)
  2549. tr._state = this;
  2550. for (let i = 0; i < this.config.dynamicSlots.length; i++)
  2551. ensureAddr(this, i << 1);
  2552. this.computeSlot = null;
  2553. }
  2554. field(field, require = true) {
  2555. let addr = this.config.address[field.id];
  2556. if (addr == null) {
  2557. if (require)
  2558. throw new RangeError("Field is not present in this state");
  2559. return undefined;
  2560. }
  2561. ensureAddr(this, addr);
  2562. return getAddr(this, addr);
  2563. }
  2564. /**
  2565. Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
  2566. state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
  2567. can be passed. Unless
  2568. [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
  2569. [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
  2570. are assumed to start in the _current_ document (not the document
  2571. produced by previous specs), and its
  2572. [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
  2573. [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
  2574. to the document created by its _own_ changes. The resulting
  2575. transaction contains the combined effect of all the different
  2576. specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
  2577. specs take precedence over earlier ones.
  2578. */
  2579. update(...specs) {
  2580. return resolveTransaction(this, specs, true);
  2581. }
  2582. /**
  2583. @internal
  2584. */
  2585. applyTransaction(tr) {
  2586. let conf = this.config, { base, compartments } = conf;
  2587. for (let effect of tr.effects) {
  2588. if (effect.is(Compartment.reconfigure)) {
  2589. if (conf) {
  2590. compartments = new Map;
  2591. conf.compartments.forEach((val, key) => compartments.set(key, val));
  2592. conf = null;
  2593. }
  2594. compartments.set(effect.value.compartment, effect.value.extension);
  2595. }
  2596. else if (effect.is(StateEffect.reconfigure)) {
  2597. conf = null;
  2598. base = effect.value;
  2599. }
  2600. else if (effect.is(StateEffect.appendConfig)) {
  2601. conf = null;
  2602. base = asArray(base).concat(effect.value);
  2603. }
  2604. }
  2605. let startValues;
  2606. if (!conf) {
  2607. conf = Configuration.resolve(base, compartments, this);
  2608. let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);
  2609. startValues = intermediateState.values;
  2610. }
  2611. else {
  2612. startValues = tr.startState.values.slice();
  2613. }
  2614. new EditorState(conf, tr.newDoc, tr.newSelection, startValues, (state, slot) => slot.update(state, tr), tr);
  2615. }
  2616. /**
  2617. Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
  2618. replaces every selection range with the given content.
  2619. */
  2620. replaceSelection(text) {
  2621. if (typeof text == "string")
  2622. text = this.toText(text);
  2623. return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },
  2624. range: EditorSelection.cursor(range.from + text.length) }));
  2625. }
  2626. /**
  2627. Create a set of changes and a new selection by running the given
  2628. function for each range in the active selection. The function
  2629. can return an optional set of changes (in the coordinate space
  2630. of the start document), plus an updated range (in the coordinate
  2631. space of the document produced by the call's own changes). This
  2632. method will merge all the changes and ranges into a single
  2633. changeset and selection, and return it as a [transaction
  2634. spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
  2635. [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
  2636. */
  2637. changeByRange(f) {
  2638. let sel = this.selection;
  2639. let result1 = f(sel.ranges[0]);
  2640. let changes = this.changes(result1.changes), ranges = [result1.range];
  2641. let effects = asArray(result1.effects);
  2642. for (let i = 1; i < sel.ranges.length; i++) {
  2643. let result = f(sel.ranges[i]);
  2644. let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);
  2645. for (let j = 0; j < i; j++)
  2646. ranges[j] = ranges[j].map(newMapped);
  2647. let mapBy = changes.mapDesc(newChanges, true);
  2648. ranges.push(result.range.map(mapBy));
  2649. changes = changes.compose(newMapped);
  2650. effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
  2651. }
  2652. return {
  2653. changes,
  2654. selection: EditorSelection.create(ranges, sel.mainIndex),
  2655. effects
  2656. };
  2657. }
  2658. /**
  2659. Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
  2660. description, taking the state's document length and line
  2661. separator into account.
  2662. */
  2663. changes(spec = []) {
  2664. if (spec instanceof ChangeSet)
  2665. return spec;
  2666. return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
  2667. }
  2668. /**
  2669. Using the state's [line
  2670. separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
  2671. [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
  2672. */
  2673. toText(string) {
  2674. return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));
  2675. }
  2676. /**
  2677. Return the given range of the document as a string.
  2678. */
  2679. sliceDoc(from = 0, to = this.doc.length) {
  2680. return this.doc.sliceString(from, to, this.lineBreak);
  2681. }
  2682. /**
  2683. Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
  2684. */
  2685. facet(facet) {
  2686. let addr = this.config.address[facet.id];
  2687. if (addr == null)
  2688. return facet.default;
  2689. ensureAddr(this, addr);
  2690. return getAddr(this, addr);
  2691. }
  2692. /**
  2693. Convert this state to a JSON-serializable object. When custom
  2694. fields should be serialized, you can pass them in as an object
  2695. mapping property names (in the resulting object, which should
  2696. not use `doc` or `selection`) to fields.
  2697. */
  2698. toJSON(fields) {
  2699. let result = {
  2700. doc: this.sliceDoc(),
  2701. selection: this.selection.toJSON()
  2702. };
  2703. if (fields)
  2704. for (let prop in fields) {
  2705. let value = fields[prop];
  2706. if (value instanceof StateField && this.config.address[value.id] != null)
  2707. result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
  2708. }
  2709. return result;
  2710. }
  2711. /**
  2712. Deserialize a state from its JSON representation. When custom
  2713. fields should be deserialized, pass the same object you passed
  2714. to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
  2715. third argument.
  2716. */
  2717. static fromJSON(json, config = {}, fields) {
  2718. if (!json || typeof json.doc != "string")
  2719. throw new RangeError("Invalid JSON representation for EditorState");
  2720. let fieldInit = [];
  2721. if (fields)
  2722. for (let prop in fields) {
  2723. if (Object.prototype.hasOwnProperty.call(json, prop)) {
  2724. let field = fields[prop], value = json[prop];
  2725. fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
  2726. }
  2727. }
  2728. return EditorState.create({
  2729. doc: json.doc,
  2730. selection: EditorSelection.fromJSON(json.selection),
  2731. extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit
  2732. });
  2733. }
  2734. /**
  2735. Create a new state. You'll usually only need this when
  2736. initializing an editor—updated states are created by applying
  2737. transactions.
  2738. */
  2739. static create(config = {}) {
  2740. let configuration = Configuration.resolve(config.extensions || [], new Map);
  2741. let doc = config.doc instanceof Text ? config.doc
  2742. : Text.of((config.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));
  2743. let selection = !config.selection ? EditorSelection.single(0)
  2744. : config.selection instanceof EditorSelection ? config.selection
  2745. : EditorSelection.single(config.selection.anchor, config.selection.head);
  2746. checkSelection(selection, doc.length);
  2747. if (!configuration.staticFacet(allowMultipleSelections))
  2748. selection = selection.asSingle();
  2749. return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
  2750. }
  2751. /**
  2752. The size (in columns) of a tab in the document, determined by
  2753. the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
  2754. */
  2755. get tabSize() { return this.facet(EditorState.tabSize); }
  2756. /**
  2757. Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
  2758. string for this state.
  2759. */
  2760. get lineBreak() { return this.facet(EditorState.lineSeparator) || "\n"; }
  2761. /**
  2762. Returns true when the editor is
  2763. [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
  2764. */
  2765. get readOnly() { return this.facet(readOnly); }
  2766. /**
  2767. Look up a translation for the given phrase (via the
  2768. [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
  2769. original string if no translation is found.
  2770. If additional arguments are passed, they will be inserted in
  2771. place of markers like `$1` (for the first value) and `$2`, etc.
  2772. A single `$` is equivalent to `$1`, and `$$` will produce a
  2773. literal dollar sign.
  2774. */
  2775. phrase(phrase, ...insert) {
  2776. for (let map of this.facet(EditorState.phrases))
  2777. if (Object.prototype.hasOwnProperty.call(map, phrase)) {
  2778. phrase = map[phrase];
  2779. break;
  2780. }
  2781. if (insert.length)
  2782. phrase = phrase.replace(/\$(\$|\d*)/g, (m, i) => {
  2783. if (i == "$")
  2784. return "$";
  2785. let n = +(i || 1);
  2786. return !n || n > insert.length ? m : insert[n - 1];
  2787. });
  2788. return phrase;
  2789. }
  2790. /**
  2791. Find the values for a given language data field, provided by the
  2792. the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
  2793. */
  2794. languageDataAt(name, pos, side = -1) {
  2795. let values = [];
  2796. for (let provider of this.facet(languageData)) {
  2797. for (let result of provider(this, pos, side)) {
  2798. if (Object.prototype.hasOwnProperty.call(result, name))
  2799. values.push(result[name]);
  2800. }
  2801. }
  2802. return values;
  2803. }
  2804. /**
  2805. Return a function that can categorize strings (expected to
  2806. represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
  2807. into one of:
  2808. - Word (contains an alphanumeric character or a character
  2809. explicitly listed in the local language's `"wordChars"`
  2810. language data, which should be a string)
  2811. - Space (contains only whitespace)
  2812. - Other (anything else)
  2813. */
  2814. charCategorizer(at) {
  2815. return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
  2816. }
  2817. /**
  2818. Find the word at the given position, meaning the range
  2819. containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
  2820. around it. If no word characters are adjacent to the position,
  2821. this returns null.
  2822. */
  2823. wordAt(pos) {
  2824. let { text, from, length } = this.doc.lineAt(pos);
  2825. let cat = this.charCategorizer(pos);
  2826. let start = pos - from, end = pos - from;
  2827. while (start > 0) {
  2828. let prev = findClusterBreak(text, start, false);
  2829. if (cat(text.slice(prev, start)) != exports.CharCategory.Word)
  2830. break;
  2831. start = prev;
  2832. }
  2833. while (end < length) {
  2834. let next = findClusterBreak(text, end);
  2835. if (cat(text.slice(end, next)) != exports.CharCategory.Word)
  2836. break;
  2837. end = next;
  2838. }
  2839. return start == end ? null : EditorSelection.range(start + from, end + from);
  2840. }
  2841. }
  2842. /**
  2843. A facet that, when enabled, causes the editor to allow multiple
  2844. ranges to be selected. Be careful though, because by default the
  2845. editor relies on the native DOM selection, which cannot handle
  2846. multiple selections. An extension like
  2847. [`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
  2848. secondary selections visible to the user.
  2849. */
  2850. EditorState.allowMultipleSelections = allowMultipleSelections;
  2851. /**
  2852. Configures the tab size to use in this state. The first
  2853. (highest-precedence) value of the facet is used. If no value is
  2854. given, this defaults to 4.
  2855. */
  2856. EditorState.tabSize = Facet.define({
  2857. combine: values => values.length ? values[0] : 4
  2858. });
  2859. /**
  2860. The line separator to use. By default, any of `"\n"`, `"\r\n"`
  2861. and `"\r"` is treated as a separator when splitting lines, and
  2862. lines are joined with `"\n"`.
  2863. When you configure a value here, only that precise separator
  2864. will be used, allowing you to round-trip documents through the
  2865. editor without normalizing line separators.
  2866. */
  2867. EditorState.lineSeparator = lineSeparator;
  2868. /**
  2869. This facet controls the value of the
  2870. [`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
  2871. consulted by commands and extensions that implement editing
  2872. functionality to determine whether they should apply. It
  2873. defaults to false, but when its highest-precedence value is
  2874. `true`, such functionality disables itself.
  2875. Not to be confused with
  2876. [`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
  2877. controls whether the editor's DOM is set to be editable (and
  2878. thus focusable).
  2879. */
  2880. EditorState.readOnly = readOnly;
  2881. /**
  2882. Registers translation phrases. The
  2883. [`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
  2884. all objects registered with this facet to find translations for
  2885. its argument.
  2886. */
  2887. EditorState.phrases = Facet.define({
  2888. compare(a, b) {
  2889. let kA = Object.keys(a), kB = Object.keys(b);
  2890. return kA.length == kB.length && kA.every(k => a[k] == b[k]);
  2891. }
  2892. });
  2893. /**
  2894. A facet used to register [language
  2895. data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
  2896. */
  2897. EditorState.languageData = languageData;
  2898. /**
  2899. Facet used to register change filters, which are called for each
  2900. transaction (unless explicitly
  2901. [disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
  2902. part of the transaction's changes.
  2903. Such a function can return `true` to indicate that it doesn't
  2904. want to do anything, `false` to completely stop the changes in
  2905. the transaction, or a set of ranges in which changes should be
  2906. suppressed. Such ranges are represented as an array of numbers,
  2907. with each pair of two numbers indicating the start and end of a
  2908. range. So for example `[10, 20, 100, 110]` suppresses changes
  2909. between 10 and 20, and between 100 and 110.
  2910. */
  2911. EditorState.changeFilter = changeFilter;
  2912. /**
  2913. Facet used to register a hook that gets a chance to update or
  2914. replace transaction specs before they are applied. This will
  2915. only be applied for transactions that don't have
  2916. [`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
  2917. can either return a single transaction spec (possibly the input
  2918. transaction), or an array of specs (which will be combined in
  2919. the same way as the arguments to
  2920. [`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
  2921. When possible, it is recommended to avoid accessing
  2922. [`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
  2923. since it will force creation of a state that will then be
  2924. discarded again, if the transaction is actually filtered.
  2925. (This functionality should be used with care. Indiscriminately
  2926. modifying transaction is likely to break something or degrade
  2927. the user experience.)
  2928. */
  2929. EditorState.transactionFilter = transactionFilter;
  2930. /**
  2931. This is a more limited form of
  2932. [`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
  2933. which can only add
  2934. [annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
  2935. [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
  2936. of filter runs even if the transaction has disabled regular
  2937. [filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
  2938. for effects that don't need to touch the changes or selection,
  2939. but do want to process every transaction.
  2940. Extenders run _after_ filters, when both are present.
  2941. */
  2942. EditorState.transactionExtender = transactionExtender;
  2943. Compartment.reconfigure = StateEffect.define();
  2944. /**
  2945. Utility function for combining behaviors to fill in a config
  2946. object from an array of provided configs. `defaults` should hold
  2947. default values for all optional fields in `Config`.
  2948. The function will, by default, error
  2949. when a field gets two values that aren't `===`-equal, but you can
  2950. provide combine functions per field to do something else.
  2951. */
  2952. function combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that
  2953. combine = {}) {
  2954. let result = {};
  2955. for (let config of configs)
  2956. for (let key of Object.keys(config)) {
  2957. let value = config[key], current = result[key];
  2958. if (current === undefined)
  2959. result[key] = value;
  2960. else if (current === value || value === undefined) ; // No conflict
  2961. else if (Object.hasOwnProperty.call(combine, key))
  2962. result[key] = combine[key](current, value);
  2963. else
  2964. throw new Error("Config merge conflict for field " + key);
  2965. }
  2966. for (let key in defaults)
  2967. if (result[key] === undefined)
  2968. result[key] = defaults[key];
  2969. return result;
  2970. }
  2971. /**
  2972. Each range is associated with a value, which must inherit from
  2973. this class.
  2974. */
  2975. class RangeValue {
  2976. /**
  2977. Compare this value with another value. Used when comparing
  2978. rangesets. The default implementation compares by identity.
  2979. Unless you are only creating a fixed number of unique instances
  2980. of your value type, it is a good idea to implement this
  2981. properly.
  2982. */
  2983. eq(other) { return this == other; }
  2984. /**
  2985. Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
  2986. */
  2987. range(from, to = from) { return Range.create(from, to, this); }
  2988. }
  2989. RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
  2990. RangeValue.prototype.point = false;
  2991. RangeValue.prototype.mapMode = exports.MapMode.TrackDel;
  2992. /**
  2993. A range associates a value with a range of positions.
  2994. */
  2995. class Range {
  2996. constructor(
  2997. /**
  2998. The range's start position.
  2999. */
  3000. from,
  3001. /**
  3002. Its end position.
  3003. */
  3004. to,
  3005. /**
  3006. The value associated with this range.
  3007. */
  3008. value) {
  3009. this.from = from;
  3010. this.to = to;
  3011. this.value = value;
  3012. }
  3013. /**
  3014. @internal
  3015. */
  3016. static create(from, to, value) {
  3017. return new Range(from, to, value);
  3018. }
  3019. }
  3020. function cmpRange(a, b) {
  3021. return a.from - b.from || a.value.startSide - b.value.startSide;
  3022. }
  3023. class Chunk {
  3024. constructor(from, to, value,
  3025. // Chunks are marked with the largest point that occurs
  3026. // in them (or -1 for no points), so that scans that are
  3027. // only interested in points (such as the
  3028. // heightmap-related logic) can skip range-only chunks.
  3029. maxPoint) {
  3030. this.from = from;
  3031. this.to = to;
  3032. this.value = value;
  3033. this.maxPoint = maxPoint;
  3034. }
  3035. get length() { return this.to[this.to.length - 1]; }
  3036. // Find the index of the given position and side. Use the ranges'
  3037. // `from` pos when `end == false`, `to` when `end == true`.
  3038. findIndex(pos, side, end, startAt = 0) {
  3039. let arr = end ? this.to : this.from;
  3040. for (let lo = startAt, hi = arr.length;;) {
  3041. if (lo == hi)
  3042. return lo;
  3043. let mid = (lo + hi) >> 1;
  3044. let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
  3045. if (mid == lo)
  3046. return diff >= 0 ? lo : hi;
  3047. if (diff >= 0)
  3048. hi = mid;
  3049. else
  3050. lo = mid + 1;
  3051. }
  3052. }
  3053. between(offset, from, to, f) {
  3054. for (let i = this.findIndex(from, -1000000000 /* Far */, true), e = this.findIndex(to, 1000000000 /* Far */, false, i); i < e; i++)
  3055. if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)
  3056. return false;
  3057. }
  3058. map(offset, changes) {
  3059. let value = [], from = [], to = [], newPos = -1, maxPoint = -1;
  3060. for (let i = 0; i < this.value.length; i++) {
  3061. let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;
  3062. if (curFrom == curTo) {
  3063. let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
  3064. if (mapped == null)
  3065. continue;
  3066. newFrom = newTo = mapped;
  3067. if (val.startSide != val.endSide) {
  3068. newTo = changes.mapPos(curFrom, val.endSide);
  3069. if (newTo < newFrom)
  3070. continue;
  3071. }
  3072. }
  3073. else {
  3074. newFrom = changes.mapPos(curFrom, val.startSide);
  3075. newTo = changes.mapPos(curTo, val.endSide);
  3076. if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)
  3077. continue;
  3078. }
  3079. if ((newTo - newFrom || val.endSide - val.startSide) < 0)
  3080. continue;
  3081. if (newPos < 0)
  3082. newPos = newFrom;
  3083. if (val.point)
  3084. maxPoint = Math.max(maxPoint, newTo - newFrom);
  3085. value.push(val);
  3086. from.push(newFrom - newPos);
  3087. to.push(newTo - newPos);
  3088. }
  3089. return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };
  3090. }
  3091. }
  3092. /**
  3093. A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
  3094. way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
  3095. [update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
  3096. structure.
  3097. */
  3098. class RangeSet {
  3099. constructor(
  3100. /**
  3101. @internal
  3102. */
  3103. chunkPos,
  3104. /**
  3105. @internal
  3106. */
  3107. chunk,
  3108. /**
  3109. @internal
  3110. */
  3111. nextLayer,
  3112. /**
  3113. @internal
  3114. */
  3115. maxPoint) {
  3116. this.chunkPos = chunkPos;
  3117. this.chunk = chunk;
  3118. this.nextLayer = nextLayer;
  3119. this.maxPoint = maxPoint;
  3120. }
  3121. /**
  3122. @internal
  3123. */
  3124. static create(chunkPos, chunk, nextLayer, maxPoint) {
  3125. return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
  3126. }
  3127. /**
  3128. @internal
  3129. */
  3130. get length() {
  3131. let last = this.chunk.length - 1;
  3132. return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
  3133. }
  3134. /**
  3135. The number of ranges in the set.
  3136. */
  3137. get size() {
  3138. if (this.isEmpty)
  3139. return 0;
  3140. let size = this.nextLayer.size;
  3141. for (let chunk of this.chunk)
  3142. size += chunk.value.length;
  3143. return size;
  3144. }
  3145. /**
  3146. @internal
  3147. */
  3148. chunkEnd(index) {
  3149. return this.chunkPos[index] + this.chunk[index].length;
  3150. }
  3151. /**
  3152. Update the range set, optionally adding new ranges or filtering
  3153. out existing ones.
  3154. (Note: The type parameter is just there as a kludge to work
  3155. around TypeScript variance issues that prevented `RangeSet<X>`
  3156. from being a subtype of `RangeSet<Y>` when `X` is a subtype of
  3157. `Y`.)
  3158. */
  3159. update(updateSpec) {
  3160. let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;
  3161. let filter = updateSpec.filter;
  3162. if (add.length == 0 && !filter)
  3163. return this;
  3164. if (sort)
  3165. add = add.slice().sort(cmpRange);
  3166. if (this.isEmpty)
  3167. return add.length ? RangeSet.of(add) : this;
  3168. let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];
  3169. let builder = new RangeSetBuilder();
  3170. while (cur.value || i < add.length) {
  3171. if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {
  3172. let range = add[i++];
  3173. if (!builder.addInner(range.from, range.to, range.value))
  3174. spill.push(range);
  3175. }
  3176. else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&
  3177. (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&
  3178. (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&
  3179. builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {
  3180. cur.nextChunk();
  3181. }
  3182. else {
  3183. if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {
  3184. if (!builder.addInner(cur.from, cur.to, cur.value))
  3185. spill.push(Range.create(cur.from, cur.to, cur.value));
  3186. }
  3187. cur.next();
  3188. }
  3189. }
  3190. return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty
  3191. : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));
  3192. }
  3193. /**
  3194. Map this range set through a set of changes, return the new set.
  3195. */
  3196. map(changes) {
  3197. if (changes.empty || this.isEmpty)
  3198. return this;
  3199. let chunks = [], chunkPos = [], maxPoint = -1;
  3200. for (let i = 0; i < this.chunk.length; i++) {
  3201. let start = this.chunkPos[i], chunk = this.chunk[i];
  3202. let touch = changes.touchesRange(start, start + chunk.length);
  3203. if (touch === false) {
  3204. maxPoint = Math.max(maxPoint, chunk.maxPoint);
  3205. chunks.push(chunk);
  3206. chunkPos.push(changes.mapPos(start));
  3207. }
  3208. else if (touch === true) {
  3209. let { mapped, pos } = chunk.map(start, changes);
  3210. if (mapped) {
  3211. maxPoint = Math.max(maxPoint, mapped.maxPoint);
  3212. chunks.push(mapped);
  3213. chunkPos.push(pos);
  3214. }
  3215. }
  3216. }
  3217. let next = this.nextLayer.map(changes);
  3218. return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
  3219. }
  3220. /**
  3221. Iterate over the ranges that touch the region `from` to `to`,
  3222. calling `f` for each. There is no guarantee that the ranges will
  3223. be reported in any specific order. When the callback returns
  3224. `false`, iteration stops.
  3225. */
  3226. between(from, to, f) {
  3227. if (this.isEmpty)
  3228. return;
  3229. for (let i = 0; i < this.chunk.length; i++) {
  3230. let start = this.chunkPos[i], chunk = this.chunk[i];
  3231. if (to >= start && from <= start + chunk.length &&
  3232. chunk.between(start, from - start, to - start, f) === false)
  3233. return;
  3234. }
  3235. this.nextLayer.between(from, to, f);
  3236. }
  3237. /**
  3238. Iterate over the ranges in this set, in order, including all
  3239. ranges that end at or after `from`.
  3240. */
  3241. iter(from = 0) {
  3242. return HeapCursor.from([this]).goto(from);
  3243. }
  3244. /**
  3245. @internal
  3246. */
  3247. get isEmpty() { return this.nextLayer == this; }
  3248. /**
  3249. Iterate over the ranges in a collection of sets, in order,
  3250. starting from `from`.
  3251. */
  3252. static iter(sets, from = 0) {
  3253. return HeapCursor.from(sets).goto(from);
  3254. }
  3255. /**
  3256. Iterate over two groups of sets, calling methods on `comparator`
  3257. to notify it of possible differences.
  3258. */
  3259. static compare(oldSets, newSets,
  3260. /**
  3261. This indicates how the underlying data changed between these
  3262. ranges, and is needed to synchronize the iteration. `from` and
  3263. `to` are coordinates in the _new_ space, after these changes.
  3264. */
  3265. textDiff, comparator,
  3266. /**
  3267. Can be used to ignore all non-point ranges, and points below
  3268. the given size. When -1, all ranges are compared.
  3269. */
  3270. minPointSize = -1) {
  3271. let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
  3272. let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
  3273. let sharedChunks = findSharedChunks(a, b, textDiff);
  3274. let sideA = new SpanCursor(a, sharedChunks, minPointSize);
  3275. let sideB = new SpanCursor(b, sharedChunks, minPointSize);
  3276. textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
  3277. if (textDiff.empty && textDiff.length == 0)
  3278. compare(sideA, 0, sideB, 0, 0, comparator);
  3279. }
  3280. /**
  3281. Compare the contents of two groups of range sets, returning true
  3282. if they are equivalent in the given range.
  3283. */
  3284. static eq(oldSets, newSets, from = 0, to) {
  3285. if (to == null)
  3286. to = 1000000000 /* Far */;
  3287. let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
  3288. let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
  3289. if (a.length != b.length)
  3290. return false;
  3291. if (!a.length)
  3292. return true;
  3293. let sharedChunks = findSharedChunks(a, b);
  3294. let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
  3295. for (;;) {
  3296. if (sideA.to != sideB.to ||
  3297. !sameValues(sideA.active, sideB.active) ||
  3298. sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))
  3299. return false;
  3300. if (sideA.to > to)
  3301. return true;
  3302. sideA.next();
  3303. sideB.next();
  3304. }
  3305. }
  3306. /**
  3307. Iterate over a group of range sets at the same time, notifying
  3308. the iterator about the ranges covering every given piece of
  3309. content. Returns the open count (see
  3310. [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
  3311. of the iteration.
  3312. */
  3313. static spans(sets, from, to, iterator,
  3314. /**
  3315. When given and greater than -1, only points of at least this
  3316. size are taken into account.
  3317. */
  3318. minPointSize = -1) {
  3319. let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;
  3320. let open = cursor.openStart;
  3321. for (;;) {
  3322. let curTo = Math.min(cursor.to, to);
  3323. if (cursor.point) {
  3324. iterator.point(pos, curTo, cursor.point, cursor.activeForPoint(cursor.to), open, cursor.pointRank);
  3325. open = cursor.openEnd(curTo) + (cursor.to > curTo ? 1 : 0);
  3326. }
  3327. else if (curTo > pos) {
  3328. iterator.span(pos, curTo, cursor.active, open);
  3329. open = cursor.openEnd(curTo);
  3330. }
  3331. if (cursor.to > to)
  3332. break;
  3333. pos = cursor.to;
  3334. cursor.next();
  3335. }
  3336. return open;
  3337. }
  3338. /**
  3339. Create a range set for the given range or array of ranges. By
  3340. default, this expects the ranges to be _sorted_ (by start
  3341. position and, if two start at the same position,
  3342. `value.startSide`). You can pass `true` as second argument to
  3343. cause the method to sort them.
  3344. */
  3345. static of(ranges, sort = false) {
  3346. let build = new RangeSetBuilder();
  3347. for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges)
  3348. build.add(range.from, range.to, range.value);
  3349. return build.finish();
  3350. }
  3351. }
  3352. /**
  3353. The empty set of ranges.
  3354. */
  3355. RangeSet.empty = new RangeSet([], [], null, -1);
  3356. function lazySort(ranges) {
  3357. if (ranges.length > 1)
  3358. for (let prev = ranges[0], i = 1; i < ranges.length; i++) {
  3359. let cur = ranges[i];
  3360. if (cmpRange(prev, cur) > 0)
  3361. return ranges.slice().sort(cmpRange);
  3362. prev = cur;
  3363. }
  3364. return ranges;
  3365. }
  3366. RangeSet.empty.nextLayer = RangeSet.empty;
  3367. /**
  3368. A range set builder is a data structure that helps build up a
  3369. [range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
  3370. an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
  3371. */
  3372. class RangeSetBuilder {
  3373. /**
  3374. Create an empty builder.
  3375. */
  3376. constructor() {
  3377. this.chunks = [];
  3378. this.chunkPos = [];
  3379. this.chunkStart = -1;
  3380. this.last = null;
  3381. this.lastFrom = -1000000000 /* Far */;
  3382. this.lastTo = -1000000000 /* Far */;
  3383. this.from = [];
  3384. this.to = [];
  3385. this.value = [];
  3386. this.maxPoint = -1;
  3387. this.setMaxPoint = -1;
  3388. this.nextLayer = null;
  3389. }
  3390. finishChunk(newArrays) {
  3391. this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
  3392. this.chunkPos.push(this.chunkStart);
  3393. this.chunkStart = -1;
  3394. this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
  3395. this.maxPoint = -1;
  3396. if (newArrays) {
  3397. this.from = [];
  3398. this.to = [];
  3399. this.value = [];
  3400. }
  3401. }
  3402. /**
  3403. Add a range. Ranges should be added in sorted (by `from` and
  3404. `value.startSide`) order.
  3405. */
  3406. add(from, to, value) {
  3407. if (!this.addInner(from, to, value))
  3408. (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);
  3409. }
  3410. /**
  3411. @internal
  3412. */
  3413. addInner(from, to, value) {
  3414. let diff = from - this.lastTo || value.startSide - this.last.endSide;
  3415. if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)
  3416. throw new Error("Ranges must be added sorted by `from` position and `startSide`");
  3417. if (diff < 0)
  3418. return false;
  3419. if (this.from.length == 250 /* ChunkSize */)
  3420. this.finishChunk(true);
  3421. if (this.chunkStart < 0)
  3422. this.chunkStart = from;
  3423. this.from.push(from - this.chunkStart);
  3424. this.to.push(to - this.chunkStart);
  3425. this.last = value;
  3426. this.lastFrom = from;
  3427. this.lastTo = to;
  3428. this.value.push(value);
  3429. if (value.point)
  3430. this.maxPoint = Math.max(this.maxPoint, to - from);
  3431. return true;
  3432. }
  3433. /**
  3434. @internal
  3435. */
  3436. addChunk(from, chunk) {
  3437. if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)
  3438. return false;
  3439. if (this.from.length)
  3440. this.finishChunk(true);
  3441. this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
  3442. this.chunks.push(chunk);
  3443. this.chunkPos.push(from);
  3444. let last = chunk.value.length - 1;
  3445. this.last = chunk.value[last];
  3446. this.lastFrom = chunk.from[last] + from;
  3447. this.lastTo = chunk.to[last] + from;
  3448. return true;
  3449. }
  3450. /**
  3451. Finish the range set. Returns the new set. The builder can't be
  3452. used anymore after this has been called.
  3453. */
  3454. finish() { return this.finishInner(RangeSet.empty); }
  3455. /**
  3456. @internal
  3457. */
  3458. finishInner(next) {
  3459. if (this.from.length)
  3460. this.finishChunk(false);
  3461. if (this.chunks.length == 0)
  3462. return next;
  3463. let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
  3464. this.from = null; // Make sure further `add` calls produce errors
  3465. return result;
  3466. }
  3467. }
  3468. function findSharedChunks(a, b, textDiff) {
  3469. let inA = new Map();
  3470. for (let set of a)
  3471. for (let i = 0; i < set.chunk.length; i++)
  3472. if (set.chunk[i].maxPoint <= 0)
  3473. inA.set(set.chunk[i], set.chunkPos[i]);
  3474. let shared = new Set();
  3475. for (let set of b)
  3476. for (let i = 0; i < set.chunk.length; i++) {
  3477. let known = inA.get(set.chunk[i]);
  3478. if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&
  3479. !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))
  3480. shared.add(set.chunk[i]);
  3481. }
  3482. return shared;
  3483. }
  3484. class LayerCursor {
  3485. constructor(layer, skip, minPoint, rank = 0) {
  3486. this.layer = layer;
  3487. this.skip = skip;
  3488. this.minPoint = minPoint;
  3489. this.rank = rank;
  3490. }
  3491. get startSide() { return this.value ? this.value.startSide : 0; }
  3492. get endSide() { return this.value ? this.value.endSide : 0; }
  3493. goto(pos, side = -1000000000 /* Far */) {
  3494. this.chunkIndex = this.rangeIndex = 0;
  3495. this.gotoInner(pos, side, false);
  3496. return this;
  3497. }
  3498. gotoInner(pos, side, forward) {
  3499. while (this.chunkIndex < this.layer.chunk.length) {
  3500. let next = this.layer.chunk[this.chunkIndex];
  3501. if (!(this.skip && this.skip.has(next) ||
  3502. this.layer.chunkEnd(this.chunkIndex) < pos ||
  3503. next.maxPoint < this.minPoint))
  3504. break;
  3505. this.chunkIndex++;
  3506. forward = false;
  3507. }
  3508. if (this.chunkIndex < this.layer.chunk.length) {
  3509. let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
  3510. if (!forward || this.rangeIndex < rangeIndex)
  3511. this.setRangeIndex(rangeIndex);
  3512. }
  3513. this.next();
  3514. }
  3515. forward(pos, side) {
  3516. if ((this.to - pos || this.endSide - side) < 0)
  3517. this.gotoInner(pos, side, true);
  3518. }
  3519. next() {
  3520. for (;;) {
  3521. if (this.chunkIndex == this.layer.chunk.length) {
  3522. this.from = this.to = 1000000000 /* Far */;
  3523. this.value = null;
  3524. break;
  3525. }
  3526. else {
  3527. let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];
  3528. let from = chunkPos + chunk.from[this.rangeIndex];
  3529. this.from = from;
  3530. this.to = chunkPos + chunk.to[this.rangeIndex];
  3531. this.value = chunk.value[this.rangeIndex];
  3532. this.setRangeIndex(this.rangeIndex + 1);
  3533. if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)
  3534. break;
  3535. }
  3536. }
  3537. }
  3538. setRangeIndex(index) {
  3539. if (index == this.layer.chunk[this.chunkIndex].value.length) {
  3540. this.chunkIndex++;
  3541. if (this.skip) {
  3542. while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))
  3543. this.chunkIndex++;
  3544. }
  3545. this.rangeIndex = 0;
  3546. }
  3547. else {
  3548. this.rangeIndex = index;
  3549. }
  3550. }
  3551. nextChunk() {
  3552. this.chunkIndex++;
  3553. this.rangeIndex = 0;
  3554. this.next();
  3555. }
  3556. compare(other) {
  3557. return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||
  3558. this.to - other.to || this.endSide - other.endSide;
  3559. }
  3560. }
  3561. class HeapCursor {
  3562. constructor(heap) {
  3563. this.heap = heap;
  3564. }
  3565. static from(sets, skip = null, minPoint = -1) {
  3566. let heap = [];
  3567. for (let i = 0; i < sets.length; i++) {
  3568. for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {
  3569. if (cur.maxPoint >= minPoint)
  3570. heap.push(new LayerCursor(cur, skip, minPoint, i));
  3571. }
  3572. }
  3573. return heap.length == 1 ? heap[0] : new HeapCursor(heap);
  3574. }
  3575. get startSide() { return this.value ? this.value.startSide : 0; }
  3576. goto(pos, side = -1000000000 /* Far */) {
  3577. for (let cur of this.heap)
  3578. cur.goto(pos, side);
  3579. for (let i = this.heap.length >> 1; i >= 0; i--)
  3580. heapBubble(this.heap, i);
  3581. this.next();
  3582. return this;
  3583. }
  3584. forward(pos, side) {
  3585. for (let cur of this.heap)
  3586. cur.forward(pos, side);
  3587. for (let i = this.heap.length >> 1; i >= 0; i--)
  3588. heapBubble(this.heap, i);
  3589. if ((this.to - pos || this.value.endSide - side) < 0)
  3590. this.next();
  3591. }
  3592. next() {
  3593. if (this.heap.length == 0) {
  3594. this.from = this.to = 1000000000 /* Far */;
  3595. this.value = null;
  3596. this.rank = -1;
  3597. }
  3598. else {
  3599. let top = this.heap[0];
  3600. this.from = top.from;
  3601. this.to = top.to;
  3602. this.value = top.value;
  3603. this.rank = top.rank;
  3604. if (top.value)
  3605. top.next();
  3606. heapBubble(this.heap, 0);
  3607. }
  3608. }
  3609. }
  3610. function heapBubble(heap, index) {
  3611. for (let cur = heap[index];;) {
  3612. let childIndex = (index << 1) + 1;
  3613. if (childIndex >= heap.length)
  3614. break;
  3615. let child = heap[childIndex];
  3616. if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
  3617. child = heap[childIndex + 1];
  3618. childIndex++;
  3619. }
  3620. if (cur.compare(child) < 0)
  3621. break;
  3622. heap[childIndex] = cur;
  3623. heap[index] = child;
  3624. index = childIndex;
  3625. }
  3626. }
  3627. class SpanCursor {
  3628. constructor(sets, skip, minPoint) {
  3629. this.minPoint = minPoint;
  3630. this.active = [];
  3631. this.activeTo = [];
  3632. this.activeRank = [];
  3633. this.minActive = -1;
  3634. // A currently active point range, if any
  3635. this.point = null;
  3636. this.pointFrom = 0;
  3637. this.pointRank = 0;
  3638. this.to = -1000000000 /* Far */;
  3639. this.endSide = 0;
  3640. this.openStart = -1;
  3641. this.cursor = HeapCursor.from(sets, skip, minPoint);
  3642. }
  3643. goto(pos, side = -1000000000 /* Far */) {
  3644. this.cursor.goto(pos, side);
  3645. this.active.length = this.activeTo.length = this.activeRank.length = 0;
  3646. this.minActive = -1;
  3647. this.to = pos;
  3648. this.endSide = side;
  3649. this.openStart = -1;
  3650. this.next();
  3651. return this;
  3652. }
  3653. forward(pos, side) {
  3654. while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)
  3655. this.removeActive(this.minActive);
  3656. this.cursor.forward(pos, side);
  3657. }
  3658. removeActive(index) {
  3659. remove(this.active, index);
  3660. remove(this.activeTo, index);
  3661. remove(this.activeRank, index);
  3662. this.minActive = findMinIndex(this.active, this.activeTo);
  3663. }
  3664. addActive(trackOpen) {
  3665. let i = 0, { value, to, rank } = this.cursor;
  3666. while (i < this.activeRank.length && this.activeRank[i] <= rank)
  3667. i++;
  3668. insert(this.active, i, value);
  3669. insert(this.activeTo, i, to);
  3670. insert(this.activeRank, i, rank);
  3671. if (trackOpen)
  3672. insert(trackOpen, i, this.cursor.from);
  3673. this.minActive = findMinIndex(this.active, this.activeTo);
  3674. }
  3675. // After calling this, if `this.point` != null, the next range is a
  3676. // point. Otherwise, it's a regular range, covered by `this.active`.
  3677. next() {
  3678. let from = this.to, wasPoint = this.point;
  3679. this.point = null;
  3680. let trackOpen = this.openStart < 0 ? [] : null, trackExtra = 0;
  3681. for (;;) {
  3682. let a = this.minActive;
  3683. if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
  3684. if (this.activeTo[a] > from) {
  3685. this.to = this.activeTo[a];
  3686. this.endSide = this.active[a].endSide;
  3687. break;
  3688. }
  3689. this.removeActive(a);
  3690. if (trackOpen)
  3691. remove(trackOpen, a);
  3692. }
  3693. else if (!this.cursor.value) {
  3694. this.to = this.endSide = 1000000000 /* Far */;
  3695. break;
  3696. }
  3697. else if (this.cursor.from > from) {
  3698. this.to = this.cursor.from;
  3699. this.endSide = this.cursor.startSide;
  3700. break;
  3701. }
  3702. else {
  3703. let nextVal = this.cursor.value;
  3704. if (!nextVal.point) { // Opening a range
  3705. this.addActive(trackOpen);
  3706. this.cursor.next();
  3707. }
  3708. else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {
  3709. // Ignore any non-empty points that end precisely at the end of the prev point
  3710. this.cursor.next();
  3711. }
  3712. else { // New point
  3713. this.point = nextVal;
  3714. this.pointFrom = this.cursor.from;
  3715. this.pointRank = this.cursor.rank;
  3716. this.to = this.cursor.to;
  3717. this.endSide = nextVal.endSide;
  3718. if (this.cursor.from < from)
  3719. trackExtra = 1;
  3720. this.cursor.next();
  3721. this.forward(this.to, this.endSide);
  3722. break;
  3723. }
  3724. }
  3725. }
  3726. if (trackOpen) {
  3727. let openStart = 0;
  3728. while (openStart < trackOpen.length && trackOpen[openStart] < from)
  3729. openStart++;
  3730. this.openStart = openStart + trackExtra;
  3731. }
  3732. }
  3733. activeForPoint(to) {
  3734. if (!this.active.length)
  3735. return this.active;
  3736. let active = [];
  3737. for (let i = this.active.length - 1; i >= 0; i--) {
  3738. if (this.activeRank[i] < this.pointRank)
  3739. break;
  3740. if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)
  3741. active.push(this.active[i]);
  3742. }
  3743. return active.reverse();
  3744. }
  3745. openEnd(to) {
  3746. let open = 0;
  3747. for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)
  3748. open++;
  3749. return open;
  3750. }
  3751. }
  3752. function compare(a, startA, b, startB, length, comparator) {
  3753. a.goto(startA);
  3754. b.goto(startB);
  3755. let endB = startB + length;
  3756. let pos = startB, dPos = startB - startA;
  3757. for (;;) {
  3758. let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;
  3759. let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);
  3760. if (a.point || b.point) {
  3761. if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&
  3762. sameValues(a.activeForPoint(a.to + dPos), b.activeForPoint(b.to))))
  3763. comparator.comparePoint(pos, clipEnd, a.point, b.point);
  3764. }
  3765. else {
  3766. if (clipEnd > pos && !sameValues(a.active, b.active))
  3767. comparator.compareRange(pos, clipEnd, a.active, b.active);
  3768. }
  3769. if (end > endB)
  3770. break;
  3771. pos = end;
  3772. if (diff <= 0)
  3773. a.next();
  3774. if (diff >= 0)
  3775. b.next();
  3776. }
  3777. }
  3778. function sameValues(a, b) {
  3779. if (a.length != b.length)
  3780. return false;
  3781. for (let i = 0; i < a.length; i++)
  3782. if (a[i] != b[i] && !a[i].eq(b[i]))
  3783. return false;
  3784. return true;
  3785. }
  3786. function remove(array, index) {
  3787. for (let i = index, e = array.length - 1; i < e; i++)
  3788. array[i] = array[i + 1];
  3789. array.pop();
  3790. }
  3791. function insert(array, index, value) {
  3792. for (let i = array.length - 1; i >= index; i--)
  3793. array[i + 1] = array[i];
  3794. array[index] = value;
  3795. }
  3796. function findMinIndex(value, array) {
  3797. let found = -1, foundPos = 1000000000 /* Far */;
  3798. for (let i = 0; i < array.length; i++)
  3799. if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {
  3800. found = i;
  3801. foundPos = array[i];
  3802. }
  3803. return found;
  3804. }
  3805. /**
  3806. Count the column position at the given offset into the string,
  3807. taking extending characters and tab size into account.
  3808. */
  3809. function countColumn(string, tabSize, to = string.length) {
  3810. let n = 0;
  3811. for (let i = 0; i < to;) {
  3812. if (string.charCodeAt(i) == 9) {
  3813. n += tabSize - (n % tabSize);
  3814. i++;
  3815. }
  3816. else {
  3817. n++;
  3818. i = findClusterBreak(string, i);
  3819. }
  3820. }
  3821. return n;
  3822. }
  3823. /**
  3824. Find the offset that corresponds to the given column position in a
  3825. string, taking extending characters and tab size into account. By
  3826. default, the string length is returned when it is too short to
  3827. reach the column. Pass `strict` true to make it return -1 in that
  3828. situation.
  3829. */
  3830. function findColumn(string, col, tabSize, strict) {
  3831. for (let i = 0, n = 0;;) {
  3832. if (n >= col)
  3833. return i;
  3834. if (i == string.length)
  3835. break;
  3836. n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;
  3837. i = findClusterBreak(string, i);
  3838. }
  3839. return strict === true ? -1 : string.length;
  3840. }
  3841. exports.Annotation = Annotation;
  3842. exports.AnnotationType = AnnotationType;
  3843. exports.ChangeDesc = ChangeDesc;
  3844. exports.ChangeSet = ChangeSet;
  3845. exports.Compartment = Compartment;
  3846. exports.EditorSelection = EditorSelection;
  3847. exports.EditorState = EditorState;
  3848. exports.Facet = Facet;
  3849. exports.Line = Line;
  3850. exports.Prec = Prec;
  3851. exports.Range = Range;
  3852. exports.RangeSet = RangeSet;
  3853. exports.RangeSetBuilder = RangeSetBuilder;
  3854. exports.RangeValue = RangeValue;
  3855. exports.SelectionRange = SelectionRange;
  3856. exports.StateEffect = StateEffect;
  3857. exports.StateEffectType = StateEffectType;
  3858. exports.StateField = StateField;
  3859. exports.Text = Text;
  3860. exports.Transaction = Transaction;
  3861. exports.codePointAt = codePointAt;
  3862. exports.codePointSize = codePointSize;
  3863. exports.combineConfig = combineConfig;
  3864. exports.countColumn = countColumn;
  3865. exports.findClusterBreak = findClusterBreak;
  3866. exports.findColumn = findColumn;
  3867. exports.fromCodePoint = fromCodePoint;