index.js 140 KB

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