From 3fd8531b3fb391bd3e714b362cd7399c2faea746 Mon Sep 17 00:00:00 2001 From: Stefan Hanauska Date: Fri, 3 Jan 2025 10:47:05 +0100 Subject: [PATCH] Missing minified files --- amd/build/cm6pro-lazy.min.js | 2 +- amd/build/cm6pro-lazy.min.js.map | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/amd/build/cm6pro-lazy.min.js b/amd/build/cm6pro-lazy.min.js index 03bcdca..2747f3f 100644 --- a/amd/build/cm6pro-lazy.min.js +++ b/amd/build/cm6pro-lazy.min.js @@ -1,3 +1,3 @@ -define("editor_codemirror/cm6pro-lazy",["exports"],(function(_exports){function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;class Text{lineAt(pos){if(pos<0||pos>this.length)throw new RangeError("Invalid position ".concat(pos," in document of length ").concat(this.length));return this.lineInner(pos,!1,1,0)}line(n){if(n<1||n>this.lines)throw new RangeError("Invalid line number ".concat(n," in ").concat(this.lines,"-line document"));return this.lineInner(n,!0,1,0)}replace(from,to,text){[from,to]=clip(this,from,to);let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length;[from,to]=clip(this,from,to);let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(){return new RawTextCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:1)}iterRange(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length;return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(null==from)inner=this.iter();else{null==to&&(to=this.lines+1);let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(0==text.length)throw new RangeError("A document must have at least one line");return 1!=text.length||text[0]?text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[])):Text.empty}}class TextLeaf extends Text{constructor(text){let length=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(text){let length=-1;for(let line of text)length+=line.length+1;return length}(text);super(),this.text=text,this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset){for(let i=0;;i++){let string=this.text[i],end=offset+string.length;if((isLine?line:end)>=target)return new Line(offset,end,line,string);offset=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new TextLeaf(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(1&open){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new TextLeaf(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new TextLeaf(joined.slice(0,mid)),new TextLeaf(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof TextLeaf))return super.replace(from,to,text);[from,to]=clip(this,from,to);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new TextLeaf(lines,newLen):TextNode.from(TextLeaf.split(lines,[]),newLen)}sliceString(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length,lineSep=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"\n";[from,to]=clip(this,from,to);let result="";for(let pos=0,i=0;pos<=to&&ifrom&&i&&(result+=lineSep),frompos&&(result+=line.slice(Math.max(0,from-pos),to-pos)),pos=end+1}return result}flatten(target){for(let line of this.text)target.push(line)}scanIdentical(){return 0}static split(text,target){let part=[],len=-1;for(let line of text)part.push(line),len+=line.length+1,32==part.length&&(target.push(new TextLeaf(part,len)),part=[],len=-1);return len>-1&&target.push(new TextLeaf(part,len)),target}}class TextNode extends Text{constructor(children,length){super(),this.children=children,this.length=length,this.lines=0;for(let child of children)this.lines+=child.lines}lineInner(target,isLine,line,offset){for(let i=0;;i++){let child=this.children[i],end=offset+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset);offset=end+1,line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));pos>=from&&end<=to&&!childOpen?target.push(child):child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if([from,to]=clip(this,from,to),text.lines=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text),totalLines=this.lines-child.lines+updated.lines;if(updated.lines>4&&updated.lines>totalLines>>6){let copy=this.children.slice();return copy[i]=updated,new TextNode(copy,this.length-(to-from)+text.length)}return super.replace(pos,end,updated)}pos=end+1}return super.replace(from,to,text)}sliceString(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length,lineSep=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"\n";[from,to]=clip(this,from,to);let result="";for(let i=0,pos=0;ifrom&&i&&(result+=lineSep),frompos&&(result+=child.sliceString(from-pos,to-pos,lineSep)),pos=end+1}return result}flatten(target){for(let child of this.children)child.flatten(target)}scanIdentical(other,dir){if(!(other instanceof TextNode))return 0;let length=0,[iA,iB,eA,eB]=dir>0?[0,0,this.children.length,other.children.length]:[this.children.length-1,other.children.length-1,-1,-1];for(;;iA+=dir,iB+=dir){if(iA==eA||iB==eB)return length;let chA=this.children[iA],chB=other.children[iB];if(chA!=chB)return length+chA.scanIdentical(chB,dir);length+=chA.length+1}}static from(children){let length=arguments.length>1&&void 0!==arguments[1]?arguments[1]:children.reduce(((l,ch)=>l+ch.length+1),-1),lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1,chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add(child){let last;if(child.lines>maxChunk&&child instanceof TextNode)for(let node of child.children)add(node);else child.lines>minChunk&&(currentLines>minChunk||!currentLines)?(flush(),chunked.push(child)):child instanceof TextLeaf&¤tLines&&(last=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last.lines<=32?(currentLines+=child.lines,currentLen+=child.length+1,currentChunk[currentChunk.length-1]=new TextLeaf(last.text.concat(child.text),last.length+1+child.length)):(currentLines+child.lines>chunk&&flush(),currentLines+=child.lines,currentLen+=child.length+1,currentChunk.push(child))}function flush(){0!=currentLines&&(chunked.push(1==currentChunk.length?currentChunk[0]:TextNode.from(currentChunk,currentLen)),currentLen=-1,currentLines=currentChunk.length=0)}for(let child of children)add(child);return flush(),1==chunked.length?chunked[0]:new TextNode(chunked,length)}}function appendText(text,target){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e9;for(let pos=0,i=0,first=!0;i=from&&(end>to&&(line=line.slice(0,to-pos)),pos1&&void 0!==arguments[1]?arguments[1]:1;this.dir=dir,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[text],this.offsets=[dir>0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){for(this.done=this.lineBreak=!1;;){let last=this.nodes.length-1,top=this.nodes[last],offsetValue=this.offsets[last],offset=offsetValue>>1,size=top instanceof TextLeaf?top.text.length:top.children.length;if(offset==(dir>0?size:0)){if(0==last)return this.done=!0,this.value="",this;dir>0&&this.offsets[last-1]++,this.nodes.pop(),this.offsets.pop()}else if((1&offsetValue)==(dir>0?0:1)){if(this.offsets[last]+=dir,0==skip)return this.lineBreak=!0,this.value="\n",this;skip--}else if(top instanceof TextLeaf){let next=top.text[offset+(dir<0?-1:0)];if(this.offsets[last]+=dir,next.length>Math.max(0,skip))return this.value=0==skip?next:dir>0?next.slice(skip):next.slice(0,next.length-skip),this;skip-=next.length}else{let next=top.children[offset+(dir<0?-1:0)];skip>next.length?(skip-=next.length,this.offsets[last]+=dir):(dir<0&&this.offsets[last]--,this.nodes.push(next),this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1))}}}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return skip<0&&(this.nextInner(-skip,-this.dir),skip=this.value.length),this.nextInner(skip,this.dir)}}class PartialTextCursor{constructor(text,start,end){this.value="",this.done=!1,this.cursor=new RawTextCursor(text,start>end?-1:1),this.pos=start>end?text.length:0,this.from=Math.min(start,end),this.to=Math.max(start,end)}nextInner(skip,dir){if(dir<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit=dir<0?this.pos-this.from:this.to-this.pos;skip>limit&&(skip=limit),limit-=skip;let{value:value}=this.cursor.next(skip);return this.pos+=(value.length+skip)*dir,this.value=value.length<=limit?value:dir<0?value.slice(value.length-limit):value.slice(0,limit),this.done=!this.value,this}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return skip<0?skip=Math.max(skip,this.from-this.pos):skip>0&&(skip=Math.min(skip,this.to-this.pos)),this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&""!=this.value}}class LineCursor{constructor(inner){this.inner=inner,this.afterBreak=!0,this.value="",this.done=!1}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,{done:done,lineBreak:lineBreak,value:value}=this.inner.next(skip);return done&&this.afterBreak?(this.value="",this.afterBreak=!1):done?(this.done=!0,this.value=""):lineBreak?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=value,this.afterBreak=!1),this}get lineBreak(){return!1}}"undefined"!=typeof Symbol&&(Text.prototype[Symbol.iterator]=function(){return this.iter()},RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this});class Line{constructor(from,to,number,text){this.from=from,this.to=to,this.number=number,this.text=text}get length(){return this.to-this.from}}function clip(text,from,to){return[from=Math.max(0,Math.min(text.length,from)),Math.max(from,Math.min(text.length,to))]}let extend="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s=>s?parseInt(s,36):1));for(let i=1;icode)return extend[i-1]<=code;return!1}function isRegionalIndicator(code){return code>=127462&&code<=127487}function findClusterBreak(str,pos){let forward=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],includeExtending=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1))&&pos--;let prev=codePointAt(str,pos);for(pos+=codePointSize(prev);pos=0&&isRegionalIndicator(codePointAt(str,i));)countBefore++,i-=2;if(countBefore%2==0)break;pos+=2}}}return pos}function prevClusterBreak(str,pos,includeExtending){for(;pos>0;){let found=nextClusterBreak(str,pos-2,includeExtending);if(found=56320&&ch<57344}function surrogateHigh(ch){return ch>=55296&&ch<56320}function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);return surrogateLow(code1)?code1-56320+(code0-55296<<10)+65536:code0}function fromCodePoint(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode(55296+(code>>10),56320+(1023&code)))}function codePointSize(code){return code<65536?1:2}const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode){return MapMode[MapMode.Simple=0]="Simple",MapMode[MapMode.TrackDel=1]="TrackDel",MapMode[MapMode.TrackBefore=2]="TrackBefore",MapMode[MapMode.TrackAfter=3]="TrackAfter",MapMode}(MapMode||(MapMode={}));class ChangeDesc{constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;i1&&void 0!==arguments[1]&&arguments[1])}get invertedDesc(){let sections=[];for(let i=0;i1&&void 0!==arguments[1]&&arguments[1];return other.empty?this:mapSet(this,other,before)}mapPos(pos){let assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:MapMode.Simple,posA=0,posB=0;for(let i=0;ipos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posApos||mode==MapMode.TrackBefore&&posApos))return null;if(endA>pos||endA==pos&&assoc<0&&!len)return pos==posA||assoc<0?posB:posB+ins;posB+=ins}posA=endA}if(pos>posA)throw new RangeError("Position ".concat(pos," is out of range for changeset of length ").concat(posA));return posB}touchesRange(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;for(let i=0,pos=0;i=0&&pos<=to&&end>=from)return!(posto)||"cover";pos=end}return!1}toString(){let result="";for(let i=0;i=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json){if(!Array.isArray(json)||json.length%2||json.some((a=>"number"!=typeof a)))throw new RangeError("Invalid JSON representation of ChangeDesc");return new ChangeDesc(json)}static create(sections){return new ChangeDesc(sections)}}class ChangeSet extends ChangeDesc{constructor(sections,inserted){super(sections),this.inserted=inserted}apply(doc){if(this.length!=doc.length)throw new RangeError("Applying change set to a document with the wrong length");return iterChanges(this,((fromA,toA,fromB,_toB,text)=>doc=doc.replace(fromB,fromB+(toA-fromA),text)),!1),doc}mapDesc(other){return mapSet(this,other,arguments.length>1&&void 0!==arguments[1]&&arguments[1],!0)}invert(doc){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i=0){sections[i]=ins,sections[i+1]=len;let index=i>>1;for(;inserted.length1&&void 0!==arguments[1]&&arguments[1];return other.empty?this:mapSet(this,other,before,!0)}iterChanges(f){iterChanges(this,f,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}get desc(){return ChangeDesc.create(this.sections)}filter(ranges){let resultSections=[],resultInserted=[],filteredSections=[],iter=new SectionIter(this);done:for(let i=0,pos=0;;){let next=i==ranges.length?1e9:ranges[i++];for(;pos0&&addInsert(resultInserted,resultSections,iter.text),iter.forward(len),pos+=len}let end=ranges[i++];for(;pos>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0,total=null;function flush(){let force=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!force&&!sections.length)return;posto||from<0||to>length)throw new RangeError("Invalid change range ".concat(from," to ").concat(to," (in doc of length ").concat(length,")"));let insText=insert?"string"==typeof insert?Text.of(insert.split(lineSep||DefaultSplit)):insert:Text.empty,insLen=insText.length;if(from==to&&0==insLen)return;frompos&&addSection(sections,from-pos,-1),addSection(sections,to-from,insLen),addInsert(inserted,sections,insText),pos=to}}(changes),flush(!total),total}static empty(length){return new ChangeSet(length?[length,-1]:[],[])}static fromJSON(json){if(!Array.isArray(json))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;ii&&"string"!=typeof e)))throw new RangeError("Invalid JSON representation of ChangeSet");if(1==part.length)sections.push(part[0],0);else{for(;inserted.length3&&void 0!==arguments[3]&&arguments[3];if(0==len&&ins<=0)return;let last=sections.length-2;last>=0&&ins<=0&&ins==sections[last+1]?sections[last]+=len:0==len&&0==sections[last]?sections[last+1]+=ins:forceJoin?(sections[last]+=len,sections[last+1]+=ins):sections.push(len,ins)}function addInsert(values,sections,value){if(0==value.length)return;let index=sections.length-2>>1;if(index>1])),!(individual||i==desc.sections.length||desc.sections[i+1]<0);)len=desc.sections[i++],ins=desc.sections[i++];f(posA,endA,posB,endB,text),posA=endA,posB=endB}}}function mapSet(setA,setB,before){let mkSet=arguments.length>3&&void 0!==arguments[3]&&arguments[3],sections=[],insert=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;)if(-1==a.ins&&-1==b.ins){let len=Math.min(a.len,b.len);addSection(sections,len,-1),a.forward(len),b.forward(len)}else if(b.ins>=0&&(a.ins<0||inserted==a.i||0==a.off&&(b.len=0&&inserted=0)){if(a.done&&b.done)return insert?ChangeSet.createSet(sections,insert):ChangeDesc.create(sections);throw new Error("Mismatched change set lengths")}{let len=0,left=a.len;for(;left;)if(-1==b.ins){let piece=Math.min(left,b.len);len+=piece,left-=piece,b.forward(piece)}else{if(!(0==b.ins&&b.len2&&void 0!==arguments[2]&&arguments[2],sections=[],insert=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let open=!1;;){if(a.done&&b.done)return insert?ChangeSet.createSet(sections,insert):ChangeDesc.create(sections);if(0==a.ins)addSection(sections,a.len,0,open),a.next();else if(0!=b.len||b.done){if(a.done||b.done)throw new Error("Mismatched change set lengths");{let len=Math.min(a.len2,b.len),sectionLen=sections.length;if(-1==a.ins){let insB=-1==b.ins?-1:b.off?0:b.ins;addSection(sections,len,insB,open),insert&&insB&&addInsert(insert,sections,b.text)}else-1==b.ins?(addSection(sections,a.off?0:a.len,len,open),insert&&addInsert(insert,sections,a.textBit(len))):(addSection(sections,a.off?0:a.len,b.off?0:b.ins,open),insert&&!b.off&&addInsert(insert,sections,b.text));open=(a.ins>len||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen),a.forward2(len),b.forward(len)}}else addSection(sections,0,b.ins,open),insert&&addInsert(insert,sections,b.text),b.next()}}class SectionIter{constructor(set){this.set=set,this.i=0,this.next()}next(){let{sections:sections}=this.set;this.i>1;return index>=inserted.length?Text.empty:inserted[index]}textBit(len){let{inserted:inserted}=this.set,index=this.i-2>>1;return index>=inserted.length&&!len?Text.empty:inserted[index].slice(this.off,null==len?void 0:this.off+len)}forward(len){len==this.len?this.next():(this.len-=len,this.off+=len)}forward2(len){-1==this.ins?this.forward(len):len==this.ins?this.next():(this.ins-=len,this.off+=len)}}class SelectionRange{constructor(from,to,flags){this.from=from,this.to=to,this.flags=flags}get anchor(){return 32&this.flags?this.to:this.from}get head(){return 32&this.flags?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return 8&this.flags?-1:16&this.flags?1:0}get bidiLevel(){let level=7&this.flags;return 7==level?null:level}get goalColumn(){let value=this.flags>>6;return 16777215==value?void 0:value}map(change){let from,to,assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return this.empty?from=to=change.mapPos(this.from,assoc):(from=change.mapPos(this.from,1),to=change.mapPos(this.to,-1)),from==this.from&&to==this.to?this:new SelectionRange(from,to,this.flags)}extend(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){let includeAssoc=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!(this.anchor!=other.anchor||this.head!=other.head||includeAssoc&&this.empty&&this.assoc!=other.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json){if(!json||"number"!=typeof json.anchor||"number"!=typeof json.head)throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json.anchor,json.head)}static create(from,to,flags){return new SelectionRange(from,to,flags)}}class EditorSelection{constructor(ranges,mainIndex){this.ranges=ranges,this.mainIndex=mainIndex}map(change){let assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return change.empty?this:EditorSelection.create(this.ranges.map((r=>r.map(change,assoc))),this.mainIndex)}eq(other){let includeAssoc=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return!1;for(let i=0;i1&&void 0!==arguments[1])||arguments[1];return EditorSelection.create([range].concat(this.ranges),main?0:this.mainIndex+1)}replaceRange(range){let which=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.mainIndex,ranges=this.ranges.slice();return ranges[which]=range,EditorSelection.create(ranges,this.mainIndex)}toJSON(){return{ranges:this.ranges.map((r=>r.toJSON())),main:this.mainIndex}}static fromJSON(json){if(!json||!Array.isArray(json.ranges)||"number"!=typeof json.main||json.main>=json.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new EditorSelection(json.ranges.map((r=>SelectionRange.fromJSON(r))),json.main)}static single(anchor){let head=arguments.length>1&&void 0!==arguments[1]?arguments[1]:anchor;return new EditorSelection([EditorSelection.range(anchor,head)],0)}static create(ranges){let mainIndex=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(0==ranges.length)throw new RangeError("A selection needs at least one range");for(let pos=0,i=0;i1&&void 0!==arguments[1]?arguments[1]:0,bidiLevel=arguments.length>2?arguments[2]:void 0,goalColumn=arguments.length>3?arguments[3]:void 0;return SelectionRange.create(pos,pos,(0==assoc?0:assoc<0?8:16)|(null==bidiLevel?7:Math.min(6,bidiLevel))|(null!=goalColumn?goalColumn:16777215)<<6)}static range(anchor,head,goalColumn,bidiLevel){let flags=(null!=goalColumn?goalColumn:16777215)<<6|(null==bidiLevel?7:Math.min(6,bidiLevel));return headanchor?8:0)|flags)}static normalized(ranges){let mainIndex=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,main=ranges[mainIndex];ranges.sort(((a,b)=>a.from-b.from)),mainIndex=ranges.indexOf(main);for(let i=1;irange.head?EditorSelection.range(to,from):EditorSelection.range(from,to))}}return new EditorSelection(ranges,mainIndex)}}function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}let nextID=0;class Facet{constructor(combine,compareInput,compare,isStatic,enables){this.combine=combine,this.compareInput=compareInput,this.compare=compare,this.isStatic=isStatic,this.id=nextID++,this.default=combine([]),this.extensions="function"==typeof enables?enables(this):enables}get reader(){return this}static define(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Facet(config.combine||(a=>a),config.compareInput||((a,b)=>a===b),config.compare||(config.combine?(a,b)=>a===b:sameArray$1),!!config.static,config.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){return get||(get=x=>x),this.compute([field],(state=>get(state.field(field))))}}function sameArray$1(a,b){return a==b||a.length==b.length&&a.every(((e,i)=>e===b[i]))}class FacetProvider{constructor(dependencies,facet,type,value){this.dependencies=dependencies,this.facet=facet,this.type=type,this.value=value,this.id=nextID++}dynamicSlot(addresses){var _a;let getter=this.value,compare=this.facet.compareInput,id=this.id,idx=addresses[id]>>1,multi=2==this.type,depDoc=!1,depSel=!1,depAddrs=[];for(let dep of this.dependencies)"doc"==dep?depDoc=!0:"selection"==dep?depSel=!0:0==(1&(null!==(_a=addresses[dep.id])&&void 0!==_a?_a:1))&&depAddrs.push(addresses[dep.id]);return{create:state=>(state.values[idx]=getter(state),1),update(state,tr){if(depDoc&&tr.docChanged||depSel&&(tr.docChanged||tr.selection)||ensureAll(state,depAddrs)){let newVal=getter(state);if(multi?!compareArray(newVal,state.values[idx],compare):!compare(newVal,state.values[idx]))return state.values[idx]=newVal,1}return 0},reconfigure:(state,oldState)=>{let newVal,oldAddr=oldState.config.address[id];if(null!=oldAddr){let oldVal=getAddr(oldState,oldAddr);if(this.dependencies.every((dep=>dep instanceof Facet?oldState.facet(dep)===state.facet(dep):!(dep instanceof StateField)||oldState.field(dep,!1)==state.field(dep,!1)))||(multi?compareArray(newVal=getter(state),oldVal,compare):compare(newVal=getter(state),oldVal)))return state.values[idx]=oldVal,0}else newVal=getter(state);return state.values[idx]=newVal,1}}}}function compareArray(a,b,compare){if(a.length!=b.length)return!1;for(let i=0;iaddresses[p.id])),providerTypes=providers.map((p=>p.type)),dynamic=providerAddrs.filter((p=>!(1&p))),idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;ia===b),config);return config.provide&&(field.provides=config.provide(field)),field}create(state){let init=state.facet(initField).find((i=>i.field==this));return((null==init?void 0:init.create)||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>(state.values[idx]=this.create(state),1),update:(state,tr)=>{let oldVal=state.values[idx],value=this.updateF(oldVal,tr);return this.compareF(oldVal,value)?0:(state.values[idx]=value,1)},reconfigure:(state,oldState)=>null!=oldState.config.address[this.id]?(state.values[idx]=oldState.field(this),0):(state.values[idx]=this.create(state),1)}}init(create){return[this,initField.of({field:this,create:create})]}get extension(){return this}}const Prec__lowest=4,Prec__low=3,Prec__default=2,Prec__high=1;function prec(value){return ext=>new PrecExtension(ext,value)}const Prec={highest:prec(0),high:prec(Prec__high),default:prec(Prec__default),low:prec(Prec__low),lowest:prec(Prec__lowest)};class PrecExtension{constructor(inner,prec){this.inner=inner,this.prec=prec}}class Compartment{of(ext){return new CompartmentInstance(this,ext)}reconfigure(content){return Compartment.reconfigure.of({compartment:this,extension:content})}get(state){return state.config.compartments.get(this)}}class CompartmentInstance{constructor(compartment,inner){this.compartment=compartment,this.inner=inner}}class Configuration{constructor(base,compartments,dynamicSlots,address,staticValues,facets){for(this.base=base,this.compartments=compartments,this.dynamicSlots=dynamicSlots,this.address=address,this.staticValues=staticValues,this.facets=facets,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(base,compartments,oldState){let fields=[],facets=Object.create(null),newCompartments=new Map;for(let ext of function(extension,compartments,newCompartments){let result=[[],[],[],[],[]],seen=new Map;function inner(ext,prec){let known=seen.get(ext);if(null!=known){if(known<=prec)return;let found=result[known].indexOf(ext);found>-1&&result[known].splice(found,1),ext instanceof CompartmentInstance&&newCompartments.delete(ext.compartment)}if(seen.set(ext,prec),Array.isArray(ext))for(let e of ext)inner(e,prec);else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError("Duplicate use of compartment in extensions");let content=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content),inner(content,prec)}else if(ext instanceof PrecExtension)inner(ext.inner,ext.prec);else if(ext instanceof StateField)result[prec].push(ext),ext.provides&&inner(ext.provides,prec);else if(ext instanceof FacetProvider)result[prec].push(ext),ext.facet.extensions&&inner(ext.facet.extensions,Prec__default);else{let content=ext.extension;if(!content)throw new Error("Unrecognized extension value in extension set (".concat(ext,"). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks."));inner(content,prec)}}return inner(extension,Prec__default),result.reduce(((a,b)=>a.concat(b)))}(base,compartments,newCompartments))ext instanceof StateField?fields.push(ext):(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext);let address=Object.create(null),staticValues=[],dynamicSlots=[];for(let field of fields)address[field.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>field.slot(a)));let oldFacets=null==oldState?void 0:oldState.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet,oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every((p=>0==p.type)))if(address[facet.id]=staticValues.length<<1|1,sameArray$1(oldProviders,providers))staticValues.push(oldState.facet(facet));else{let value=facet.combine(providers.map((p=>p.value)));staticValues.push(oldState&&facet.compare(value,oldState.facet(facet))?oldState.facet(facet):value)}else{for(let p of providers)0==p.type?(address[p.id]=staticValues.length<<1|1,staticValues.push(p.value)):(address[p.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>p.dynamicSlot(a))));address[facet.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>dynamicFacetSlot(a,facet,providers)))}}let dynamic=dynamicSlots.map((f=>f(address)));return new Configuration(base,newCompartments,dynamic,address,staticValues,facets)}}function ensureAddr(state,addr){if(1&addr)return 2;let idx=addr>>1,status=state.status[idx];if(4==status)throw new Error("Cyclic dependency between fields and/or facets");if(2&status)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}function getAddr(state,addr){return 1&addr?state.config.staticValues[addr>>1]:state.values[addr>>1]}const languageData=Facet.define(),allowMultipleSelections=Facet.define({combine:values=>values.some((v=>v)),static:!0}),lineSeparator=Facet.define({combine:values=>values.length?values[0]:void 0,static:!0}),changeFilter=Facet.define(),transactionFilter=Facet.define(),transactionExtender=Facet.define(),readOnly=Facet.define({combine:values=>!!values.length&&values[0]});class Annotation{constructor(type,value){this.type=type,this.value=value}static define(){return new AnnotationType}}class AnnotationType{of(value){return new Annotation(this,value)}}class StateEffectType{constructor(map){this.map=map}of(value){return new StateEffect(this,value)}}class StateEffect{constructor(type,value){this.type=type,this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return void 0===mapped?void 0:mapped==this.value?this:new StateEffect(this.type,mapped)}is(type){return this.type==type}static define(){return new StateEffectType((arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);mapped&&result.push(mapped)}return result}}StateEffect.reconfigure=StateEffect.define(),StateEffect.appendConfig=StateEffect.define();class Transaction{constructor(startState,changes,selection,effects,annotations,scrollIntoView){this.startState=startState,this.changes=changes,this.selection=selection,this.effects=effects,this.annotations=annotations,this.scrollIntoView=scrollIntoView,this._doc=null,this._state=null,selection&&checkSelection(selection,changes.newLength),annotations.some((a=>a.type==Transaction.time))||(this.annotations=annotations.concat(Transaction.time.of(Date.now())))}static create(startState,changes,selection,effects,annotations,scrollIntoView){return new Transaction(startState,changes,selection,effects,annotations,scrollIntoView)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(Transaction.userEvent);return!(!e||!(e==event||e.length>event.length&&e.slice(0,event.length)==event&&"."==e[event.length]))}}function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA=a[iA]))from=a[iA++],to=a[iA++];else{if(!(iB=0;i--){let extension=extenders[i](tr);extension&&Object.keys(extension).length&&(spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),!0))}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}(filter?function(tr){let state=tr.startState,result=!0;for(let filter of state.facet(changeFilter)){let value=filter(tr);if(!1===value){result=!1;break}Array.isArray(value)&&(result=!0===result?value:joinRanges(result,value))}if(!0!==result){let changes,back;if(!1===result)back=tr.changes.invertedDesc,changes=ChangeSet.empty(state.doc.length);else{let filtered=tr.changes.filter(result);changes=filtered.changes,back=filtered.filtered.mapDesc(filtered.changes).invertedDesc}tr=Transaction.create(state,changes,tr.selection&&tr.selection.map(back),StateEffect.mapEffects(tr.effects,back),tr.annotations,tr.scrollIntoView)}let filters=state.facet(transactionFilter);for(let i=filters.length-1;i>=0;i--){let filtered=filters[i](tr);tr=filtered instanceof Transaction?filtered:Array.isArray(filtered)&&1==filtered.length&&filtered[0]instanceof Transaction?filtered[0]:resolveTransaction(state,asArray$1(filtered),!1)}return tr}(tr):tr)}Transaction.time=Annotation.define(),Transaction.userEvent=Annotation.define(),Transaction.addToHistory=Annotation.define(),Transaction.remote=Annotation.define();const none$2=[];function asArray$1(value){return null==value?none$2:Array.isArray(value)?value:[value]}var CharCategory=function(CharCategory){return CharCategory[CharCategory.Word=0]="Word",CharCategory[CharCategory.Space=1]="Space",CharCategory[CharCategory.Other=2]="Other",CharCategory}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch(_){}function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(function(str){if(wordChar)return wordChar.test(str);for(let i=0;i"€"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return!0}return!1}(char))return CharCategory.Word;for(let i=0;i-1)return CharCategory.Word;return CharCategory.Other}}class EditorState{constructor(config,doc,selection,values,computeSlot,tr){this.config=config,this.doc=doc,this.selection=selection,this.values=values,this.status=config.statusTemplate.slice(),this.computeSlot=computeSlot,tr&&(tr._state=this);for(let i=0;i1&&void 0!==arguments[1])||arguments[1],addr=this.config.address[field.id];if(null!=addr)return ensureAddr(this,addr),getAddr(this,addr);if(require)throw new RangeError("Field is not present in this state")}update(){for(var _len=arguments.length,specs=new Array(_len),_key=0;_key<_len;_key++)specs[_key]=arguments[_key];return resolveTransaction(this,specs,!0)}applyTransaction(tr){let startValues,conf=this.config,{base:base,compartments:compartments}=conf;for(let effect of tr.effects)effect.is(Compartment.reconfigure)?(conf&&(compartments=new Map,conf.compartments.forEach(((val,key)=>compartments.set(key,val))),conf=null),compartments.set(effect.value.compartment,effect.value.extension)):effect.is(StateEffect.reconfigure)?(conf=null,base=effect.value):effect.is(StateEffect.appendConfig)&&(conf=null,base=asArray$1(base).concat(effect.value));if(conf)startValues=tr.startState.values.slice();else{conf=Configuration.resolve(base,compartments,this),startValues=new EditorState(conf,this.doc,this.selection,conf.dynamicSlots.map((()=>null)),((state,slot)=>slot.reconfigure(state,this)),null).values}let selection=tr.startState.facet(allowMultipleSelections)?tr.newSelection:tr.newSelection.asSingle();new EditorState(conf,tr.newDoc,selection,startValues,((state,slot)=>slot.update(state,tr)),tr)}replaceSelection(text){return"string"==typeof text&&(text=this.toText(text)),this.changeByRange((range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)})))}changeByRange(f){let sel=this.selection,result1=f(sel.ranges[0]),changes=this.changes(result1.changes),ranges=[result1.range],effects=asArray$1(result1.effects);for(let i=1;i0&&void 0!==arguments[0]?arguments[0]:[];return spec instanceof ChangeSet?spec:ChangeSet.of(spec,this.doc.length,this.facet(EditorState.lineSeparator))}toText(string){return Text.of(string.split(this.facet(EditorState.lineSeparator)||DefaultSplit))}sliceDoc(){let from=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.doc.length;return this.doc.sliceString(from,to,this.lineBreak)}facet(facet){let addr=this.config.address[facet.id];return null==addr?facet.default:(ensureAddr(this,addr),getAddr(this,addr))}toJSON(fields){let result={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(fields)for(let prop in fields){let value=fields[prop];value instanceof StateField&&null!=this.config.address[value.id]&&(result[prop]=value.spec.toJSON(this.field(fields[prop]),this))}return result}static fromJSON(json){let config=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},fields=arguments.length>2?arguments[2]:void 0;if(!json||"string"!=typeof json.doc)throw new RangeError("Invalid JSON representation for EditorState");let fieldInit=[];if(fields)for(let prop in fields)if(Object.prototype.hasOwnProperty.call(json,prop)){let field=fields[prop],value=json[prop];fieldInit.push(field.init((state=>field.spec.fromJSON(value,state))))}return EditorState.create({doc:json.doc,selection:EditorSelection.fromJSON(json.selection),extensions:config.extensions?fieldInit.concat([config.extensions]):fieldInit})}static create(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},configuration=Configuration.resolve(config.extensions||[],new Map),doc=config.doc instanceof Text?config.doc:Text.of((config.doc||"").split(configuration.staticFacet(EditorState.lineSeparator)||DefaultSplit)),selection=config.selection?config.selection instanceof EditorSelection?config.selection:EditorSelection.single(config.selection.anchor,config.selection.head):EditorSelection.single(0);return checkSelection(selection,doc.length),configuration.staticFacet(allowMultipleSelections)||(selection=selection.asSingle()),new EditorState(configuration,doc,selection,configuration.dynamicSlots.map((()=>null)),((state,slot)=>slot.create(state)),null)}get tabSize(){return this.facet(EditorState.tabSize)}get lineBreak(){return this.facet(EditorState.lineSeparator)||"\n"}get readOnly(){return this.facet(readOnly)}phrase(phrase){for(var _len2=arguments.length,insert=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)insert[_key2-1]=arguments[_key2];for(let map of this.facet(EditorState.phrases))if(Object.prototype.hasOwnProperty.call(map,phrase)){phrase=map[phrase];break}return insert.length&&(phrase=phrase.replace(/\$(\$|\d*)/g,((m,i)=>{if("$"==i)return"$";let n=+(i||1);return!n||n>insert.length?m:insert[n-1]}))),phrase}languageDataAt(name,pos){let side=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name)&&values.push(result[name]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text:text,from:from,length:length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;end2&&void 0!==arguments[2]?arguments[2]:{},result={};for(let config of configs)for(let key of Object.keys(config)){let value=config[key],current=result[key];if(void 0===current)result[key]=value;else if(current===value||void 0===value);else{if(!Object.hasOwnProperty.call(combine,key))throw new Error("Config merge conflict for field "+key);result[key]=combine[key](current,value)}}for(let key in defaults)void 0===result[key]&&(result[key]=defaults[key]);return result}EditorState.allowMultipleSelections=allowMultipleSelections,EditorState.tabSize=Facet.define({combine:values=>values.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every((k=>a[k]==b[k]))}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();class RangeValue{eq(other){return this==other}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;return Range$1.create(from,to,this)}}RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=class Range{constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new Range(from,to,value)}};function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}class Chunk{constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end){let startAt=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1,diff=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff>=0?lo:hi;diff>=0?hi=mid:lo=mid+1}}between(offset,from,to,f){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new Chunk(from,to,value,maxPoint):null,pos:newPos}}}class RangeSet{constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new RangeSet(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last=this.chunk.length-1;return last<0?0:Math.max(this.chunkEnd(last),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index){return this.chunkPos[index]+this.chunk[index].length}update(updateSpec){let{add:add=[],sort:sort=!1,filterFrom:filterFrom=0,filterTo:filterTo=this.length}=updateSpec,filter=updateSpec.filter;if(0==add.length&&!filter)return this;if(sort&&(add=add.slice().sort(cmpRange)),this.isEmpty)return add.length?RangeSet.of(add):this;let cur=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur.value||i=0){let range=add[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else 1==cur.rangeIndex&&cur.chunkIndexthis.chunkEnd(cur.chunkIndex)||filterTocur.to||filterTo=start&&from<=start+chunk.length&&!1===chunk.between(start,from-start,to-start,f))return}this.nextLayer.between(from,to,f)}}iter(){let from=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets){let from=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator){let minPointSize=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,a=oldSets.filter((set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize)),b=newSets.filter((set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize)),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps(((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator))),textDiff.empty&&0==textDiff.length&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3?arguments[3]:void 0;null==to&&(to=999999999);let a=oldSets.filter((set=>!set.isEmpty&&newSets.indexOf(set)<0)),b=newSets.filter((set=>!set.isEmpty&&oldSets.indexOf(set)<0));if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator){let cursor=new SpanCursor(sets,null,arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrompos&&(iterator.span(pos,curTo,cursor.active,openRanges),openRanges=cursor.openEnd(curTo));if(cursor.to>to)return openRanges+(cursor.point&&cursor.to>to?1:0);pos=cursor.to,cursor.next()}}static of(ranges){let sort=arguments.length>1&&void 0!==arguments[1]&&arguments[1],build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort?function(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur}return ranges}(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}static join(sets){if(!sets.length)return RangeSet.empty;let result=sets[sets.length-1];for(let i=sets.length-2;i>=0;i--)for(let layer=sets[i];layer!=RangeSet.empty;layer=layer.nextLayer)result=new RangeSet(layer.chunkPos,layer.chunk,result,Math.max(layer.maxPoint,result.maxPoint));return result}}RangeSet.empty=new RangeSet([],[],null,-1),RangeSet.empty.nextLayer=RangeSet.empty;class RangeSetBuilder{finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new RangeSetBuilder)).add(from,to,value)}addInner(from,to,value){let diff=from-this.lastTo||value.startSide-this.last.endSide;if(diff<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return!(diff<0)&&(250==this.from.length&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=from),this.from.push(from-this.chunkStart),this.to.push(to-this.chunkStart),this.last=value,this.lastFrom=from,this.lastTo=to,this.value.push(value),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last=chunk.value.length-1;return this.last=chunk.value[last],this.lastFrom=chunk.from[last]+from,this.lastTo=chunk.to[last]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),0==this.chunks.length)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}}function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i3&&void 0!==arguments[3]?arguments[3]:0;this.layer=layer,this.skip=skip,this.minPoint=minPoint,this.rank=rank}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;return this.chunkIndex=this.rangeIndex=0,this.gotoInner(pos,side,!1),this}gotoInner(pos,side,forward){for(;this.chunkIndex=this.minPoint)break}}}setRangeIndex(index){if(index==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex1&&void 0!==arguments[1]?arguments[1]:null,minPoint=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,heap=[];for(let i=0;i=minPoint&&heap.push(new LayerCursor(cur,skip,minPoint,i));return 1==heap.length?heap[0]:new HeapCursor(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;for(let cur of this.heap)cur.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur of this.heap)cur.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(0==this.heap.length)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top=this.heap[0];this.from=top.from,this.to=top.to,this.value=top.value,this.rank=top.rank,top.value&&top.next(),heapBubble(this.heap,0)}}}function heapBubble(heap,index){for(let cur=heap[index];;){let childIndex=1+(index<<1);if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0&&(child=heap[childIndex+1],childIndex++),cur.compare(child)<0)break;heap[childIndex]=cur,heap[index]=child,index=childIndex}}class SpanCursor{constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;return this.cursor.goto(pos,side),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=pos,this.endSide=side,this.openStart=-1,this.next(),this}forward(pos,side){for(;this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0;)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index){remove(this.active,index),remove(this.activeTo,index),remove(this.activeRank,index),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value:value,to:to,rank:rank}=this.cursor;for(;i0;)i++;insert(this.active,i,value),insert(this.activeTo,i,to),insert(this.activeRank,i,rank),trackOpen&&insert(trackOpen,i,this.cursor.from),this.minActive=findMinIndex(this.active,this.activeTo)}next(){let from=this.to,wasPoint=this.point;this.point=null;let trackOpen=this.openStart<0?[]:null;for(;;){let a=this.minActive;if(a>-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a],this.endSide=this.active[a].endSide;break}this.removeActive(a),trackOpen&&remove(trackOpen,a)}else{if(!this.cursor.value){this.to=this.endSide=1e9;break}if(this.cursor.from>from){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}{let nextVal=this.cursor.value;if(nextVal.point){if(!(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0&&trackOpen[i]=0&&!(this.activeRank[i]to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)&&active.push(this.active[i]);return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}}function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff=a.to+dPos-b.to||a.endSide-b.endSide,end=diff<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff<=0&&a.next(),diff>=0&&b.next()}}function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i=index;i--)array[i+1]=array[i];array[index]=value}function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:string.length,n=0;for(let i=0;i=col)return i;if(i==string.length)break;n+=9==string.charCodeAt(i)?tabSize-n%tabSize:1,i=findClusterBreak(string,i)}return!0===strict?-1:string.length}const COUNT="undefined"==typeof Symbol?"__ͼ":Symbol.for("ͼ"),SET="undefined"==typeof Symbol?"__styleSet"+Math.floor(1e8*Math.random()):Symbol("styleSet"),top="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};class StyleModule{constructor(spec,options){this.rules=[];let{finish:finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}function render(selectors,spec,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&"keyframes"==isAt[1];if(isAt&&null==spec)return target.push(selectors[0]+";");for(let prop in spec){let value=spec[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map((part=>selectors.map((sel=>part.replace(/&/,sel))))).reduce(((a,b)=>a.concat(b))),value,target);else if(value&&"object"==typeof value){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else null!=value&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,(l=>"-"+l.toLowerCase()))+": "+value+";")}(local.length||keyframes)&&target.push((!finish||isAt||isKeyframes?selectors:selectors.map(finish)).join(", ")+" {"+local.join(" ")+"}")}for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join("\n")}static newName(){let id=top[COUNT]||1;return top[COUNT]=id+1,"ͼ"+id.toString(36)}static mount(root,modules,options){let set=root[SET],nonce=options&&options.nonce;set?nonce&&set.setNonce(nonce):set=new StyleSet(root,nonce),set.mount(Array.isArray(modules)?modules:[modules],root)}}let adoptedSet=new Map;class StyleSet{constructor(root,nonce){let doc=root.ownerDocument||root,win=doc.defaultView;if(!root.head&&root.adoptedStyleSheets&&win.CSSStyleSheet){let adopted=adoptedSet.get(doc);if(adopted)return root[SET]=adopted;this.sheet=new win.CSSStyleSheet,adoptedSet.set(doc,this)}else this.styleTag=doc.createElement("style"),nonce&&this.styleTag.setAttribute("nonce",nonce);this.modules=[],root[SET]=this}mount(modules,root){let sheet=this.sheet,pos=0,j=0;for(let i=0;i-1&&(this.modules.splice(index,1),j--,index=-1),-1==index){if(this.modules.splice(j++,0,mod),sheet)for(let k=0;k",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mac="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),ie$1="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(i=1;i<=24;i++)base[i+111]="F"+i;for(i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code in base)shift.hasOwnProperty(code)||(shift[code]=base[code]);function getSelection(root){let target;return target=11==root.nodeType?root.getSelection?root:root.ownerDocument:root,target.getSelection()}function contains(dom,node){return!!node&&(dom==node||dom.contains(1!=node.nodeType?node.parentNode:node))}function hasSelection(dom,selection){if(!selection.anchorNode)return!1;try{return contains(dom,selection.anchorNode)}catch(_){return!1}}function clientRectsFor(dom){return 3==dom.nodeType?textRange(dom,0,dom.nodeValue.length).getClientRects():1==dom.nodeType?dom.getClientRects():[]}function isEquivalentPosition(node,off,targetNode,targetOff){return!!targetNode&&(scanFor(node,off,targetNode,targetOff,-1)||scanFor(node,off,targetNode,targetOff,1))}function domIndex(node){for(var index=0;;index++)if(!(node=node.previousSibling))return index}function isBlockElement(node){return 1==node.nodeType&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName)}function scanFor(node,off,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off==targetOff)return!0;if(off==(dir<0?0:maxOffset(node))){if("DIV"==node.nodeName)return!1;let parent=node.parentNode;if(!parent||1!=parent.nodeType)return!1;off=domIndex(node)+(dir<0?0:1),node=parent}else{if(1!=node.nodeType)return!1;if(1==(node=node.childNodes[off+(dir<0?-1:0)]).nodeType&&"false"==node.contentEditable)return!1;off=dir<0?maxOffset(node):0}}}function maxOffset(node){return 3==node.nodeType?node.nodeValue.length:node.childNodes.length}function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}function windowRect(win){let vp=win.visualViewport;return vp?{left:0,right:vp.width,top:0,bottom:vp.height}:{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}function getScale(elt,rect){let scaleX=rect.width/elt.offsetWidth,scaleY=rect.height/elt.offsetHeight;return(scaleX>.995&&scaleX<1.005||!isFinite(scaleX)||Math.abs(rect.width-elt.offsetWidth)<1)&&(scaleX=1),(scaleY>.995&&scaleY<1.005||!isFinite(scaleY)||Math.abs(rect.height-elt.offsetHeight)<1)&&(scaleY=1),{scaleX:scaleX,scaleY:scaleY}}class DOMSelectionState{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(domSel){return this.anchorNode==domSel.anchorNode&&this.anchorOffset==domSel.anchorOffset&&this.focusNode==domSel.focusNode&&this.focusOffset==domSel.focusOffset}setRange(range){let{anchorNode:anchorNode,focusNode:focusNode}=range;this.set(anchorNode,Math.min(range.anchorOffset,anchorNode?maxOffset(anchorNode):0),focusNode,Math.min(range.focusOffset,focusNode?maxOffset(focusNode):0))}set(anchorNode,anchorOffset,focusNode,focusOffset){this.anchorNode=anchorNode,this.anchorOffset=anchorOffset,this.focusNode=focusNode,this.focusOffset=focusOffset}}let scratchRange,preventScrollSupported=null;function focusPreventScroll(dom){if(dom.setActive)return dom.setActive();if(preventScrollSupported)return dom.focus(preventScrollSupported);let stack=[];for(let cur=dom;cur&&(stack.push(cur,cur.scrollTop,cur.scrollLeft),cur!=cur.ownerDocument);cur=cur.parentNode);if(dom.focus(null==preventScrollSupported?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),!preventScrollSupported){preventScrollSupported=!1;for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:from,range=scratchRange||(scratchRange=document.createRange());return range.setEnd(node,to),range.setStart(node,from),range}function dispatchKey(elt,name,code,mods){let options={key:name,code:name,keyCode:code,which:code,cancelable:!0};mods&&({altKey:options.altKey,ctrlKey:options.ctrlKey,shiftKey:options.shiftKey,metaKey:options.metaKey}=mods);let down=new KeyboardEvent("keydown",options);down.synthetic=!0,elt.dispatchEvent(down);let up=new KeyboardEvent("keyup",options);return up.synthetic=!0,elt.dispatchEvent(up),down.defaultPrevented||up.defaultPrevented}function clearAttributes(node){for(;node.attributes.length;)node.removeAttributeNode(node.attributes[0])}function isScrolledToBottom(elt){return elt.scrollTop>Math.max(1,elt.scrollHeight-elt.clientHeight-4)}function textNodeBefore(startNode,startOffset){for(let node=startNode,offset=startOffset;;){if(3==node.nodeType&&offset>0)return{node:node,offset:offset};if(1==node.nodeType&&offset>0){if("false"==node.contentEditable)return null;node=node.childNodes[offset-1],offset=maxOffset(node)}else{if(!node.parentNode||isBlockElement(node))return null;offset=domIndex(node),node=node.parentNode}}}function textNodeAfter(startNode,startOffset){for(let node=startNode,offset=startOffset;;){if(3==node.nodeType&&offset2&&void 0!==arguments[2])||arguments[2];this.node=node,this.offset=offset,this.precise=precise}static before(dom,precise){return new DOMPos(dom.parentNode,domIndex(dom),precise)}static after(dom,precise){return new DOMPos(dom.parentNode,domIndex(dom)+1,precise)}}const noChildren=[];class ContentView{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(view){let pos=this.posAtStart;for(let child of this.children){if(child==view)return pos;pos+=child.length+child.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(view){return this.posBefore(view)+view.length}sync(view,track){if(2&this.flags){let next,parent=this.dom,prev=null;for(let child of this.children){if(7&child.flags){if(!child.dom&&(next=prev?prev.nextSibling:parent.firstChild)){let contentView=ContentView.get(next);(!contentView||!contentView.parent&&contentView.canReuseDOM(child))&&child.reuseDOM(next)}child.sync(view,track),child.flags&=-8}if(next=prev?prev.nextSibling:parent.firstChild,track&&!track.written&&track.node==parent&&next!=child.dom&&(track.written=!0),child.dom.parentNode==parent)for(;next&&next!=child.dom;)next=rm$1(next);else parent.insertBefore(child.dom,next);prev=child.dom}for(next=prev?prev.nextSibling:parent.firstChild,next&&track&&track.node==parent&&(track.written=!0);next;)next=rm$1(next)}else if(1&this.flags)for(let child of this.children)7&child.flags&&(child.sync(view,track),child.flags&=-8)}reuseDOM(_dom){}localPosFromDOM(node,offset){let after;if(node==this.dom)after=this.dom.childNodes[offset];else{let bias=0==maxOffset(node)?0:0==offset?-1:1;for(;;){let parent=node.parentNode;if(parent==this.dom)break;0==bias&&parent.firstChild!=parent.lastChild&&(bias=node==parent.firstChild?-1:1),node=parent}after=bias<0?node:node.nextSibling}if(after==this.dom.firstChild)return 0;for(;after&&!ContentView.get(after);)after=after.nextSibling;if(!after)return this.length;for(let i=0,pos=0;;i++){let child=this.children[i];if(child.dom==after)return pos;pos+=child.length+child.breakAfter}}domBoundsAround(from,to){let offset=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,fromI=-1,fromStart=-1,toI=-1,toEnd=-1;for(let i=0,pos=offset,prevEnd=offset;ito)return child.domBoundsAround(from,to,pos);if(end>=from&&-1==fromI&&(fromI=i,fromStart=pos),pos>to&&child.dom.parentNode==this.dom){toI=i,toEnd=prevEnd;break}prevEnd=end,pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI=0?this.children[toI].dom:null}}markDirty(){let andParent=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.flags|=2,this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList&&(parent.flags|=2),1&parent.flags)return;parent.flags|=1,childList=!1}}setParent(parent){this.parent!=parent&&(this.parent=parent,7&this.flags&&this.markParentsDirty(!0))}setDOM(dom){this.dom!=dom&&(this.dom&&(this.dom.cmView=null),this.dom=dom,dom.cmView=this)}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to){let children=arguments.length>2&&void 0!==arguments[2]?arguments[2]:noChildren;this.markDirty();for(let i=from;i0&&void 0!==arguments[0]?arguments[0]:this.length;return new ChildCursor(this.children,pos,this.children.length)}childPos(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.childCursor().findPos(pos,bias)}toString(){let name=this.constructor.name.replace("View","");return name+(this.children.length?"("+this.children.join()+")":this.length?"["+("Text"==name?this.text:this.length)+"]":"")+(this.breakAfter?"#":"")}static get(node){return node.cmView}get isEditable(){return!0}get isWidget(){return!1}get isHidden(){return!1}merge(from,to,source,hasStart,openStart,openEnd){return!1}become(other){return!1}canReuseDOM(other){return other.constructor==this.constructor&&!(8&(this.flags|other.flags))}getSide(){return 0}destroy(){for(let child of this.children)child.parent==this&&child.destroy();this.parent=null}}function rm$1(dom){let next=dom.nextSibling;return dom.parentNode.removeChild(dom),next}ContentView.prototype.breakAfter=0;class ChildCursor{constructor(children,pos,i){this.children=children,this.pos=pos,this.i=i,this.off=0}findPos(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;for(;;){if(pos>this.pos||pos==this.pos&&(bias>0||0==this.i||this.children[this.i-1].breakAfter))return this.off=pos-this.pos,this;let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}}function replaceRange(parent,fromI,fromOff,toI,toOff,insert,breakAtStart,openStart,openEnd){let{children:children}=parent,before=children.length?children[fromI]:null,last=insert.length?insert[insert.length-1]:null,breakAtEnd=last?last.breakAfter:breakAtStart;if(!(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert.length<2&&before.merge(fromOff,toOff,insert.length?last:null,0==fromOff,openStart,openEnd))){if(toI0&&(!breakAtStart&&insert.length&&before.merge(fromOff,before.length,insert[0],!1,openStart,0)?before.breakAfter=insert.shift().breakAfter:(fromOff2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/Linux|X11/.test(nav.platform),ie:ie,ie_version:ie_upto10?doc.documentMode||6:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko:gecko,gecko_version:gecko?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios:ios,android:/Android\b/.test(nav.userAgent),webkit:webkit,safari:safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,tabSize:null!=doc.documentElement.style.tabSize?"tab-size":"-moz-tab-size"};class TextView extends ContentView{constructor(text){super(),this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(view,track){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(track&&track.node==this.dom&&(track.written=!0),this.dom.nodeValue=this.text)}reuseDOM(dom){3==dom.nodeType&&this.createDOM(dom)}merge(from,to,source){return!(8&this.flags||source&&(!(source instanceof TextView)||this.length-(to-from)+source.length>256||8&source.flags))&&(this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to),this.markDirty(),!0)}split(from){let result=new TextView(this.text.slice(from));return this.text=this.text.slice(0,from),this.markDirty(),result.flags|=8&this.flags,result}localPosFromDOM(node,offset){return node==this.dom?offset:offset?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset){return{from:offset,to:offset+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return function(text,pos,side){let length=text.nodeValue.length;pos>length&&(pos=length);let from=pos,to=pos,flatten=0;0==pos&&side<0||pos==length&&side>=0?browser.chrome||browser.gecko||(pos?(from--,flatten=1):to=0)?0:rects.length-1];browser.safari&&!flatten&&0==rect.width&&(rect=Array.prototype.find.call(rects,(r=>r.width))||rect);return flatten?flattenRect(rect,flatten<0):rect||null}(this.dom,pos,side)}}class MarkView extends ContentView{constructor(mark){let children=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],length=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;super(),this.mark=mark,this.children=children,this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){if(clearAttributes(dom),this.mark.class&&(dom.className=this.mark.class),this.mark.attrs)for(let name in this.mark.attrs)dom.setAttribute(name,this.mark.attrs[name]);return dom}canReuseDOM(other){return super.canReuseDOM(other)&&!(8&(this.flags|other.flags))}reuseDOM(node){node.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(node),this.flags|=6)}sync(view,track){this.dom?4&this.flags&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(view,track)}merge(from,to,source,_hasStart,openStart,openEnd){return(!source||!(!(source instanceof MarkView&&source.mark.eq(this.mark))||from&&openStart<=0||tofrom&&result.push(off=from&&(detachFrom=i),off=end,i++}let length=this.length-from;return this.length=from,detachFrom>-1&&(this.children.length=detachFrom,this.markDirty()),new MarkView(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}}class WidgetView extends ContentView{static create(widget,length,side){return new WidgetView(widget,length,side)}constructor(widget,length,side){super(),this.widget=widget,this.length=length,this.side=side,this.prevWidget=null}split(from){let result=WidgetView.create(this.widget,this.length-from,this.side);return this.length-=from,result}sync(view){this.dom&&this.widget.updateDOM(this.dom,view)||(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){return!(source&&(!(source instanceof WidgetView&&this.widget.compare(source.widget))||from>0&&openStart<=0||to0)?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}domBoundsAround(){return null}coordsAt(pos,side){let custom=this.widget.coordsAt(this.dom,pos,side);if(custom)return custom;let rects=this.dom.getClientRects(),rect=null;if(!rects.length)return null;let fromBack=this.side?this.side<0:pos>0;for(let i=fromBack?rects.length-1:0;rect=rects[i],!(pos>0?0==i:i==rects.length-1||rect.top0?DOMPos.before(this.dom):DOMPos.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(pos){return this.dom.getBoundingClientRect()}get overrideDOMText(){return Text.empty}get isHidden(){return!0}}function inlineDOMAtPos(parent,pos){let dom=parent.dom,{children:children}=parent,i=0;for(let off=0;ioff&&pos0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j0&&view instanceof MarkView&&children.length&&(last=children[children.length-1])instanceof MarkView&&last.mark.eq(view.mark)?joinInlineInto(last,view.children[0],open-1):(children.push(view),view.setParent(parent)),parent.length+=view.length}function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;!function scan(view,pos){for(let i=0,off=0;i=pos&&(child.children.length?scan(child,pos-off):(!after||after.isHidden&&side>0)&&(end>pos||off==end&&child.getSide()>0)?(after=child,afterPos=pos-off):(off-1?1:0)!=keysB.length-(ignore&&keysB.indexOf(ignore)>-1?1:0))return!1;for(let key of keysA)if(key!=ignore&&(-1==keysB.indexOf(key)||a[key]!==b[key]))return!1;return!0}function updateAttrs(dom,prev,attrs){let changed=!1;if(prev)for(let name in prev)attrs&&name in attrs||(changed=!0,"style"==name?dom.style.cssText="":dom.removeAttribute(name));if(attrs)for(let name in attrs)prev&&prev[name]==attrs[name]||(changed=!0,"style"==name?dom.style.cssText=attrs[name]:dom.setAttribute(name,attrs[name]));return changed}function getAttrs$1(dom){let attrs=Object.create(null);for(let i=0;i0&&0==this.children[i-1].length;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=at,end}transferDOM(other){this.dom&&(this.markDirty(),other.setDOM(this.dom),other.prevAttrs=void 0===this.prevAttrs?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(attrs){attrsEq(this.attrs,attrs)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=attrs)}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;attrs&&(this.attrs=combineAttrs(attrs,this.attrs||{})),cls&&(this.attrs=combineAttrs({class:cls},this.attrs||{}))}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){"DIV"==node.nodeName&&(this.setDOM(node),this.flags|=6)}sync(view,track){var _a;this.dom?4&this.flags&&(clearAttributes(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),void 0!==this.prevAttrs&&(updateAttrs(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(view,track);let last=this.dom.lastChild;for(;last&&ContentView.get(last)instanceof MarkView;)last=last.lastChild;if(!(last&&this.length&&("BR"==last.nodeName||0!=(null===(_a=ContentView.get(last))||void 0===_a?void 0:_a.isEditable)||browser.ios&&this.children.some((ch=>ch instanceof TextView))))){let hack=document.createElement("BR");hack.cmIgnore=!0,this.dom.appendChild(hack)}}measureTextSize(){if(0==this.children.length||this.length>20)return null;let textHeight,totalWidth=0;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(1!=rects.length)return null;totalWidth+=rects[0].width,textHeight=rects[0].height}return totalWidth?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length,textHeight:textHeight}:null}coordsAt(pos,side){let rect=coordsInChildren(this,pos,side);if(!this.children.length&&rect&&this.parent){let{heightOracle:heightOracle}=this.parent.view.viewState,height=rect.bottom-rect.top;if(Math.abs(height-heightOracle.lineHeight)<2&&heightOracle.textHeight=pos){if(block instanceof LineView)return block;if(end>pos)break}off=end+block.breakAfter}return null}}class BlockWidgetView extends ContentView{constructor(widget,length,deco){super(),this.widget=widget,this.length=length,this.deco=deco,this.breakAfter=0,this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){return!(source&&(!(source instanceof BlockWidgetView&&this.widget.compare(source.widget))||from>0&&openStart<=0||to0)}}class WidgetType{eq(widget){return!1}updateDOM(dom,view){return!1}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(event){return!0}coordsAt(dom,pos,side){return null}get isHidden(){return!1}get editable(){return!1}destroy(dom){}}var BlockType=function(BlockType){return BlockType[BlockType.Text=0]="Text",BlockType[BlockType.WidgetBefore=1]="WidgetBefore",BlockType[BlockType.WidgetAfter=2]="WidgetAfter",BlockType[BlockType.WidgetRange=3]="WidgetRange",BlockType}(BlockType||(BlockType={}));class Decoration extends RangeValue{constructor(startSide,endSide,widget,spec){super(),this.startSide=startSide,this.endSide=endSide,this.widget=widget,this.spec=spec}get heightRelevant(){return!1}static mark(spec){return new MarkDecoration(spec)}static widget(spec){let side=Math.max(-1e4,Math.min(1e4,spec.side||0)),block=!!spec.block;return side+=block&&!spec.inlineOrder?side>0?3e8:-4e8:side>0?1e8:-1e8,new PointDecoration(spec,side,side,block,spec.widget||null,!1)}static replace(spec){let startSide,endSide,block=!!spec.block;if(spec.isBlockGap)startSide=-5e8,endSide=4e8;else{let{start:start,end:end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1,endSide=1+(end?block?2e8:1:-6e8)}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,!0)}static line(spec){return new LineDecoration(spec)}static set(of){let sort=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return RangeSet.of(of,sort)}hasHeight(){return!!this.widget&&this.widget.estimatedHeight>-1}}Decoration.none=RangeSet.empty;class MarkDecoration extends Decoration{constructor(spec){let{start:start,end:end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec),this.tagName=spec.tagName||"span",this.class=spec.class||"",this.attrs=spec.attributes||null}eq(other){var _a,_b;return this==other||other instanceof MarkDecoration&&this.tagName==other.tagName&&(this.class||(null===(_a=this.attrs)||void 0===_a?void 0:_a.class))==(other.class||(null===(_b=other.attrs)||void 0===_b?void 0:_b.class))&&attrsEq(this.attrs,other.attrs,"class")}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}}MarkDecoration.prototype.point=!1;class LineDecoration extends Decoration{constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof LineDecoration&&this.spec.class==other.spec.class&&attrsEq(this.spec.attributes,other.spec.attributes)}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(to!=from)throw new RangeError("Line decoration ranges must be zero-length");return super.range(from,to)}}LineDecoration.prototype.mapMode=MapMode.TrackBefore,LineDecoration.prototype.point=!0;class PointDecoration extends Decoration{constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec),this.block=block,this.isReplace=isReplace,this.mapMode=block?startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter:MapMode.TrackDel}get type(){return this.startSide!=this.endSide?BlockType.WidgetRange:this.startSide<=0?BlockType.WidgetBefore:BlockType.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(other){return other instanceof PointDecoration&&(a=this.widget,b=other.widget,a==b||!!(a&&b&&a.compare(b)))&&this.block==other.block&&this.startSide==other.startSide&&this.endSide==other.endSide;var a,b}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(this.isReplace&&(from>to||from==to&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&to!=from)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(from,to)}}function getInclusive(spec){let block=arguments.length>1&&void 0!==arguments[1]&&arguments[1],{inclusiveStart:start,inclusiveEnd:end}=spec;return null==start&&(start=spec.inclusive),null==end&&(end=spec.inclusive),{start:null!=start?start:block,end:null!=end?end:block}}function addRange(from,to,ranges){let margin=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,last=ranges.length-1;last>=0&&ranges[last]+margin>=from?ranges[last]=Math.max(ranges[last],to):ranges.push(from,to)}PointDecoration.prototype.point=!0;class ContentBuilder{constructor(doc,pos,end,disallowBlockEffectsFor){this.doc=doc,this.pos=pos,this.end=end,this.disallowBlockEffectsFor=disallowBlockEffectsFor,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=doc.iter(),this.skip=pos}posCovered(){if(0==this.content.length)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last=this.content[this.content.length-1];return!(last.breakAfter||last instanceof BlockWidgetView&&last.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new LineView),this.atCursorPos=!0),this.curLine}flushBuffer(){let active=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.bufferMarks;this.pendingBuffer&&(this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length),this.pendingBuffer=0)}addBlockWidget(view){this.flushBuffer(),this.curLine=null,this.content.push(view)}finish(openEnd){this.pendingBuffer&&openEnd<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,this.posCovered()||openEnd&&this.content.length&&this.content[this.content.length-1]instanceof BlockWidgetView||this.getLine()}buildText(length,active,openStart){for(;length>0;){if(this.textOff==this.text.length){let{value:value,lineBreak:lineBreak,done:done}=this.cursor.next(this.skip);if(this.skip=0,done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,length--;continue}this.text=value,this.textOff=0}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(active.length-openStart)),this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart),this.atCursorPos=!0,this.textOff+=take,length-=take,openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart),this.pos=to,this.openStart<0&&(this.openStart=openStart)}point(from,to,deco,active,openStart,index){if(this.disallowBlockEffectsFor[index]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration)if(deco.block)deco.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new BlockWidgetView(deco.widget||NullWidget.block,len,deco));else{let view=WidgetView.create(deco.widget||NullWidget.inline,len,len?0:deco.startSide),cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from0),cursorAfter=!view.isEditable&&(fromactive.length||deco.startSide<=0),line=this.getLine();2!=this.pendingBuffer||cursorBefore||view.isEditable||(this.pendingBuffer=0),this.flushBuffer(active),cursorBefore&&(line.append(wrapMarks(new WidgetBufferView(1),active),openStart),openStart=active.length+Math.max(0,openStart-active.length)),line.append(wrapMarks(view,active),openStart),this.atCursorPos=cursorAfter,this.pendingBuffer=cursorAfter?fromactive.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=active.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(deco);len&&(this.textOff+len<=this.text.length?this.textOff+=len:(this.skip+=len-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=to),this.openStart<0&&(this.openStart=openStart)}static build(text,from,to,decorations,dynamicDecorationMap){let builder=new ContentBuilder(text,from,to,dynamicDecorationMap);return builder.openEnd=RangeSet.spans(decorations,from,to,builder),builder.openStart<0&&(builder.openStart=builder.openEnd),builder.finish(builder.openEnd),builder}}function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view}class NullWidget extends WidgetType{constructor(tag){super(),this.tag=tag}eq(other){return other.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}NullWidget.inline=new NullWidget("span"),NullWidget.block=new NullWidget("div");var Direction=function(Direction){return Direction[Direction.LTR=0]="LTR",Direction[Direction.RTL=1]="RTL",Direction}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i=index){if(span.level==level)return i;(maybe<0||(0!=assoc?assoc<0?span.fromindex:order[maybe].level>span.level))&&(maybe=i)}}if(maybe<0)throw new RangeError("Index out of range");return maybe}}function isolatesEq(a,b){if(a.length!=b.length)return!1;for(let i=0;iiCh&&order.push(new BidiSpan(iCh,iso.from,localLevel)),computeSectionOrder(line,iso.direction==LTR!=!(localLevel%2)?level+1:level,baseLevel,iso.inner,iso.from,iso.to,order),iCh=iso.to}iScan=iso.to}else{if(iScan==to||(sameDir?types[iScan]!=ourType:types[iScan]==ourType))break;iScan++}recurse?emitSpans(line,iCh,iScan,level+1,baseLevel,recurse,order):iChfrom;){let sameDir=!0,isNum=!1;if(!iI||iCh>isolates[iI-1].to){let next=types[iCh-1];next!=ourType&&(sameDir=!1,isNum=16==next)}let recurse=sameDir||1!=ourType?null:[],localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI&&iScan==isolates[iI-1].to){if(isNum)break run;let iso=isolates[--iI];if(!sameDir)for(let upto=iso.from,jI=iI;;){if(upto==from)break run;if(!jI||isolates[jI-1].to!=upto){if(types[upto-1]==ourType)break run;break}upto=isolates[--jI].from}if(recurse)recurse.push(iso);else{iso.to=0;sJ-=3)if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2],type=2&flags?outerType:4&flags?1&flags?oppositeType:outerType:0;type&&(types[i]=types[BracketStack[sJ]]=type),sI=sJ;break}}else{if(189==BracketStack.length)break;BracketStack[sI++]=i,BracketStack[sI++]=ch,BracketStack[sI++]=context}else if(2==(type=types[i])||1==type){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur=BracketStack[sJ+2];if(2&cur)break;if(embed)BracketStack[sJ+2]|=2;else{if(4&cur)break;BracketStack[sJ+2]|=4}}}}}(line,from,to,isolates,outerType),function(rFrom,rTo,isolates,outerType){for(let iI=0,prev=outerType;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iIi;)j==fromJ&&(j=isolates[--jI].from,fromJ=jI?isolates[jI-1].to:rFrom),types[--j]=replace;i=end}else prev=type,i++}}}(from,to,isolates,outerType),emitSpans(line,from,to,level,baseLevel,isolates,order)}function trivialOrder(length){return[new BidiSpan(0,length,0)]}let movedOver="";function moveVisually(line,order,dir,start,forward){var _a;let startIndex=start.head-line.from,spanI=BidiSpan.find(order,startIndex,null!==(_a=start.bidiLevel)&&void 0!==_a?_a:-1,start.assoc),span=order[spanI],spanEnd=span.side(forward,dir);if(startIndex==spanEnd){let nextI=spanI+=forward?1:-1;if(nextI<0||nextI>=order.length)return null;span=order[spanI=nextI],startIndex=span.side(!forward,dir),spanEnd=span.side(forward,dir)}let nextIndex=findClusterBreak(line.text,startIndex,span.forward(forward,dir));(nextIndexspan.to)&&(nextIndex=spanEnd),movedOver=line.text.slice(Math.min(startIndex,nextIndex),Math.max(startIndex,nextIndex));let nextSpan=spanI==(forward?order.length-1:0)?null:order[spanI+(forward?1:-1)];return nextSpan&&nextIndex==spanEnd&&nextSpan.level+(forward?0:1)values.some((x=>x))}),nativeSelectionHidden=Facet.define({combine:values=>values.some((x=>x))}),scrollHandler=Facet.define();class ScrollTarget{constructor(range){let y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"nearest",x=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"nearest",yMargin=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5,xMargin=arguments.length>4&&void 0!==arguments[4]?arguments[4]:5,isSnapshot=arguments.length>5&&void 0!==arguments[5]&&arguments[5];this.range=range,this.y=y,this.x=x,this.yMargin=yMargin,this.xMargin=xMargin,this.isSnapshot=isSnapshot}map(changes){return changes.empty?this:new ScrollTarget(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(state){return this.range.to<=state.doc.length?this:new ScrollTarget(EditorSelection.cursor(state.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const scrollIntoView$1=StateEffect.define({map:(t,ch)=>t.map(ch)}),setEditContextFormatting=StateEffect.define();function logException(state,exception,context){let handler=state.facet(exceptionSink);handler.length?handler[0](exception):window.onerror?window.onerror(String(exception),context,void 0,void 0,exception):context?console.error(context+":",exception):console.error(exception)}const editable=Facet.define({combine:values=>!values.length||values[0]});let nextPluginID=0;const viewPlugin=Facet.define();class ViewPlugin{constructor(id,create,domEventHandlers,domEventObservers,buildExtensions){this.id=id,this.create=create,this.domEventHandlers=domEventHandlers,this.domEventObservers=domEventObservers,this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers:eventHandlers,eventObservers:eventObservers,provide:provide,decorations:deco}=spec||{};return new ViewPlugin(nextPluginID++,create,eventHandlers,eventObservers,(plugin=>{let ext=[viewPlugin.of(plugin)];return deco&&ext.push(decorations.of((view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none}))),provide&&ext.push(provide(plugin)),ext}))}static fromClass(cls,spec){return ViewPlugin.define((view=>new cls(view)),spec)}}class PluginInstance{constructor(spec){this.spec=spec,this.mustUpdate=null,this.value=null}update(view){if(this.value){if(this.mustUpdate){let update=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(update)}catch(e){if(logException(update.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch(_){}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(view){var _a;if(null===(_a=this.value)||void 0===_a?void 0:_a.destroy)try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const editorAttributes=Facet.define(),contentAttributes=Facet.define(),decorations=Facet.define(),outerDecorations=Facet.define(),atomicRanges=Facet.define(),bidiIsolatedRanges=Facet.define();function getIsolatedRanges(view,line){let isolates=view.state.facet(bidiIsolatedRanges);if(!isolates.length)return isolates;let sets=isolates.map((i=>i instanceof Function?i(view):i)),result=[];return RangeSet.spans(sets,line.from,line.to,{point(){},span(fromDoc,toDoc,active,open){let from=fromDoc-line.from,to=toDoc-line.from,level=result;for(let i=active.length-1;i>=0;i--,open--){let update,direction=active[i].spec.bidiIsolate;if(null==direction&&(direction=autoDirection(line.text,from,to)),open>0&&level.length&&(update=level[level.length-1]).to==from&&update.direction==direction)update.to=to,level=update.inner;else{let add={from:from,to:to,direction:direction,inner:[]};level.push(add),level=add.inner}}}}),result}const scrollMargins=Facet.define();function getScrollMargins(view){let left=0,right=0,top=0,bottom=0;for(let source of view.state.facet(scrollMargins)){let m=source(view);m&&(null!=m.left&&(left=Math.max(left,m.left)),null!=m.right&&(right=Math.max(right,m.right)),null!=m.top&&(top=Math.max(top,m.top)),null!=m.bottom&&(bottom=Math.max(bottom,m.bottom)))}return{left:left,right:right,top:top,bottom:bottom}}const styleModule=Facet.define();class ChangedRange{constructor(fromA,toA,fromB,toB){this.fromA=fromA,this.toA=toA,this.fromB=fromB,this.toB=toB}join(other){return new ChangedRange(Math.min(this.fromA,other.fromA),Math.max(this.toA,other.toA),Math.min(this.fromB,other.fromB),Math.max(this.toB,other.toB))}addToSet(set){let i=set.length,me=this;for(;i>0;i--){let range=set[i-1];if(!(range.fromA>me.toA)){if(range.toAend)break;rI+=2}if(!next)return result;new ChangedRange(next.fromA,next.toA,next.fromB,next.toB).addToSet(result),posA=next.toA,posB=next.toB}}}class ViewUpdate{constructor(view,state,transactions){this.view=view,this.state=state,this.transactions=transactions,this.flags=0,this.startState=view.state,this.changes=ChangeSet.empty(this.startState.doc.length);for(let tr of transactions)this.changes=this.changes.compose(tr.changes);let changedRanges=[];this.changes.iterChangedRanges(((fromA,toA,fromB,toB)=>changedRanges.push(new ChangedRange(fromA,toA,fromB,toB)))),this.changedRanges=changedRanges}static create(view,state,transactions){return new ViewUpdate(view,state,transactions)}get viewportChanged(){return(4&this.flags)>0}get heightChanged(){return(2&this.flags)>0}get geometryChanged(){return this.docChanged||(10&this.flags)>0}get focusChanged(){return(1&this.flags)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some((tr=>tr.selection))}get empty(){return 0==this.flags&&0==this.transactions.length}}class DocView extends ContentView{get length(){return this.view.state.doc.length}constructor(view){super(),this.view=view,this.decorations=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.editContextFormatting=Decoration.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(view.contentDOM),this.children=[new LineView],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new ChangedRange(0,0,0,view.state.doc.length)],0,null)}update(update){var _a;let changedRanges=update.changedRanges;this.minWidth>0&&changedRanges.length&&(changedRanges.every((_ref=>{let{fromA:fromA,toA:toA}=_ref;return toAthis.minWidthTo}))?(this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(update);let readCompositionAt=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&((null===(_a=this.domChanged)||void 0===_a?void 0:_a.newSel)?readCompositionAt=this.domChanged.newSel.head:function(changes,composition){let touched=!1;composition&&changes.iterChangedRanges(((from,to)=>{fromcomposition.from&&(touched=!0)}));return touched}(update.changes,this.hasComposition)||update.selectionSet||(readCompositionAt=update.state.selection.main.head));let composition=readCompositionAt>-1?function(view,changes,headPos){let found=findCompositionNode(view,headPos);if(!found)return null;let{node:textNode,from:from,to:to}=found,text=textNode.nodeValue;if(/[\n\r]/.test(text))return null;if(view.state.doc.sliceString(found.from,found.to)!=text)return null;let inv=changes.invertedDesc,range=new ChangedRange(inv.mapPos(from),inv.mapPos(to),from,to),marks=[];for(let parent=textNode.parentNode;;parent=parent.parentNode){let parentView=ContentView.get(parent);if(parentView instanceof MarkView)marks.push({node:parent,deco:parentView.mark});else{if(parentView instanceof LineView||"DIV"==parent.nodeName&&parent.parentNode==view.contentDOM)return{range:range,text:textNode,marks:marks,line:parent};if(parent==view.contentDOM)return null;marks.push({node:parent,deco:new MarkDecoration({inclusive:!0,attributes:getAttrs$1(parent),tagName:parent.tagName.toLowerCase()})})}}}(this.view,update.changes,readCompositionAt):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:from,to:to}=this.hasComposition;changedRanges=new ChangedRange(from,to,update.changes.mapPos(from,-1),update.changes.mapPos(to,1)).addToSet(changedRanges.slice())}this.hasComposition=composition?{from:composition.range.fromB,to:composition.range.toB}:null,(browser.ie||browser.chrome)&&!composition&&update&&update.state.doc.lines!=update.startState.doc.lines&&(this.forceSelection=!0);let decoDiff=function(a,b,diff){let comp=new class{constructor(){this.changes=[]}compareRange(from,to){addRange(from,to,this.changes)}comparePoint(from,to){addRange(from,to,this.changes)}};return RangeSet.compare(a,b,diff,comp),comp.changes}(this.decorations,this.updateDeco(),update.changes);return changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff),!!(7&this.flags||0!=changedRanges.length)&&(this.updateInner(changedRanges,update.startState.doc.length,composition),update.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(changes,oldLength,composition){this.view.viewState.mustMeasureContent=!0,this.updateChildren(changes,oldLength,composition);let{observer:observer}=this.view;observer.ignore((()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,track),this.flags&=-8,track&&(track.written||observer.selectionRange.focusNode!=track.node)&&(this.forceSelection=!0),this.dom.style.height=""})),this.markedForComposition.forEach((cView=>cView.flags&=-9));let gaps=[];if(this.view.viewport.from||this.view.viewport.to=0?ranges[i]:null;if(!next)break;let content,breakAtStart,openStart,openEnd,{fromA:fromA,toA:toA,fromB:fromB,toB:toB}=next;if(composition&&composition.range.fromBfromB){let before=ContentBuilder.build(this.view.state.doc,fromB,composition.range.fromB,this.decorations,this.dynamicDecorationMap),after=ContentBuilder.build(this.view.state.doc,composition.range.toB,toB,this.decorations,this.dynamicDecorationMap);breakAtStart=before.breakAtStart,openStart=before.openStart,openEnd=after.openEnd;let compLine=this.compositionView(composition);after.breakAtStart?compLine.breakAfter=1:after.content.length&&compLine.merge(compLine.length,compLine.length,after.content[0],!1,after.openStart,0)&&(compLine.breakAfter=after.content[0].breakAfter,after.content.shift()),before.content.length&&compLine.merge(0,0,before.content[before.content.length-1],!0,0,before.openEnd)&&before.content.pop(),content=before.content.concat(compLine).concat(after.content)}else({content:content,breakAtStart:breakAtStart,openStart:openStart,openEnd:openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap));let{i:toI,off:toOff}=cursor.findPos(toA,1),{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content,breakAtStart,openStart,openEnd)}composition&&this.fixCompositionDOM(composition)}updateEditContextFormatting(update){this.editContextFormatting=this.editContextFormatting.map(update.changes);for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setEditContextFormatting)&&(this.editContextFormatting=effect.value)}compositionView(composition){let cur=new TextView(composition.text.nodeValue);cur.flags|=8;for(let{deco:deco}of composition.marks)cur=new MarkView(deco,[cur],cur.length);let line=new LineView;return line.append(cur,0),line}fixCompositionDOM(composition){let fix=(dom,cView)=>{cView.flags|=8|(cView.children.some((c=>7&c.flags))?1:0),this.markedForComposition.add(cView);let prev=ContentView.get(dom);prev&&prev!=cView&&(prev.dom=null),cView.setDOM(dom)},pos=this.childPos(composition.range.fromB,1),cView=this.children[pos.i];fix(composition.line,cView);for(let i=composition.marks.length-1;i>=-1;i--)pos=cView.childPos(pos.off,1),cView=cView.children[pos.i],fix(i>=0?composition.marks[i].node:composition.text,cView)}updateSelection(){let fromPointer=arguments.length>1&&void 0!==arguments[1]&&arguments[1];!(arguments.length>0&&void 0!==arguments[0]&&arguments[0])&&this.view.observer.selectionRange.focusNode||this.view.observer.readSelectionRange();let activeElt=this.view.root.activeElement,focused=activeElt==this.dom,selectionNotFocus=!focused&&hasSelection(this.dom,this.view.observer.selectionRange)&&!(activeElt&&this.dom.contains(activeElt));if(!(focused||fromPointer||selectionNotFocus))return;let force=this.forceSelection;this.forceSelection=!1;let main=this.view.state.selection.main,anchor=this.moveToLine(this.domAtPos(main.anchor)),head=main.empty?anchor:this.moveToLine(this.domAtPos(main.head));if(browser.gecko&&main.empty&&!this.hasComposition&&(1==(pos=anchor).node.nodeType&&pos.node.firstChild&&(0==pos.offset||"false"==pos.node.childNodes[pos.offset-1].contentEditable)&&(pos.offset==pos.node.childNodes.length||"false"==pos.node.childNodes[pos.offset].contentEditable))){let dummy=document.createTextNode("");this.view.observer.ignore((()=>anchor.node.insertBefore(dummy,anchor.node.childNodes[anchor.offset]||null))),anchor=head=new DOMPos(dummy,0),force=!0}var pos;let domSel=this.view.observer.selectionRange;!force&&domSel.focusNode&&(isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)&&isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset)||this.suppressWidgetCursorChange(domSel,main))||(this.view.observer.ignore((()=>{browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&function(node,inside){for(let cur=node;cur&&cur!=inside;cur=cur.assignedSlot||cur.parentNode)if(1==cur.nodeType&&"false"==cur.contentEditable)return!0;return!1}(domSel.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let rawSel=getSelection(this.view.root);if(rawSel)if(main.empty){if(browser.gecko){let nextTo=(node=anchor.node,offset=anchor.offset,1!=node.nodeType?0:(offset&&"false"==node.childNodes[offset-1].contentEditable?1:0)|(offsetmain.head&&([anchor,head]=[head,anchor]),range.setEnd(head.node,head.offset),range.setStart(anchor.node,anchor.offset),rawSel.removeAllRanges(),rawSel.addRange(range)}else;var node,offset;selectionNotFocus&&this.view.root.activeElement==this.dom&&(this.dom.blur(),activeElt&&activeElt.focus())})),this.view.observer.setSelectionRange(anchor,head)),this.impreciseAnchor=anchor.precise?null:new DOMPos(domSel.anchorNode,domSel.anchorOffset),this.impreciseHead=head.precise?null:new DOMPos(domSel.focusNode,domSel.focusOffset)}suppressWidgetCursorChange(sel,cursor){return this.hasComposition&&cursor.empty&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)&&this.posFromDOM(sel.focusNode,sel.focusOffset)==cursor.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:view}=this,cursor=view.state.selection.main,sel=getSelection(view.root),{anchorNode:anchorNode,anchorOffset:anchorOffset}=view.observer.selectionRange;if(!(sel&&cursor.empty&&cursor.assoc&&sel.modify))return;let line=LineView.find(this,cursor.head);if(!line)return;let lineStart=line.posAtStart;if(cursor.head==lineStart||cursor.head==lineStart+line.length)return;let before=this.coordsAt(cursor.head,-1),after=this.coordsAt(cursor.head,1);if(!before||!after||before.bottom>after.top)return;let dom=this.domAtPos(cursor.head+cursor.assoc);sel.collapse(dom.node,dom.offset),sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary"),view.observer.readSelectionRange();let newRange=view.observer.selectionRange;view.docView.posFromDOM(newRange.anchorNode,newRange.anchorOffset)!=cursor.from&&sel.collapse(anchorNode,anchorOffset)}moveToLine(pos){let newPos,dom=this.dom;if(pos.node!=dom)return pos;for(let i=pos.offset;!newPos&&i=0;i--){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(view.length))}return newPos?new DOMPos(newPos.node,newPos.offset,!0):pos}nearest(dom){for(let cur=dom;cur;){let domView=ContentView.get(cur);if(domView&&domView.rootView==this)return domView;cur=cur.parentNode}return null}posFromDOM(node,offset){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset)+view.posAtStart}domAtPos(pos){let{i:i,off:off}=this.childCursor().findPos(pos,-1);for(;i=0;i--){let child=this.children[i],end=off-child.breakAfter,start=end-child.length;if(endpos||child.covers(1))&&(!best||child instanceof LineView&&!(best instanceof LineView&&side>=0)))best=child,bestPos=start;else if(best&&start==pos&&end==pos&&child instanceof BlockWidgetView&&Math.abs(side)<2){if(child.deco.startSide<0)break;i&&(best=null)}off=start}return best?best.coordsAt(pos-bestPos,side):null}coordsForChar(pos){let{i:i,off:off}=this.childPos(pos,1),child=this.children[i];if(!(child instanceof LineView))return null;for(;child.children.length;){let{i:i,off:childOff}=child.childPos(off,1);for(;;i++){if(i==child.children.length)return null;if((child=child.children[i]).length)break}off=childOff}if(!(child instanceof TextView))return null;let end=findClusterBreak(child.text,off);if(end==off)return null;let rects=textRange(child.dom,off,end).getClientRects();for(let i=0;iMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;ito)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();if(result.push(childRect.height),isWider){let last=child.dom.lastChild,rects=last?clientRectsFor(last):[];if(rects.length){let rect=rects[rects.length-1],width=ltr?rect.right-childRect.left:childRect.right-rect.left;width>widest&&(widest=width,this.minWidth=contentWidth,this.minWidthFrom=pos,this.minWidthTo=end)}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i:i}=this.childPos(pos,1);return"rtl"==getComputedStyle(this.children[i].dom).direction?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children)if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}let lineHeight,charWidth,textHeight,dummy=document.createElement("div");return dummy.className="cm-line",dummy.style.width="99999px",dummy.style.position="absolute",dummy.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore((()=>{this.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height,charWidth=rect?rect.width/27:7,textHeight=rect?rect.height:lineHeight,dummy.remove()})),{lineHeight:lineHeight,charWidth:charWidth,textHeight:textHeight}}childCursor(){let pos=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.length,i=this.children.length;return i&&(pos-=this.children[--i].length),new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i],end=next?next.from-1:this.length;if(end>pos){let height=(vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top)/this.view.scaleY;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:!0,inclusive:!0,isBlockGap:!0}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let i=1,allDeco=this.view.state.facet(decorations).map((d=>(this.dynamicDecorationMap[i++]="function"==typeof d)?d(this.view):d)),dynamicOuter=!1,outerDeco=this.view.state.facet(outerDecorations).map(((d,i)=>{let dynamic="function"==typeof d;return dynamic&&(dynamicOuter=!0),dynamic?d(this.view):d}));for(outerDeco.length&&(this.dynamicDecorationMap[i++]=dynamicOuter,allDeco.push(RangeSet.join(outerDeco))),this.decorations=[this.editContextFormatting,...allDeco,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];irange.anchor?-1:1);if(!rect)return;!range.empty&&(other=this.coordsAt(range.anchor,range.anchor>range.head?-1:1))&&(rect={left:Math.min(rect.left,other.left),top:Math.min(rect.top,other.top),right:Math.max(rect.right,other.right),bottom:Math.max(rect.bottom,other.bottom)});let margins=getScrollMargins(this.view),targetRect={left:rect.left-margins.left,top:rect.top-margins.top,right:rect.right+margins.right,bottom:rect.bottom+margins.bottom},{offsetWidth:offsetWidth,offsetHeight:offsetHeight}=this.view.scrollDOM;!function(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc=dom.ownerDocument,win=doc.defaultView||window;for(let cur=dom,stop=!1;cur&&!stop;)if(1==cur.nodeType){let bounding,top=cur==doc.body,scaleX=1,scaleY=1;if(top)bounding=windowRect(win);else{if(/^(fixed|sticky)$/.test(getComputedStyle(cur).position)&&(stop=!0),cur.scrollHeight<=cur.clientHeight&&cur.scrollWidth<=cur.clientWidth){cur=cur.assignedSlot||cur.parentNode;continue}let rect=cur.getBoundingClientRect();({scaleX:scaleX,scaleY:scaleY}=getScale(cur,rect)),bounding={left:rect.left,right:rect.left+cur.clientWidth*scaleX,top:rect.top,bottom:rect.top+cur.clientHeight*scaleY}}let moveX=0,moveY=0;if("nearest"==y)rect.top0&&rect.bottom>bounding.bottom+moveY&&(moveY=rect.bottom-bounding.bottom+moveY+yMargin)):rect.bottom>bounding.bottom&&(moveY=rect.bottom-bounding.bottom+yMargin,side<0&&rect.top-moveY0&&rect.right>bounding.right+moveX&&(moveX=rect.right-bounding.right+moveX+xMargin)):rect.right>bounding.right&&(moveX=rect.right-bounding.right+xMargin,side<0&&rect.leftx?rect.left-x:Math.max(0,x-rect.right)}function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}function yOverlap(a,b){return a.topb.top+1}function upTop(rect,top){return toprect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom:bottom}:rect}function domPosAtCoords(parent,x,y){let closest,closestRect,closestX,closestY,above,below,aboveRect,belowRect,closestOverlap=!1;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;idy||closestY==dy&&closestX>dx){closest=child,closestRect=rect,closestX=dx,closestY=dy;let side=dy?y0?i0)}0==dx?y>rect.bottom&&(!aboveRect||aboveRect.bottomrect.top)&&(below=child,belowRect=rect):aboveRect&&yOverlap(aboveRect,rect)?aboveRect=upBot(aboveRect,rect.bottom):belowRect&&yOverlap(belowRect,rect)&&(belowRect=upTop(belowRect,rect.top))}}if(aboveRect&&aboveRect.bottom>=y?(closest=above,closestRect=aboveRect):belowRect&&belowRect.top<=y&&(closest=below,closestRect=belowRect),!closest)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));return 3==closest.nodeType?domPosInText(closest,clipX,y):closestOverlap&&"false"!=closest.contentEditable?domPosAtCoords(closest,clipX,y):{node:parent,offset:Array.prototype.indexOf.call(parent.childNodes,closest)+(x>=(closestRect.left+closestRect.right)/2?1:0)}}function domPosInText(node,x,y){let len=node.nodeValue.length,closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;iy?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy=(rect.left+rect.right)/2,after=right;if(browser.chrome||browser.gecko){textRange(node,i).getBoundingClientRect().left==rect.right&&(after=!right)}if(dy<=0)return{node:node,offset:i+(after?1:0)};closestOffset=i+(after?1:0),closestDY=dy}}}return{node:node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}function posAtCoords(view,coords,precise){let bias=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;var _a,_b;let block,content=view.contentDOM.getBoundingClientRect(),docTop=content.top+view.viewState.paddingTop,{docHeight:docHeight}=view.viewState,{x:x,y:y}=coords,yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.viewState.heightOracle.textHeight/2,bounced=!1;block=view.elementAtHeight(yOffset),block.type!=BlockType.Text;)for(;yOffset=bias>0?block.bottom+halfLine:block.top-halfLine,!(yOffset>=0&&yOffset<=docHeight);){if(bounced)return precise?null:0;bounced=!0,bias=-bias}y=docTop+yOffset;let lineStart=block.from;if(lineStartview.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content,block,x,y);let doc=view.dom.ownerDocument,root=view.root.elementFromPoint?view.root:doc,element=root.elementFromPoint(x,y);element&&!view.contentDOM.contains(element)&&(element=null),element||(x=Math.max(content.left+1,Math.min(content.right-1,x)),element=root.elementFromPoint(x,y),element&&!view.contentDOM.contains(element)&&(element=null));let node,offset=-1;if(element&&0!=(null===(_a=view.docView.nearest(element))||void 0===_a?void 0:_a.isEditable))if(doc.caretPositionFromPoint){let pos=doc.caretPositionFromPoint(x,y);pos&&({offsetNode:node,offset:offset}=pos)}else if(doc.caretRangeFromPoint){let range=doc.caretRangeFromPoint(x,y);range&&(({startContainer:node,startOffset:offset}=range),(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset,x))&&(node=void 0))}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node:node,offset:offset}=domPosAtCoords(line.dom,x,y))}let nearest=view.docView.nearest(node);if(!nearest)return null;if(nearest.isWidget&&1==(null===(_b=nearest.dom)||void 0===_b?void 0:_b.nodeType)){let rect=nearest.dom.getBoundingClientRect();return coords.y1.5*view.defaultLineHeight){let textHeight=view.viewState.heightOracle.textHeight;into+=Math.floor((y-block.top-.5*(view.defaultLineHeight-textHeight))/textHeight)*view.viewState.heightOracle.lineLength}let content=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content,into,view.state.tabSize)}function isSuspiciousSafariCaretResult(node,offset,x){let len;if(3!=node.nodeType||offset!=(len=node.nodeValue.length))return!1;for(let next=node.nextSibling;next;next=next.nextSibling)if(1!=next.nodeType||"BR"!=next.nodeName)return!1;return textRange(node,len-1,len).getBoundingClientRect().left>x}function isSuspiciousChromeCaretResult(node,offset,x){if(0!=offset)return!1;for(let cur=node;;){let parent=cur.parentNode;if(!parent||1!=parent.nodeType||parent.firstChild!=cur)return!1;if(parent.classList.contains("cm-line"))break;cur=parent}return x-(1==node.nodeType?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect()).left>5}function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type))for(let l of line.type)if(l.to>pos||l.to==pos&&(l.to==line.to||l.type==BlockType.Text))return l;return line}function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line),direction=view.textDirectionAt(line.from);for(let cur=start,check=null;;){let next=moveVisually(line,spans,direction,cur,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur;char="\n",line=view.state.doc.line(line.number+(forward?1:-1)),spans=view.bidiSpans(line),next=view.visualLineSide(line,!forward)}if(check){if(!check(char))return cur}else{if(!by)return next;check=by(char)}cur=next}}function skipAtomicRanges(atoms,pos,bias){for(;;){let moved=0;for(let set of atoms)set.between(pos-1,pos+1,((from,to,value)=>{if(pos>from&&posf(view))),pos.from,oldPos.head>pos.from?-1:1);return newPos==pos.from?pos:EditorSelection.cursor(newPos,newPosnull)),browser.gecko&&function(doc){appliedFirefoxHack.has(doc)||(appliedFirefoxHack.add(doc),doc.addEventListener("copy",(()=>{})),doc.addEventListener("cut",(()=>{})))}(view.contentDOM.ownerDocument)}handleEvent(event){(function(view,event){if(!event.bubbles)return!0;if(event.defaultPrevented)return!1;for(let cView,node=event.target;node!=view.contentDOM;node=node.parentNode)if(!node||11==node.nodeType||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return!1;return!0})(this.view,event)&&!this.ignoreDuringComposition(event)&&("keydown"==event.type&&this.keydown(event)||this.runHandlers(event.type,event))}runHandlers(type,event){let handlers=this.handlers[type];if(handlers){for(let observer of handlers.observers)observer(this.view,event);for(let handler of handlers.handlers){if(event.defaultPrevented)break;if(handler(this.view,event)){event.preventDefault();break}}}}ensureHandlers(plugins){let handlers=computeHandlers(plugins),prev=this.handlers,dom=this.view.contentDOM;for(let type in handlers)if("scroll"!=type){let passive=!handlers[type].handlers.length,exists=prev[type];exists&&passive!=!exists.handlers.length&&(dom.removeEventListener(type,this.handleEvent),exists=null),exists||dom.addEventListener(type,this.handleEvent,{passive:passive})}for(let type in prev)"scroll"==type||handlers[type]||dom.removeEventListener(type,this.handleEvent);this.handlers=handlers}keydown(event){if(this.lastKeyCode=event.keyCode,this.lastKeyTime=Date.now(),9==event.keyCode&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&27!=event.keyCode&&modifierCodes.indexOf(event.keyCode)<0&&(this.tabFocusMode=-1),browser.android&&browser.chrome&&!event.synthetic&&(13==event.keyCode||8==event.keyCode))return this.view.observer.delayAndroidKey(event.key,event.keyCode),!0;let pending;return!browser.ios||event.synthetic||event.altKey||event.metaKey||!((pending=PendingKeys.find((key=>key.keyCode==event.keyCode)))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)?(229!=event.keyCode&&this.view.observer.forceFlush(),!1):(this.pendingIOSKey=pending||event,setTimeout((()=>this.flushIOSKey()),250),!0)}flushIOSKey(change){let key=this.pendingIOSKey;return!!key&&(!("Enter"==key.key&&change&&change.from0||!!(browser.safari&&!browser.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100)&&(this.compositionPendingKey=!1,!0))}startMouseSelection(mouseSelection){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=mouseSelection}update(update){this.view.observer.update(update),this.mouseSelection&&this.mouseSelection.update(update),this.draggedContent&&update.docChanged&&(this.draggedContent=this.draggedContent.map(update.changes)),update.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function bindHandler(plugin,handler){return(view,event)=>{try{return handler.call(plugin,event,view)}catch(e){logException(view.state,e)}}}function computeHandlers(plugins){let result=Object.create(null);function record(type){return result[type]||(result[type]={observers:[],handlers:[]})}for(let plugin of plugins){let spec=plugin.spec;if(spec&&spec.domEventHandlers)for(let type in spec.domEventHandlers){let f=spec.domEventHandlers[type];f&&record(type).handlers.push(bindHandler(plugin.value,f))}if(spec&&spec.domEventObservers)for(let type in spec.domEventObservers){let f=spec.domEventObservers[type];f&&record(type).observers.push(bindHandler(plugin.value,f))}}for(let type in handlers)record(type).handlers.push(handlers[type]);for(let type in observers)record(type).observers.push(observers[type]);return result}const PendingKeys=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],EmacsyPendingKeys="dthko",modifierCodes=[16,17,18,20,91,92,224,225];function dragScrollSpeed(dist){return.7*Math.max(0,dist)+8}class MouseSelection{constructor(view,startEvent,style,mustSelect){this.view=view,this.startEvent=startEvent,this.style=style,this.mustSelect=mustSelect,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=startEvent,this.scrollParents=function(dom){let x,y,doc=dom.ownerDocument;for(let cur=dom.parentNode;cur&&!(cur==doc.body||x&&y);)if(1==cur.nodeType)!y&&cur.scrollHeight>cur.clientHeight&&(y=cur),!x&&cur.scrollWidth>cur.clientWidth&&(x=cur),cur=cur.assignedSlot||cur.parentNode;else{if(11!=cur.nodeType)break;cur=cur.host}return{x:x,y:y}}(view.contentDOM),this.atoms=view.state.facet(atomicRanges).map((f=>f(view)));let doc=view.contentDOM.ownerDocument;doc.addEventListener("mousemove",this.move=this.move.bind(this)),doc.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=startEvent.shiftKey,this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&function(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}(view,startEvent),this.dragging=!(!function(view,event){let{main:main}=view.state.selection;if(main.empty)return!1;let sel=getSelection(view.root);if(!sel||0==sel.rangeCount)return!0;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return!0}return!1}(view,startEvent)||1!=getClickType(startEvent))&&null}start(event){!1===this.dragging&&this.select(event)}move(event){if(0==event.buttons)return this.destroy();if(this.dragging||null==this.dragging&&(a=this.startEvent,b=event,Math.max(Math.abs(a.clientX-b.clientX),Math.abs(a.clientY-b.clientY))<10))return;var a,b;this.select(this.lastEvent=event);let sx=0,sy=0,left=0,top=0,right=this.view.win.innerWidth,bottom=this.view.win.innerHeight;this.scrollParents.x&&({left:left,right:right}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:top,bottom:bottom}=this.scrollParents.y.getBoundingClientRect());let margins=getScrollMargins(this.view);event.clientX-margins.left<=left+6?sx=-dragScrollSpeed(left-event.clientX):event.clientX+margins.right>=right-6&&(sx=dragScrollSpeed(event.clientX-right)),event.clientY-margins.top<=top+6?sy=-dragScrollSpeed(top-event.clientY):event.clientY+margins.bottom>=bottom-6&&(sy=dragScrollSpeed(event.clientY-bottom)),this.setScrollSpeed(sx,sy)}up(event){null==this.dragging&&this.select(this.lastEvent),this.dragging||event.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let doc=this.view.contentDOM.ownerDocument;doc.removeEventListener("mousemove",this.move),doc.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(sx,sy){this.scrollSpeed={x:sx,y:sy},sx||sy?this.scrolling<0&&(this.scrolling=setInterval((()=>this.scroll()),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:x,y:y}=this.scrollSpeed;x&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=x,x=0),y&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=y,y=0),(x||y)&&this.view.win.scrollBy(x,y),!1===this.dragging&&this.select(this.lastEvent)}skipAtoms(sel){let ranges=null;for(let i=0;itr.isUserEvent("input.type")))?this.destroy():this.style.update(update)&&setTimeout((()=>this.select(this.lastEvent)),20)}}const handlers=Object.create(null),observers=Object.create(null),brokenClipboardAPI=browser.ie&&browser.ie_version<15||browser.ios&&browser.webkit_version<604;function doPaste(view,input){let changes,{state:state}=view,i=1,text=state.toText(input),byLine=text.lines==state.selection.ranges.length;if(null!=lastLinewiseCopy&&state.selection.ranges.every((r=>r.empty))&&lastLinewiseCopy==text.toString()){let lastLine=-1;changes=state.changeByRange((range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range:range};lastLine=line.from;let insert=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert},range:EditorSelection.cursor(range.from+insert.length)}}))}else changes=byLine?state.changeByRange((range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}})):state.replaceSelection(text);view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:!0})}function rangeForClick(view,pos,bias,type){if(1==type)return EditorSelection.cursor(pos,bias);if(2==type)return function(state,pos){let bias=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,categorize=state.charCategorizer(pos),line=state.doc.lineAt(pos),linePos=pos-line.from;if(0==line.length)return EditorSelection.cursor(pos);0==linePos?bias=1:linePos==line.length&&(bias=-1);let from=linePos,to=linePos;bias<0?from=findClusterBreak(line.text,linePos,!1):to=findClusterBreak(line.text,linePos);let cat=categorize(line.text.slice(from,to));for(;from>0;){let prev=findClusterBreak(line.text,from,!1);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}for(;to{view.inputState.lastScrollTop=view.scrollDOM.scrollTop,view.inputState.lastScrollLeft=view.scrollDOM.scrollLeft},handlers.keydown=(view,event)=>(view.inputState.setSelectionOrigin("select"),27==event.keyCode&&0!=view.inputState.tabFocusMode&&(view.inputState.tabFocusMode=Date.now()+2e3),!1),observers.touchstart=(view,e)=>{view.inputState.lastTouchTime=Date.now(),view.inputState.setSelectionOrigin("select.pointer")},observers.touchmove=view=>{view.inputState.setSelectionOrigin("select.pointer")},handlers.mousedown=(view,event)=>{if(view.observer.flush(),view.inputState.lastTouchTime>Date.now()-2e3)return!1;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle))if(style=makeStyle(view,event),style)break;if(style||0!=event.button||(style=function(view,event){let start=queryPos(view,event),type=getClickType(event),startSel=view.state.selection;return{update(update){update.docChanged&&(start.pos=update.changes.mapPos(start.pos),startSel=startSel.map(update.changes))},get(event,extend,multiple){let removed,cur=queryPos(view,event),range=rangeForClick(view,cur.pos,cur.bias,type);if(start.pos!=cur.pos&&!extend){let startRange=rangeForClick(view,start.pos,start.bias,type),from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from1&&(removed=function(sel,pos){for(let i=0;i=pos)return EditorSelection.create(sel.ranges.slice(0,i).concat(sel.ranges.slice(i+1)),sel.mainIndex==i?0:sel.mainIndex-(sel.mainIndex>i?1:0))}return null}(startSel,cur.pos))?removed:multiple?startSel.addRange(range):EditorSelection.create([range])}}}(view,event)),style){let mustFocus=!view.hasFocus;view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus)),mustFocus&&view.observer.ignore((()=>{focusPreventScroll(view.contentDOM);let active=view.root.activeElement;active&&!active.contains(view.contentDOM)&&active.blur()}));let mouseSel=view.inputState.mouseSelection;if(mouseSel)return mouseSel.start(event),!1===mouseSel.dragging}return!1};let insideY=(y,rect)=>y>=rect.top&&y<=rect.bottom,inside=(x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right;function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off=pos-line.posAtStart;if(0==off)return 1;if(off==line.length)return-1;let before=line.coordsAt(off,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off,1);return after&&inside(x,y,after)?1:before&&insideY(y,before)?-1:1}function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},!1);return{pos:pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last=lastMouseDown,lastTime=lastMouseDownTime;return lastMouseDown=event,lastMouseDownTime=Date.now(),lastMouseDownCount=!last||lastTime>Date.now()-400&&Math.abs(last.clientX-event.clientX)<2&&Math.abs(last.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},!1),{draggedContent:draggedContent}=view.inputState,del=direct&&draggedContent&&function(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}(view,event)?{from:draggedContent.from,to:draggedContent.to}:null,ins={from:dropPos,insert:text},changes=view.state.changes(del?[del,ins]:ins);view.focus(),view.dispatch({changes:changes,selection:{anchor:changes.mapPos(dropPos,-1),head:changes.mapPos(dropPos,1)},userEvent:del?"move.drop":"input.drop"}),view.inputState.draggedContent=null}handlers.dragstart=(view,event)=>{let{selection:{main:range}}=view.state;if(event.target.draggable){let cView=view.docView.nearest(event.target);if(cView&&cView.isWidget){let from=cView.posAtStart,to=from+cView.length;(from>=range.to||to<=range.from)&&(range=EditorSelection.range(from,to))}}let{inputState:inputState}=view;return inputState.mouseSelection&&(inputState.mouseSelection.dragging=!0),inputState.draggedContent=range,event.dataTransfer&&(event.dataTransfer.setData("Text",view.state.sliceDoc(range.from,range.to)),event.dataTransfer.effectAllowed="copyMove"),!1},handlers.dragend=view=>(view.inputState.draggedContent=null,!1),handlers.drop=(view,event)=>{if(!event.dataTransfer)return!1;if(view.state.readOnly)return!0;let files=event.dataTransfer.files;if(files&&files.length){let text=Array(files.length),read=0,finishFile=()=>{++read==files.length&&dropText(view,event,text.filter((s=>null!=s)).join(view.state.lineBreak),!1)};for(let i=0;i{/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)||(text[i]=reader.result),finishFile()},reader.readAsText(files[i])}return!0}{let text=event.dataTransfer.getData("Text");if(text)return dropText(view,event,text,!0),!0}return!1},handlers.paste=(view,event)=>{if(view.state.readOnly)return!0;view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;return data?(doPaste(view,data.getData("text/plain")||data.getData("text/uri-list")),!0):(function(view){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.focus(),setTimeout((()=>{view.focus(),target.remove(),doPaste(view,target.value)}),50)}(view),!1)};let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text:text,ranges:ranges,linewise:linewise}=function(state){let content=[],ranges=[],linewise=!1;for(let range of state.selection.ranges)range.empty||(content.push(state.sliceDoc(range.from,range.to)),ranges.push(range));if(!content.length){let upto=-1;for(let{from:from}of state.selection.ranges){let line=state.doc.lineAt(from);line.number>upto&&(content.push(line.text),ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})),upto=line.number}linewise=!0}return{text:content.join(state.lineBreak),ranges:ranges,linewise:linewise}}(view.state);if(!text&&!linewise)return!1;lastLinewiseCopy=linewise?text:null,"cut"!=event.type||view.state.readOnly||view.dispatch({changes:ranges,scrollIntoView:!0,userEvent:"delete.cut"});let data=brokenClipboardAPI?null:event.clipboardData;return data?(data.clearData(),data.setData("text/plain",text),!0):(function(view,text){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.value=text,target.focus(),target.selectionEnd=text.length,target.selectionStart=0,setTimeout((()=>{target.remove(),view.focus()}),50)}(view,text),!1)};const isFocusChange=Annotation.define();function focusChangeTransaction(state,focus){let effects=[];for(let getEffect of state.facet(focusChangeEffect)){let effect=getEffect(state,focus);effect&&effects.push(effect)}return effects?state.update({effects:effects,annotations:isFocusChange.of(!0)}):null}function updateForFocusChange(view){setTimeout((()=>{let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){let tr=focusChangeTransaction(view.state,focus);tr?view.dispatch(tr):view.update([])}}),10)}observers.focus=view=>{view.inputState.lastFocusTime=Date.now(),view.scrollDOM.scrollTop||!view.inputState.lastScrollTop&&!view.inputState.lastScrollLeft||(view.scrollDOM.scrollTop=view.inputState.lastScrollTop,view.scrollDOM.scrollLeft=view.inputState.lastScrollLeft),updateForFocusChange(view)},observers.blur=view=>{view.observer.clearSelectionRange(),updateForFocusChange(view)},observers.compositionstart=observers.compositionupdate=view=>{view.observer.editContext||(null==view.inputState.compositionFirstChange&&(view.inputState.compositionFirstChange=!0),view.inputState.composing<0&&(view.inputState.composing=0))},observers.compositionend=view=>{view.observer.editContext||(view.inputState.composing=-1,view.inputState.compositionEndedAt=Date.now(),view.inputState.compositionPendingKey=!0,view.inputState.compositionPendingChange=view.observer.pendingRecords().length>0,view.inputState.compositionFirstChange=null,browser.chrome&&browser.android?view.observer.flushSoon():view.inputState.compositionPendingChange?Promise.resolve().then((()=>view.observer.flush())):setTimeout((()=>{view.inputState.composing<0&&view.docView.hasComposition&&view.update([])}),50))},observers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()},handlers.beforeinput=(view,event)=>{var _a;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find((key=>key.inputType==event.inputType)))&&(view.observer.delayAndroidKey(pending.key,pending.keyCode),"Backspace"==pending.key||"Delete"==pending.key)){let startViewHeight=(null===(_a=window.visualViewport)||void 0===_a?void 0:_a.height)||0;setTimeout((()=>{var _a;((null===(_a=window.visualViewport)||void 0===_a?void 0:_a.height)||0)>startViewHeight+10&&view.hasFocus&&(view.contentDOM.blur(),view.focus())}),100)}return browser.ios&&"deleteContentForward"==event.inputType&&view.observer.flushSoon(),browser.safari&&"insertText"==event.inputType&&view.inputState.composing>=0&&setTimeout((()=>observers.compositionend(view,event)),20),!1};const appliedFirefoxHack=new Set;const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"];class HeightOracle{constructor(lineWrapping){this.lineWrapping=lineWrapping,this.doc=Text.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;return this.lineWrapping&&(lines+=Math.max(0,Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength))),this.lineHeight*lines}heightForLine(length){if(!this.lineWrapping)return this.lineHeight;return(1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5))))*this.lineHeight}setDoc(doc){return this.doc=doc,this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=!1;for(let i=0;i-1,changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;if(this.lineWrapping=lineWrapping,this.lineHeight=lineHeight,this.charWidth=charWidth,this.textHeight=textHeight,this.lineLength=lineLength,changed){this.heightSamples={};for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:2;this.length=length,this.height=height,this.flags=flags}get outdated(){return(2&this.flags)>0}set outdated(value){this.flags=(value?2:0)|-3&this.flags}setHeight(oracle,height){this.height!=height&&(Math.abs(this.height-height)>.001&&(oracle.heightChanged=!0),this.height=height)}replace(_from,_to,nodes){return HeightMap.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations,oldDoc,oracle,changes){let me=this,doc=oracle.doc;for(let i=changes.length-1;i>=0;i--){let{fromA:fromA,toA:toA,fromB:fromB,toB:toB}=changes[i],start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle.setDoc(oldDoc),0,0),end=start.to>=toA?start:me.lineAt(toA,QueryType$1.ByPosNoHeight,oracle,0,0);for(toB+=end.to-toA,toA=end.to;i>0&&start.from<=changes[i-1].toA;)fromA=changes[i-1].fromA,fromB=changes[i-1].fromB,i--,fromA2*after){let split=nodes[i-1];split.break?nodes.splice(--i,1,split.left,null,split.right):nodes.splice(--i,1,split.left,split.right),j+=1+split.break,before-=split.size}else{if(!(after>2*before))break;{let split=nodes[j];split.break?nodes.splice(j,1,split.left,null,split.right):nodes.splice(j,1,split.left,split.right),j+=2+split.break,after-=split.size}}else if(before=offset&&f(this.blockAt(0,oracle,top,offset))}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,measured=arguments.length>3?arguments[3]:void 0;return measured&&measured.from<=offset&&measured.more&&this.setHeight(oracle,measured.heights[measured.index++]),this.outdated=!1,this}toString(){return"block(".concat(this.length,")")}}class HeightMapText extends HeightMapBlock{constructor(length,height){super(length,height,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(_height,_oracle,top,offset){return new BlockInfo(offset,this.length,top,this.height,this.breaks)}replace(_from,_to,nodes){let node=nodes[0];return 1==nodes.length&&(node instanceof HeightMapText||node instanceof HeightMapGap&&4&node.flags)&&Math.abs(this.length-node.length)<10?(node instanceof HeightMapGap?node=new HeightMapText(node.length,this.height):node.height=this.height,this.outdated||(node.outdated=!1),node):HeightMap.of(nodes)}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0;return measured&&measured.from<=offset&&measured.more?this.setHeight(oracle,measured.heights[measured.index++]):(force||this.outdated)&&this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed))+this.breaks*oracle.lineHeight),this.outdated=!1,this}toString(){return"line(".concat(this.length).concat(this.collapsed?-this.collapsed:"").concat(this.widgetHeight?":"+this.widgetHeight:"",")")}}class HeightMapGap extends HeightMap{constructor(length){super(length,0)}heightMetrics(oracle,offset){let perLine,firstLine=oracle.doc.lineAt(offset).number,lastLine=oracle.doc.lineAt(offset+this.length).number,lines=lastLine-firstLine+1,perChar=0;if(oracle.lineWrapping){let totalPerLine=Math.min(this.height,oracle.lineHeight*lines);perLine=totalPerLine/lines,this.length>lines+1&&(perChar=(this.height-totalPerLine)/(this.length-lines-1))}else perLine=this.height/lines;return{firstLine:firstLine,lastLine:lastLine,perLine:perLine,perChar:perChar}}blockAt(height,oracle,top,offset){let{firstLine:firstLine,lastLine:lastLine,perLine:perLine,perChar:perChar}=this.heightMetrics(oracle,offset);if(oracle.lineWrapping){let guess=offset+(height0){let last=nodes[nodes.length-1];last instanceof HeightMapGap?nodes[nodes.length-1]=new HeightMapGap(last.length+after):nodes.push(null,new HeightMapGap(after-1))}if(from>0){let first=nodes[0];first instanceof HeightMapGap?nodes[0]=new HeightMapGap(from+first.length):nodes.unshift(new HeightMapGap(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new HeightMapGap(to-1),null)}decomposeRight(from,result){result.push(null,new HeightMapGap(this.length-from-1))}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0,end=offset+this.length;if(measured&&measured.from<=offset+this.length&&measured.more){let nodes=[],pos=Math.max(offset,measured.from),singleHeight=-1;for(measured.from>offset&&nodes.push(new HeightMapGap(measured.from-offset-1).updateHeight(oracle,offset));pos<=end&&measured.more;){let len=oracle.doc.lineAt(pos).length;nodes.length&&nodes.push(null);let height=measured.heights[measured.index++];-1==singleHeight?singleHeight=height:Math.abs(height-singleHeight)>=.001&&(singleHeight=-2);let line=new HeightMapText(len,height);line.outdated=!1,nodes.push(line),pos+=len+1}pos<=end&&nodes.push(null,new HeightMapGap(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);return(singleHeight<0||Math.abs(result.height-this.height)>=.001||Math.abs(singleHeight-this.heightMetrics(oracle,offset).perLine)>=.001)&&(oracle.heightChanged=!0),result}return(force||this.outdated)&&(this.setHeight(oracle,oracle.heightForGap(offset,offset+this.length)),this.outdated=!1),this}toString(){return"gap(".concat(this.length,")")}}class HeightMapBranch extends HeightMap{constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0)),this.left=left,this.right=right,this.size=left.size+right.size}get break(){return 1&this.flags}blockAt(height,oracle,top,offset){let mid=top+this.left.height;return heightrightOffset))return base;let subQuery=type==QueryType$1.ByPosNoHeight?QueryType$1.ByPosNoHeight:QueryType$1.ByPos;return left?base.join(this.right.lineAt(rightOffset,subQuery,oracle,rightTop,rightOffset)):this.left.lineAt(rightOffset,subQuery,oracle,top,offset).join(base)}forEachLine(from,to,oracle,top,offset,f){let rightTop=top+this.left.height,rightOffset=offset+this.left.length+this.break;if(this.break)from=rightOffset&&this.right.forEachLine(from,to,oracle,rightTop,rightOffset,f);else{let mid=this.lineAt(rightOffset,QueryType$1.ByPos,oracle,top,offset);from=from&&mid.from<=to&&f(mid),to>mid.to&&this.right.forEachLine(mid.to+1,to,oracle,rightTop,rightOffset,f)}}replace(from,to,nodes){let rightStart=this.left.length+this.break;if(tothis.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];from>0&&this.decomposeLeft(from,result);let left=result.length;for(let node of nodes)result.push(node);if(from>0&&mergeGaps(result,left-1),to=left&&result.push(null)),to>left&&this.right.decomposeLeft(to-left,result)}decomposeRight(from,result){let left=this.left.length,right=left+this.break;if(from>=right)return this.right.decomposeRight(from-right,result);from2*right.size||right.size>2*left.size?HeightMap.of(this.break?[left,null,right]:[left,right]):(this.left=left,this.right=right,this.height=left.height+right.height,this.outdated=left.outdated||right.outdated,this.size=left.size+right.size,this.length=left.length+this.break+right.length,this)}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0,{left:left,right:right}=this,rightStart=offset+left.length+this.break,rebalance=null;return measured&&measured.from<=offset+left.length&&measured.more?rebalance=left=left.updateHeight(oracle,offset,force,measured):left.updateHeight(oracle,offset,force),measured&&measured.from<=rightStart+right.length&&measured.more?rebalance=right=right.updateHeight(oracle,rightStart,force,measured):right.updateHeight(oracle,rightStart,force),rebalance?this.balanced(left,right):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function mergeGaps(nodes,around){let before,after;null==nodes[around]&&(before=nodes[around-1])instanceof HeightMapGap&&(after=nodes[around+1])instanceof HeightMapGap&&nodes.splice(around-1,3,new HeightMapGap(before.length+1+after.length))}class NodeBuilder{constructor(pos,oracle){this.pos=pos,this.oracle=oracle,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=pos}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(_from,to){if(this.lineStart>-1){let end=Math.min(to,this.lineEnd),last=this.nodes[this.nodes.length-1];last instanceof HeightMapText?last.length+=end-this.pos:(end>this.pos||!this.isCovered)&&this.nodes.push(new HeightMapText(end-this.pos,-1)),this.writtenTo=end,to>end&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=to}point(from,to,deco){if(from=5)&&this.addLineDeco(height,breaks,len)}else to>from&&this.span(from,to);this.lineEnd>-1&&this.lineEnd-1)return;let{from:from,to:to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from,this.lineEnd=to,this.writtenTofrom&&this.nodes.push(new HeightMapText(this.pos-from,-1)),this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);return this.oracle.doc.lineAt(from).to==to&&(gap.flags|=4),gap}ensureLine(){this.enterLine();let last=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last instanceof HeightMapText)return last;let line=new HeightMapText(0,-1);return this.nodes.push(line),line}addBlock(block){this.enterLine();let deco=block.deco;deco&&deco.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(block),this.writtenTo=this.pos=this.pos+block.length,deco&&deco.endSide>0&&(this.covering=block)}addLineDeco(height,breaks,length){let line=this.ensureLine();line.length+=length,line.collapsed+=length,line.widgetHeight=Math.max(line.widgetHeight,height),line.breaks+=breaks,this.writtenTo=this.pos=this.pos+length}finish(from){let last=0==this.nodes.length?null:this.nodes[this.nodes.length-1];!(this.lineStart>-1)||last instanceof HeightMapText||this.isCovered?(this.writtenToelt.clientHeight||elt.scrollWidth>elt.clientWidth)&&"visible"!=style.overflow){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left),right=Math.min(right,parentRect.right),top=Math.max(top,parentRect.top),bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent="absolute"==style.position||"fixed"==style.position?elt.offsetParent:elt.parentNode}else{if(11!=parent.nodeType)break;parent=parent.host}return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top-(rect.top+paddingTop),bottom:Math.max(top,bottom)-(rect.top+paddingTop)}}function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}class LineGap{constructor(from,to,size){this.from=from,this.to=to,this.size=size}static same(a,b){if(a.length!=b.length)return!1;for(let i=0;i"function"!=typeof v&&"cm-lineWrapping"==v.class));this.heightOracle=new HeightOracle(guessWrapping),this.stateDeco=state.facet(decorations).filter((d=>"function"!=typeof d)),this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]);for(let i=0;i<2&&(this.viewport=this.getViewport(0,null),this.updateForViewport());i++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Decoration.set(this.lineGaps.map((gap=>gap.draw(this,!1)))),this.computeVisibleRanges()}updateForViewport(){let viewports=[this.viewport],{main:main}=this.state.selection;for(let i=0;i<=1;i++){let pos=i?main.head:main.anchor;if(!viewports.some((_ref2=>{let{from:from,to:to}=_ref2;return pos>=from&&pos<=to}))){let{from:from,to:to}=this.lineBlockAt(pos);viewports.push(new Viewport(from,to))}}return this.viewports=viewports.sort(((a,b)=>a.from-b.from)),this.updateScaler()}updateScaler(){let scaler=this.scaler;return this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle,this.heightMap,this.viewports),scaler.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,(block=>{this.viewportLines.push(scaleBlock(block,this.scaler))}))}update(update){let scrollTarget=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter((d=>"function"!=typeof d));let contentChanges=update.changedRanges,heightChanges=ChangedRange.extendWithRanges(contentChanges,function(a,b,diff){let comp=new DecorationComparator;return RangeSet.compare(a,b,diff,comp,0),comp.changes}(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length))),prevHeight=this.heightMap.height,scrollAnchor=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges),this.heightMap.height!=prevHeight&&(update.flags|=2),scrollAnchor?(this.scrollAnchorPos=update.changes.mapPos(scrollAnchor.from,-1),this.scrollAnchorHeight=scrollAnchor.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;(scrollTarget&&(scrollTarget.range.headviewport.to)||!this.viewportIsAppropriate(viewport))&&(viewport=this.getViewport(0,scrollTarget));let viewportChange=viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport,update.flags|=this.updateForViewport(),(viewportChange||!update.changes.empty||2&update.flags)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes))),update.flags|=this.computeVisibleRanges(),scrollTarget&&(this.scrollTarget=scrollTarget),!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc&&!update.state.facet(nativeSelectionHidden)&&(this.mustEnforceCursorAssoc=!0)}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom),oracle=this.heightOracle,whiteSpace=style.whiteSpace;this.defaultTextDirection="rtl"==style.direction?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace),domRect=dom.getBoundingClientRect(),measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=domRect.height;this.contentDOMHeight=domRect.height,this.mustMeasureContent=!1;let result=0,bias=0;if(domRect.width&&domRect.height){let{scaleX:scaleX,scaleY:scaleY}=getScale(dom,domRect);(scaleX>.005&&Math.abs(this.scaleX-scaleX)>.005||scaleY>.005&&Math.abs(this.scaleY-scaleY)>.005)&&(this.scaleX=scaleX,this.scaleY=scaleY,result|=8,refresh=measureContent=!0)}let paddingTop=(parseInt(style.paddingTop)||0)*this.scaleY,paddingBottom=(parseInt(style.paddingBottom)||0)*this.scaleY;this.paddingTop==paddingTop&&this.paddingBottom==paddingBottom||(this.paddingTop=paddingTop,this.paddingBottom=paddingBottom,result|=10),this.editorWidth!=view.scrollDOM.clientWidth&&(oracle.lineWrapping&&(measureContent=!0),this.editorWidth=view.scrollDOM.clientWidth,result|=8);let scrollTop=view.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=scrollTop&&(this.scrollAnchorHeight=-1,this.scrollTop=scrollTop),this.scrolledToBottom=isScrolledToBottom(view.scrollDOM);let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop),dTop=pixelViewport.top-this.pixelViewport.top,dBottom=pixelViewport.bottom-this.pixelViewport.bottom;this.pixelViewport=pixelViewport;let inView=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(inView!=this.inView&&(this.inView=inView,inView&&(measureContent=!0)),!this.inView&&!this.scrollTarget)return 0;let contentWidth=domRect.width;if(this.contentDOMWidth==contentWidth&&this.editorHeight==view.scrollDOM.clientHeight||(this.contentDOMWidth=domRect.width,this.editorHeight=view.scrollDOM.clientHeight,result|=8),measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights)&&(refresh=!0),refresh||oracle.lineWrapping&&Math.abs(contentWidth-this.contentDOMWidth)>oracle.charWidth){let{lineHeight:lineHeight,charWidth:charWidth,textHeight:textHeight}=view.docView.measureTextSize();refresh=lineHeight>0&&oracle.refresh(whiteSpace,lineHeight,charWidth,textHeight,contentWidth/charWidth,lineHeights),refresh&&(view.docView.minWidth=0,result|=8)}dTop>0&&dBottom>0?bias=Math.max(dTop,dBottom):dTop<0&&dBottom<0&&(bias=Math.min(dTop,dBottom)),oracle.heightChanged=!1;for(let vp of this.viewports){let heights=vp.from==this.viewport.from?lineHeights:view.docView.measureVisibleLineHeights(vp);this.heightMap=(refresh?HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle,[new ChangedRange(0,0,0,view.state.doc.length)]):this.heightMap).updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}oracle.heightChanged&&(result|=2)}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return viewportChange&&(2&result&&(result|=this.updateScaler()),this.viewport=this.getViewport(bias,this.scrollTarget),result|=this.updateForViewport()),(2&result||viewportChange)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view)),result|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,view.docView.enforceCursorAssoc()),result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2)),map=this.heightMap,oracle=this.heightOracle,{visibleTop:visibleTop,visibleBottom:visibleBottom}=this,viewport=new Viewport(map.lineAt(visibleTop-1e3*marginTop,QueryType$1.ByHeight,oracle,0,0).from,map.lineAt(visibleBottom+1e3*(1-marginTop),QueryType$1.ByHeight,oracle,0,0).to);if(scrollTarget){let{head:head}=scrollTarget.range;if(headviewport.to){let topPos,viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),block=map.lineAt(head,QueryType$1.ByPos,oracle,0,0);topPos="center"==scrollTarget.y?(block.top+block.bottom)/2-viewHeight/2:"start"==scrollTarget.y||"nearest"==scrollTarget.y&&head1&&void 0!==arguments[1]?arguments[1]:0;if(!this.inView)return!0;let{top:top}=this.heightMap.lineAt(from,QueryType$1.ByPos,this.heightOracle,0,0),{bottom:bottom}=this.heightMap.lineAt(to,QueryType$1.ByPos,this.heightOracle,0,0),{visibleTop:visibleTop,visibleBottom:visibleBottom}=this;return(0==from||top<=visibleTop-Math.max(10,Math.min(-bias,250)))&&(to==this.state.doc.length||bottom>=visibleBottom+Math.max(10,Math.min(bias,250)))&&top>visibleTop-2e3&&bottom>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[],addGap=(from,to,line,structure)=>{if(to-fromfrom&&posgap.from>=line.from&&gap.to<=line.to&&Math.abs(gap.from-from)gap.frompos))));if(!gap){if(tor.from<=to&&r.to>=to))){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),!1,!0).head;lineStart>from&&(to=lineStart)}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)},checkLine=line=>{if(line.lengthpos&&(ranges.push({from:pos,to:from}),total+=from-pos),pos=to}},20),posline.from&&addGap(line.from,viewFrom,line,structure),viewTogap.draw(this,this.heightOracle.lineWrapping)))))}computeVisibleRanges(){let deco=this.stateDeco;this.lineGaps.length&&(deco=deco.concat(this.lineGapDeco));let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from:from,to:to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some(((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to));return this.visibleRanges=ranges,changed?4:0}lineBlockAt(pos){return pos>=this.viewport.from&&pos<=this.viewport.to&&this.viewportLines.find((b=>b.from<=pos&&b.to>=pos))||scaleBlock(this.heightMap.lineAt(pos,QueryType$1.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(height){return height>=this.viewportLines[0].top&&height<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find((l=>l.top<=height&&l.bottom>=height))||scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType$1.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(scrollTop){let block=this.lineBlockAtHeight(scrollTop+8);return block.from>=this.viewport.from||this.viewportLines[0].top-scrollTop>200?block:this.viewportLines[0]}elementAtHeight(height){return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Viewport{constructor(from,to){this.from=from,this.to=to}}function findPosition(_ref4,ratio){let{total:total,ranges:ranges}=_ref4;if(ratio<=0)return ranges[0].from;if(ratio>=1)return ranges[ranges.length-1].to;let dist=Math.floor(total*ratio);for(let i=0;;i++){let{from:from,to:to}=ranges[i],size=to-from;if(dist<=size)return from+dist;dist-=size}}function findFraction(structure,pos){let counted=0;for(let{from:from,to:to}of structure.ranges){if(pos<=to){counted+=pos-from;break}counted+=to-from}return counted/structure.total}const IdScaler={toDOM:n=>n,fromDOM:n=>n,scale:1,eq(other){return other==this}};class BigScaler{constructor(oracle,heightMap,viewports){let vpHeight=0,base=0,domBase=0;this.viewports=viewports.map((_ref5=>{let{from:from,to:to}=_ref5,top=heightMap.lineAt(from,QueryType$1.ByPos,oracle,0,0).top,bottom=heightMap.lineAt(to,QueryType$1.ByPos,oracle,0,0).bottom;return vpHeight+=bottom-top,{from:from,to:to,top:top,bottom:bottom,domTop:0,domBottom:0}})),this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports)obj.domTop=domBase+(obj.top-base)*this.scale,domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top),base=obj.bottom}toDOM(n){for(let i=0,base=0,domBase=0;;i++){let vp=ivp.from==other.viewports[i].from&&vp.to==other.viewports[i].to)))}}function scaleBlock(block,scaler){if(1==scaler.scale)return block;let bTop=scaler.toDOM(block.top),bBottom=scaler.toDOM(block.bottom);return new BlockInfo(block.from,block.length,bTop,bBottom-bTop,Array.isArray(block._content)?block._content.map((b=>scaleBlock(b,scaler))):block._content)}const theme=Facet.define({combine:strs=>strs.join(" ")}),darkTheme=Facet.define({combine:values=>values.indexOf(!0)>-1}),baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName(),lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new StyleModule(spec,{finish:sel=>/&/.test(sel)?sel.replace(/&\w*/,(m=>{if("&"==m)return main;if(!scopes||!scopes[m])throw new RangeError("Unsupported selector: ".concat(m));return scopes[m]})):main+" "+sel})}const baseTheme$1$3=buildTheme("."+baseThemeID,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:'url(\'data:image/svg+xml,\')',backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},lightDarkIDs);class DOMReader{constructor(points,state){this.points=points,this.text="",this.lineSeparator=state.facet(EditorState.lineSeparator)}append(text){this.text+=text}lineBreak(){this.text+="￿"}readRange(start,end){if(!start)return this;let parent=start.parentNode;for(let cur=start;;){this.findPointBefore(parent,cur);let oldLen=this.text.length;this.readNode(cur);let next=cur.nextSibling;if(next==end)break;let view=ContentView.get(cur),nextView=ContentView.get(next);(view&&nextView?view.breakAfter:(view?view.breakAfter:isBlockElement(cur))||isBlockElement(next)&&("BR"!=cur.nodeName||cur.cmIgnore)&&this.text.length>oldLen)&&this.lineBreak(),cur=next}return this.findPointBefore(parent,end),this}readTextNode(node){let text=node.nodeValue;for(let point of this.points)point.node==node&&(point.pos=this.text.length+Math.min(point.offset,text.length));for(let off=0,re=this.lineSeparator?null:/\r\n?|\n/g;;){let m,nextBreak=-1,breakSize=1;if(this.lineSeparator?(nextBreak=text.indexOf(this.lineSeparator,off),breakSize=this.lineSeparator.length):(m=re.exec(text))&&(nextBreak=m.index,breakSize=m[0].length),this.append(text.slice(off,nextBreak<0?text.length:nextBreak)),nextBreak<0)break;if(this.lineBreak(),breakSize>1)for(let point of this.points)point.node==node&&point.pos>this.text.length&&(point.pos-=breakSize-1);off=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node),fromView=view&&view.overrideDOMText;if(null!=fromView){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else 3==node.nodeType?this.readTextNode(node):"BR"==node.nodeName?node.nextSibling&&this.lineBreak():1==node.nodeType&&this.readRange(node.firstChild,null)}findPointBefore(node,next){for(let point of this.points)point.node==node&&node.childNodes[point.offset]==next&&(point.pos=this.text.length)}findPointInside(node,length){for(let point of this.points)(3==node.nodeType?point.node==node:node.contains(point.node))&&(point.pos=this.text.length+(isAtEnd(node,point.node,point.offset)?length:0))}}function isAtEnd(parent,node,offset){for(;;){if(!node||offset-1;let{impreciseHead:iHead,impreciseAnchor:iAnchor}=view.docView;if(view.state.readOnly&&start>-1)this.newSel=null;else if(start>-1&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:function(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode:anchorNode,anchorOffset:anchorOffset,focusNode:focusNode,focusOffset:focusOffset}=view.observer.selectionRange;anchorNode&&(result.push(new DOMPoint(anchorNode,anchorOffset)),focusNode==anchorNode&&focusOffset==anchorOffset||result.push(new DOMPoint(focusNode,focusOffset)));return result}(view),reader=new DOMReader(selPoints,view.state);reader.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=reader.text,this.newSel=function(points,base){if(0==points.length)return null;let anchor=points[0].pos,head=2==points.length?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base,head+base):null}(selPoints,this.bounds.from)}else{let domSel=view.observer.selectionRange,head=iHead&&iHead.node==domSel.focusNode&&iHead.offset==domSel.focusOffset||!contains(view.contentDOM,domSel.focusNode)?view.state.selection.main.head:view.docView.posFromDOM(domSel.focusNode,domSel.focusOffset),anchor=iAnchor&&iAnchor.node==domSel.anchorNode&&iAnchor.offset==domSel.anchorOffset||!contains(view.contentDOM,domSel.anchorNode)?view.state.selection.main.anchor:view.docView.posFromDOM(domSel.anchorNode,domSel.anchorOffset),vp=view.viewport;if((browser.ios||browser.chrome)&&view.state.selection.main.empty&&head!=anchor&&(vp.from>0||vp.toDate.now()-100?view.inputState.lastKeyCode:-1;if(domChange.bounds){let{from:from,to:to}=domChange.bounds,preferredPos=sel.from,preferredSide=null;(8===lastKey||browser.android&&domChange.text.length0&&toB>0&&a.charCodeAt(toA-1)==b.charCodeAt(toB-1);)toA--,toB--;if("end"==preferredSide){preferredPos-=toA+Math.max(0,from-Math.min(toA,toB))-from}if(toA=toA?from-preferredPos:0,toB=from+(toB-toA),toA=from}else if(toB=toB?from-preferredPos:0,toA=from+(toA-toB),toB=from}return{from:from,toA:toA,toB:toB}}(view.state.doc.sliceString(from,to,"￿"),domChange.text,preferredPos-from,preferredSide);diff&&(browser.chrome&&13==lastKey&&diff.toB==diff.from+2&&"￿￿"==domChange.text.slice(diff.from,diff.toB)&&diff.toB--,change={from:from+diff.from,to:from+diff.toA,insert:Text.of(domChange.text.slice(diff.from,diff.toB).split("￿"))})}else newSel&&(!view.hasFocus&&view.state.facet(editable)||newSel.main.eq(sel))&&(newSel=null);if(!change&&!newSel)return!1;if(!change&&domChange.typeOver&&!sel.empty&&newSel&&newSel.main.empty?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,sel.to)}:change&&change.from>=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,change.from).append(change.insert).append(view.state.doc.slice(change.to,sel.to))}:(browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())&&"off"==view.contentDOM.getAttribute("autocorrect")?(newSel&&2==change.insert.length&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}):browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&"\n "==change.insert.toString()&&view.lineWrapping&&(newSel&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}),change)return applyDOMChangeInner(view,change,newSel,lastKey);if(newSel&&!newSel.main.eq(sel)){let scrollIntoView=!1,userEvent="select";return view.inputState.lastSelectionTime>Date.now()-50&&("select"==view.inputState.lastSelectionOrigin&&(scrollIntoView=!0),userEvent=view.inputState.lastSelectionOrigin),view.dispatch({selection:newSel,scrollIntoView:scrollIntoView,userEvent:userEvent}),!0}return!1}function applyDOMChangeInner(view,change,newSel){let lastKey=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;if(browser.ios&&view.inputState.flushIOSKey(change))return!0;let sel=view.state.selection.main;if(browser.android&&(change.to==sel.to&&(change.from==sel.from||change.from==sel.from-1&&" "==view.state.sliceDoc(change.from,sel.from))&&1==change.insert.length&&2==change.insert.lines&&dispatchKey(view.contentDOM,"Enter",13)||(change.from==sel.from-1&&change.to==sel.to&&0==change.insert.length||8==lastKey&&change.insert.lengthsel.head)&&dispatchKey(view.contentDOM,"Backspace",8)||change.from==sel.from&&change.to==sel.to+1&&0==change.insert.length&&dispatchKey(view.contentDOM,"Delete",46)))return!0;let defaultTr,text=change.insert.toString();view.inputState.composing>=0&&view.inputState.composing++;let defaultInsert=()=>defaultTr||(defaultTr=applyDefaultInsert(view,change,newSel));return view.state.facet(inputHandler$1).some((h=>h(view,change.from,change.to,text,defaultInsert)))||view.dispatch(defaultInsert()),!0}function applyDefaultInsert(view,change,newSel){let tr,startState=view.state,sel=startState.selection.main;if(change.from>=sel.from&&change.to<=sel.to&&change.to-change.from>=(sel.to-sel.from)/3&&(!newSel||newSel.main.empty&&newSel.main.from==change.from+change.insert.length)&&view.inputState.composing<0){let before=sel.fromchange.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,void 0,view.state.lineBreak)+after))}else{let changes=startState.changes(change),mainSel=newSel&&newSel.main.to<=changes.newLength?newSel.main:void 0;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let compositionRange,replaced=view.state.sliceDoc(change.from,change.to),composition=newSel&&findCompositionNode(view,newSel.main.head);if(composition){let dLen=change.insert.length-(change.to-change.from);compositionRange={from:composition.from,to:composition.to-dLen}}else compositionRange=view.state.doc.lineAt(sel.head);let offset=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange((range=>{if(range.from==sel.from&&range.to==sel.to)return{changes:changes,range:mainSel||range.map(changes)};let to=range.to-offset,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range:range};let rangeChanges=startState.changes({from:from,to:to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:mainSel?EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff)):range.map(rangeChanges)}}))}else tr={changes:changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}let userEvent="input.type";return(view.composing||view.inputState.compositionPendingChange&&view.inputState.compositionEndedAt>Date.now()-50)&&(view.inputState.compositionPendingChange=!1,userEvent+=".compose",view.inputState.compositionFirstChange&&(userEvent+=".start",view.inputState.compositionFirstChange=!1)),startState.update(tr,{userEvent:userEvent,scrollIntoView:!0})}const observeOptions={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},useCharData=browser.ie&&browser.ie_version<=11;class DOMObserver{constructor(view){this.view=view,this.active=!1,this.editContext=null,this.selectionRange=new DOMSelectionState,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=view.contentDOM,this.observer=new MutationObserver((mutations=>{for(let mut of mutations)this.queue.push(mut);(browser.ie&&browser.ie_version<=11||browser.ios&&view.composing)&&mutations.some((m=>"childList"==m.type&&m.removedNodes.length||"characterData"==m.type&&m.oldValue.length>m.target.nodeValue.length))?this.flushSoon():this.flush()})),!window.EditContext||!1===view.constructor.EDIT_CONTEXT||browser.chrome&&browser.chrome_version<126||(this.editContext=new EditContextManager(view),view.state.facet(editable)&&(view.contentDOM.editContext=this.editContext.editContext)),useCharData&&(this.onCharData=event=>{this.queue.push({target:event.target,type:"characterData",oldValue:event.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),"function"==typeof ResizeObserver&&(this.resizeScroll=new ResizeObserver((()=>{var _a;(null===(_a=this.view.docView)||void 0===_a?void 0:_a.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))}),{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver((entries=>{entries.length>0&&entries[entries.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))}),{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout((()=>{this.resizeTimeout=-1,this.view.requestMeasure()}),50))}onPrint(event){("change"!=event.type||event.matches)&&(this.view.viewState.printing=!0,this.view.measure(),setTimeout((()=>{this.view.viewState.printing=!1,this.view.requestMeasure()}),500))}updateGaps(gaps){if(this.gapIntersection&&(gaps.length!=this.gaps.length||this.gaps.some(((g,i)=>g!=gaps[i])))){this.gapIntersection.disconnect();for(let gap of gaps)this.gapIntersection.observe(gap);this.gaps=gaps}}onSelectionChange(event){let wasChanged=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:view}=this,sel=this.selectionRange;if(view.state.facet(editable)?view.root.activeElement!=this.dom:!hasSelection(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);context&&context.ignoreEvent(event)?wasChanged||(this.selectionChanged=!1):(browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:view}=this,selection=getSelection(view.root);if(!selection)return!1;let range=browser.safari&&11==view.root.nodeType&&function(doc){let elt=doc.activeElement;for(;elt&&elt.shadowRoot;)elt=elt.shadowRoot.activeElement;return elt}(this.dom.ownerDocument)==this.dom&&function(view,selection){if(selection.getComposedRanges){let range=selection.getComposedRanges(view.root)[0];if(range)return buildSelectionRangeFromRange(view,range)}let found=null;function read(event){event.preventDefault(),event.stopImmediatePropagation(),found=event.getTargetRanges()[0]}return view.contentDOM.addEventListener("beforeinput",read,!0),view.dom.ownerDocument.execCommand("indent"),view.contentDOM.removeEventListener("beforeinput",read,!0),found?buildSelectionRangeFromRange(view,found):null}(this.view,selection)||selection;if(!range||this.selectionRange.eq(range))return!1;let local=hasSelection(this.dom,range);return local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime{let key=this.delayedAndroidKey;if(key){this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=key.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&key.force&&dispatchKey(this.dom,key.key,key.keyCode)}};this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}this.delayedAndroidKey&&"Enter"!=key||(this.delayedAndroidKey={key:key,keyCode:keyCode,force:this.lastChange{this.delayedFlush=-1,this.flush()})))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let mut of this.observer.takeRecords())this.queue.push(mut);return this.queue}processRecords(){let records=this.pendingRecords();records.length&&(this.queue=[]);let from=-1,to=-1,typeOver=!1;for(let record of records){let range=this.readMutation(record);range&&(range.typeOver&&(typeOver=!0),-1==from?({from:from,to:to}=range):(from=Math.min(range.from,from),to=Math.max(range.to,to)))}return{from:from,to:to,typeOver:typeOver}}readChange(){let{from:from,to:to,typeOver:typeOver}=this.processRecords(),newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;from>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let change=new DOMChange(this.view,from,to,typeOver);return this.view.docView.domChanged={newSel:change.newSel?change.newSel.main:null},change}flush(){let readSelection=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;readSelection&&this.readSelectionRange();let domChange=this.readChange();if(!domChange)return this.view.requestMeasure(),!1;let startState=this.view.state,handled=applyDOMChange(this.view,domChange);return this.view.state==startState&&(domChange.domChanged||domChange.newSel&&!domChange.newSel.main.eq(this.view.state.selection.main))&&this.view.update([]),handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;if(cView.markDirty("attributes"==rec.type),"attributes"==rec.type&&(cView.flags|=4),"childList"==rec.type){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1),childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:!1}}return"characterData"==rec.type?{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}:null}setWindow(win){win!=this.win&&(this.removeWindowListeners(this.win),this.win=win,this.addWindowListeners(this.win))}addWindowListeners(win){win.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener("change",this.onPrint):win.addEventListener("beforeprint",this.onPrint),win.addEventListener("scroll",this.onScroll),win.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(win){win.removeEventListener("scroll",this.onScroll),win.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener("change",this.onPrint):win.removeEventListener("beforeprint",this.onPrint),win.document.removeEventListener("selectionchange",this.onSelectionChange)}update(update){this.editContext&&(this.editContext.update(update),update.startState.facet(editable)!=update.state.facet(editable)&&(update.view.contentDOM.editContext=update.state.facet(editable)?this.editContext.editContext:null))}destroy(){var _a,_b,_c;this.stop(),null===(_a=this.intersection)||void 0===_a||_a.disconnect(),null===(_b=this.gapIntersection)||void 0===_b||_b.disconnect(),null===(_c=this.resizeScroll)||void 0===_c||_c.disconnect();for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function findChild(cView,dom,dir){for(;dom;){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}function buildSelectionRangeFromRange(view,range){let anchorNode=range.startContainer,anchorOffset=range.startOffset,focusNode=range.endContainer,focusOffset=range.endOffset,curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);return isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset)&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]),{anchorNode:anchorNode,anchorOffset:anchorOffset,focusNode:focusNode,focusOffset:focusOffset}}class EditContextManager{constructor(view){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.resetRange(view.state);let context=this.editContext=new window.EditContext({text:view.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,view.state.selection.main.anchor))),selectionEnd:this.toContextPos(view.state.selection.main.head)});this.handlers.textupdate=e=>{let{anchor:anchor}=view.state.selection.main,change={from:this.toEditorPos(e.updateRangeStart),to:this.toEditorPos(e.updateRangeEnd),insert:Text.of(e.text.split("\n"))};change.from==this.from&&anchorthis.to&&(change.to=anchor),(change.from!=change.to||change.insert.length)&&(this.pendingContextChange=change,applyDOMChangeInner(view,change,EditorSelection.single(this.toEditorPos(e.selectionStart),this.toEditorPos(e.selectionEnd))),this.pendingContextChange&&this.revertPending(view.state))},this.handlers.characterboundsupdate=e=>{let rects=[],prev=null;for(let i=this.toEditorPos(e.rangeStart),end=this.toEditorPos(e.rangeEnd);i{let deco=[];for(let format of e.getTextFormats()){let lineStyle=format.underlineStyle,thickness=format.underlineThickness;if("None"!=lineStyle&&"None"!=thickness){let style="text-decoration: underline ".concat("Dashed"==lineStyle?"dashed ":"Squiggle"==lineStyle?"wavy ":"").concat("Thin"==thickness?1:2,"px");deco.push(Decoration.mark({attributes:{style:style}}).range(this.toEditorPos(format.rangeStart),this.toEditorPos(format.rangeEnd)))}}view.dispatch({effects:setEditContextFormatting.of(Decoration.set(deco))})},this.handlers.compositionstart=()=>{view.inputState.composing<0&&(view.inputState.composing=0,view.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{view.inputState.composing=-1,view.inputState.compositionFirstChange=null};for(let event in this.handlers)context.addEventListener(event,this.handlers[event]);this.measureReq={read:view=>{this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());let sel=getSelection(view.root);sel&&sel.rangeCount&&this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect())}}}applyEdits(update){let off=0,abort=!1,pending=this.pendingContextChange;return update.changes.iterChanges(((fromA,toA,_fromB,_toB,insert)=>{if(abort)return;let dLen=insert.length-(toA-fromA);if(pending&&toA>=pending.to){if(pending.from==fromA&&pending.to==toA&&pending.insert.eq(insert))return pending=this.pendingContextChange=null,off+=dLen,void(this.to+=dLen);pending=null,this.revertPending(update.state)}if(fromA+=off,(toA+=off)<=this.from)this.from+=dLen,this.to+=dLen;else if(fromAthis.to||this.to-this.from+insert.length>3e4)return void(abort=!0);this.editContext.updateText(this.toContextPos(fromA),this.toContextPos(toA),insert.toString()),this.to+=dLen}off+=dLen})),pending&&!abort&&this.revertPending(update.state),!abort}update(update){this.applyEdits(update)&&this.rangeIsValid(update.state)?(update.docChanged||update.selectionSet)&&this.setSelection(update.state):(this.pendingContextChange=null,this.resetRange(update.state),this.editContext.updateText(0,this.editContext.text.length,update.state.doc.sliceString(this.from,this.to)),this.setSelection(update.state)),(update.geometryChanged||update.docChanged||update.selectionSet)&&update.view.requestMeasure(this.measureReq)}resetRange(state){let{head:head}=state.selection.main;this.from=Math.max(0,head-1e4),this.to=Math.min(state.doc.length,head+1e4)}revertPending(state){let pending=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(pending.from),this.toContextPos(pending.to+pending.insert.length),state.doc.sliceString(pending.from,pending.to))}setSelection(state){let{main:main}=state.selection,start=this.toContextPos(Math.max(this.from,Math.min(this.to,main.anchor))),end=this.toContextPos(main.head);this.editContext.selectionStart==start&&this.editContext.selectionEnd==end||this.editContext.updateSelection(start,end)}rangeIsValid(state){let{head:head}=state.selection.main;return!(this.from>0&&head-this.from<500||this.to3e4)}toEditorPos(contextPos){return contextPos+this.from}toContextPos(editorPos){return editorPos-this.from}destroy(){for(let event in this.handlers)this.editContext.removeEventListener(event,this.handlers[event])}}class EditorView{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),config.parent&&config.parent.appendChild(this.dom);let{dispatch:dispatch}=config;this.dispatchTransactions=config.dispatchTransactions||dispatch&&(trs=>trs.forEach((tr=>dispatch(tr,this))))||(trs=>this.update(trs)),this.dispatch=this.dispatch.bind(this),this._root=config.root||function(node){for(;node;){if(node&&(9==node.nodeType||11==node.nodeType&&node.host))return node;node=node.assignedSlot||node.parentNode}return null}(config.parent)||document,this.viewState=new ViewState(config.state||EditorState.create(config)),config.scrollTo&&config.scrollTo.is(scrollIntoView$1)&&(this.viewState.scrollTarget=config.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(viewPlugin).map((spec=>new PluginInstance(spec)));for(let plugin of this.plugins)plugin.update(this);this.observer=new DOMObserver(this),this.inputState=new InputState(this),this.inputState.ensureHandlers(this.plugins),this.docView=new DocView(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(){for(var _len3=arguments.length,input=new Array(_len3),_key3=0;_key3<_len3;_key3++)input[_key3]=arguments[_key3];let trs=1==input.length&&input[0]instanceof Transaction?input:1==input.length&&Array.isArray(input[0])?input[0]:[this.state.update(...input)];this.dispatchTransactions(trs,this)}update(transactions){if(0!=this.updateState)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let update,redrawn=!1,attrsChanged=!1,state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state}if(this.destroyed)return void(this.viewState.state=state);let focus=this.hasFocus,focusFlag=0,dispatchFocus=null;transactions.some((tr=>tr.annotation(isFocusChange)))?(this.inputState.notifiedFocused=focus,focusFlag=1):focus!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=focus,dispatchFocus=focusChangeTransaction(state,focus),dispatchFocus||(focusFlag=1));let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey?(this.observer.clearDelayedAndroidKey(),domChange=this.observer.readChange(),(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))&&(domChange=null)):this.observer.clear(),state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions),update.flags|=focusFlag;let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget&&(scrollTarget=scrollTarget.map(tr.changes)),tr.scrollIntoView){let{main:main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)e.is(scrollIntoView$1)&&(scrollTarget=e.value.clip(this.state))}this.viewState.update(update,scrollTarget),this.bidiCache=CachedOrder.update(this.bidiCache,update.changes),update.empty||(this.updatePlugins(update),this.inputState.update(update)),redrawn=this.docView.update(update),this.state.facet(styleModule)!=this.styleModules&&this.mountStyles(),attrsChanged=this.updateAttrs(),this.showAnnouncements(transactions),this.docView.updateSelection(redrawn,transactions.some((tr=>tr.isUserEvent("select.pointer"))))}finally{this.updateState=0}if(update.startState.facet(theme)!=update.state.facet(theme)&&(this.viewState.mustMeasureContent=!0),(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),redrawn&&this.docViewUpdate(),!update.empty)for(let listener of this.state.facet(updateListener))try{listener(update)}catch(e){logException(this.state,e,"update listener")}(dispatchFocus||domChange)&&Promise.resolve().then((()=>{dispatchFocus&&this.state==dispatchFocus.startState&&this.dispatch(dispatchFocus),domChange&&!applyDOMChange(this,domChange)&&pendingKey.force&&dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)}))}setState(newState){if(0!=this.updateState)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed)return void(this.viewState.state=newState);this.updateState=2;let hadFocus=this.hasFocus;try{for(let plugin of this.plugins)plugin.destroy(this);this.viewState=new ViewState(newState),this.plugins=newState.facet(viewPlugin).map((spec=>new PluginInstance(spec))),this.pluginMap.clear();for(let plugin of this.plugins)plugin.update(this);this.docView.destroy(),this.docView=new DocView(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}hadFocus&&this.focus(),this.requestMeasure()}updatePlugins(update){let prevSpecs=update.startState.facet(viewPlugin),specs=update.state.facet(viewPlugin);if(prevSpecs!=specs){let newPlugins=[];for(let spec of specs){let found=prevSpecs.indexOf(spec);if(found<0)newPlugins.push(new PluginInstance(spec));else{let plugin=this.plugins[found];plugin.mustUpdate=update,newPlugins.push(plugin)}}for(let plugin of this.plugins)plugin.mustUpdate!=update&&plugin.destroy(this);this.plugins=newPlugins,this.pluginMap.clear()}else for(let p of this.plugins)p.mustUpdate=update;for(let i=0;i0&&void 0!==arguments[0])||arguments[0];if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey)return this.measureScheduled=-1,void this.requestMeasure();this.measureScheduled=0,flush&&this.observer.forceFlush();let updated=null,sDOM=this.scrollDOM,scrollTop=sDOM.scrollTop*this.scaleY,{scrollAnchorPos:scrollAnchorPos,scrollAnchorHeight:scrollAnchorHeight}=this.viewState;Math.abs(scrollTop-this.viewState.scrollTop)>1&&(scrollAnchorHeight=-1),this.viewState.scrollAnchorHeight=-1;try{for(let i=0;;i++){if(scrollAnchorHeight<0)if(isScrolledToBottom(sDOM))scrollAnchorPos=-1,scrollAnchorHeight=this.viewState.heightMap.height;else{let block=this.viewState.scrollAnchorAt(scrollTop);scrollAnchorPos=block.from,scrollAnchorHeight=block.top}this.updateState=1;let changed=this.viewState.measure(this);if(!changed&&!this.measureRequests.length&&null==this.viewState.scrollTarget)break;if(i>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let measuring=[];4&changed||([this.measureRequests,measuring]=[measuring,this.measureRequests]);let measured=measuring.map((m=>{try{return m.read(this)}catch(e){return logException(this.state,e),BadMeasure}})),update=ViewUpdate.create(this,this.state,[]),redrawn=!1;update.flags|=changed,updated?updated.flags|=changed:updated=update,this.updateState=2,update.empty||(this.updatePlugins(update),this.inputState.update(update),this.updateAttrs(),redrawn=this.docView.update(update),redrawn&&this.docViewUpdate());for(let i=0;i1||diff<-1){scrollTop+=diff,sDOM.scrollTop=scrollTop/this.scaleY,scrollAnchorHeight=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}get themeClasses(){return baseThemeID+" "+(this.state.facet(darkTheme)?baseDarkID:baseLightID)+" "+this.state.facet(theme)}updateAttrs(){let editorAttrs=attrsFromFacet(this,editorAttributes,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(editable)?"true":"false",class:"cm-content",style:"".concat(browser.tabSize,": ").concat(this.state.tabSize),role:"textbox","aria-multiline":"true"};this.state.readOnly&&(contentAttrs["aria-readonly"]="true"),attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore((()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs),changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor}));return this.editorAttrs=editorAttrs,this.contentAttrs=contentAttrs,changed}showAnnouncements(trs){let first=!0;for(let tr of trs)for(let effect of tr.effects)if(effect.is(EditorView.announce)){first&&(this.announceDOM.textContent=""),first=!1,this.announceDOM.appendChild(document.createElement("div")).textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);let nonce=this.state.facet(EditorView.cspNonce);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1$3).reverse(),nonce?{nonce:nonce}:void 0)}readMeasured(){if(2==this.updateState)throw new Error("Reading the editor layout isn't allowed during an update");0==this.updateState&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(request){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame((()=>this.measure()))),request){if(this.measureRequests.indexOf(request)>-1)return;if(null!=request.key)for(let i=0;ip.spec==plugin))||null),known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(height){return this.readMeasured(),this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){return this.readMeasured(),this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,(initial=>function(view,pos,start){let categorize=view.state.charCategorizer(pos),cat=categorize(start);return next=>{let nextCat=categorize(next);return cat==CharCategory.Space&&(cat=nextCat),cat==nextCat}}(this,start.head,initial))))}visualLineSide(line,end){let order=this.bidiSpans(line),dir=this.textDirectionAt(line.from),span=order[end?order.length-1:0];return EditorSelection.cursor(span.side(end,dir)+line.from,span.forward(!end,dir)?1:-1)}moveToLineBoundary(start,forward){return function(view,start,forward,includeWrap){let line=blockAt(view,start.head),coords=includeWrap&&line.type==BlockType.Text&&(view.lineWrapping||line.widgetLineBreaks)?view.coordsAtPos(start.assoc<0&&start.head>line.from?start.head-1:start.head):null;if(coords){let editorRect=view.dom.getBoundingClientRect(),direction=view.textDirectionAt(line.from),pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(null!=pos)return EditorSelection.cursor(pos,forward?-1:1)}return EditorSelection.cursor(forward?line.to:line.from,forward?-1:1)}(this,start,forward,!(arguments.length>2&&void 0!==arguments[2])||arguments[2])}moveVertically(start,forward,distance){return skipAtoms(this,start,function(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let startY,goal=start.goalColumn,rect=view.contentDOM.getBoundingClientRect(),startCoords=view.coordsAtPos(startPos,start.assoc||-1),docTop=view.documentTop;if(startCoords)null==goal&&(goal=startCoords.left-rect.left),startY=dir<0?startCoords.top:startCoords.bottom;else{let line=view.viewState.lineBlockAt(startPos);null==goal&&(goal=Math.min(rect.right-rect.left,view.defaultCharacterWidth*(startPos-line.from))),startY=(dir<0?line.top:line.bottom)+docTop}let resolvedGoal=rect.left+goal,dist=null!=distance?distance:view.viewState.heightOracle.textHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist+extra)*dir,pos=posAtCoords(view,{x:resolvedGoal,y:curY},!1,dir);if(curYrect.bottom||(dir<0?posstartPos)){let charRect=view.docView.coordsForChar(pos),assoc=!charRect||curY1&&void 0!==arguments[1]?arguments[1]:0;return this.docView.posFromDOM(node,offset)}posAtCoords(coords){let precise=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.readMeasured(),posAtCoords(this,coords,precise)}coordsAtPos(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;this.readMeasured();let rect=this.docView.coordsAt(pos,side);if(!rect||rect.left==rect.right)return rect;let line=this.state.doc.lineAt(pos),order=this.bidiSpans(line);return flattenRect(rect,order[BidiSpan.find(order,pos-line.from,-1,side)].dir==Direction.LTR==side>0)}coordsForChar(pos){return this.readMeasured(),this.docView.coordsForChar(pos)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){return!this.state.facet(perLineTextDirection)||posthis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(pos))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(line){if(line.length>MaxBidiLine)return trivialOrder(line.length);let isolates,dir=this.textDirectionAt(line.from);for(let entry of this.bidiCache)if(entry.from==line.from&&entry.dir==dir&&(entry.fresh||isolatesEq(entry.isolates,isolates=getIsolatedRanges(this,line))))return entry.order;isolates||(isolates=getIsolatedRanges(this,line));let order=function(line,direction,isolates){if(!line)return[new BidiSpan(0,0,direction==RTL?1:0)];if(direction==LTR&&!isolates.length&&!BidiRE.test(line))return trivialOrder(line.length);if(isolates.length)for(;line.length>types.length;)types[types.length]=256;let order=[],level=direction==LTR?0:1;return computeSectionOrder(line,level,level,isolates,0,line.length,order),order}(line.text,dir,isolates);return this.bidiCache.push(new CachedOrder(line.from,line.to,dir,isolates,!0,order)),order}get hasFocus(){var _a;return(this.dom.ownerDocument.hasFocus()||browser.safari&&(null===(_a=this.inputState)||void 0===_a?void 0:_a.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore((()=>{focusPreventScroll(this.contentDOM),this.docView.updateSelection()}))}setRoot(root){this._root!=root&&(this._root=root,this.observer.setWindow((9==root.nodeType?root:root.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(pos){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return scrollIntoView$1.of(new ScrollTarget("number"==typeof pos?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}scrollSnapshot(){let{scrollTop:scrollTop,scrollLeft:scrollLeft}=this.scrollDOM,ref=this.viewState.scrollAnchorAt(scrollTop);return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from),"start","start",ref.top-scrollTop,scrollLeft,!0))}setTabFocusMode(to){null==to?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:"boolean"==typeof to?this.inputState.tabFocusMode=to?0:-1:0!=this.inputState.tabFocusMode&&(this.inputState.tabFocusMode=Date.now()+to)}static domEventHandlers(handlers){return ViewPlugin.define((()=>({})),{eventHandlers:handlers})}static domEventObservers(observers){return ViewPlugin.define((()=>({})),{eventObservers:observers})}static theme(spec,options){let prefix=StyleModule.newName(),result=[theme.of(prefix),styleModule.of(buildTheme(".".concat(prefix),spec))];return options&&options.dark&&result.push(darkTheme.of(!0)),result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a;let content=dom.querySelector(".cm-content"),cView=content&&ContentView.get(content)||ContentView.get(dom);return(null===(_a=null==cView?void 0:cView.rootView)||void 0===_a?void 0:_a.view)||null}}EditorView.styleModule=styleModule,EditorView.inputHandler=inputHandler$1,EditorView.scrollHandler=scrollHandler,EditorView.focusChangeEffect=focusChangeEffect,EditorView.perLineTextDirection=perLineTextDirection,EditorView.exceptionSink=exceptionSink,EditorView.updateListener=updateListener,EditorView.editable=editable,EditorView.mouseSelectionStyle=mouseSelectionStyle,EditorView.dragMovesSelection=dragMovesSelection$1,EditorView.clickAddsSelectionRange=clickAddsSelectionRange,EditorView.decorations=decorations,EditorView.outerDecorations=outerDecorations,EditorView.atomicRanges=atomicRanges,EditorView.bidiIsolatedRanges=bidiIsolatedRanges,EditorView.scrollMargins=scrollMargins,EditorView.darkTheme=darkTheme,EditorView.cspNonce=Facet.define({combine:values=>values.length?values[0]:""}),EditorView.contentAttributes=contentAttributes,EditorView.editorAttributes=editorAttributes,EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"}),EditorView.announce=StateEffect.define();const MaxBidiLine=4096,BadMeasure={};class CachedOrder{constructor(from,to,dir,isolates,fresh,order){this.from=from,this.to=to,this.dir=dir,this.isolates=isolates,this.fresh=fresh,this.order=order}static update(cache,changes){if(changes.empty&&!cache.some((c=>c.fresh)))return cache;let result=[],lastDir=cache.length?cache[cache.length-1].dir:Direction.LTR;for(let i=Math.max(0,cache.length-10);i=0;i--){let source=sources[i],value="function"==typeof source?source(view):source;value&&combineAttrs(value,base)}return base}const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name,platform){const parts=name.split(/-(?!$)/);let alt,ctrl,shift,meta,result=parts[parts.length-1];"Space"==result&&(result=" ");for(let i=0;irunHandlers(getKeymap(view.state),event,view,"editor")})),keymap=Facet.define({enables:handleKeyEvents}),Keymaps=new WeakMap;function getKeymap(state){let bindings=state.facet(keymap),map=Keymaps.get(bindings);return map||Keymaps.set(bindings,map=function(bindings){let platform=arguments.length>1&&void 0!==arguments[1]?arguments[1]:currentPlatform,bound=Object.create(null),isPrefix=Object.create(null),checkPrefix=(name,is)=>{let current=isPrefix[name];if(null==current)isPrefix[name]=is;else if(current!=is)throw new Error("Key binding "+name+" is used both as a regular binding and as a multi-stroke prefix")},add=(scope,key,command,preventDefault,stopPropagation)=>{var _a,_b;let scopeObj=bound[scope]||(bound[scope]=Object.create(null)),parts=key.split(/ (?!$)/).map((k=>normalizeKeyName(k,platform)));for(let i=1;i{let ourObj=storedPrefix={view:view,prefix:prefix,scope:scope};return setTimeout((()=>{storedPrefix==ourObj&&(storedPrefix=null)}),4e3),!0}]})}let full=parts.join(" ");checkPrefix(full,!1);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:!1,stopPropagation:!1,run:(null===(_b=null===(_a=scopeObj._any)||void 0===_a?void 0:_a.run)||void 0===_b?void 0:_b.slice())||[]});command&&binding.run.push(command),preventDefault&&(binding.preventDefault=!0),stopPropagation&&(binding.stopPropagation=!0)};for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope of scopes){let scopeObj=bound[scope]||(bound[scope]=Object.create(null));scopeObj._any||(scopeObj._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:any}=b;for(let key in scopeObj)scopeObj[key].run.push((view=>any(view,currentKeyEvent)))}let name=b[platform]||b.key;if(name)for(let scope of scopes)add(scope,name,b.run,b.preventDefault,b.stopPropagation),b.shift&&add(scope,"Shift-"+name,b.shift,b.preventDefault,b.stopPropagation)}return bound}(bindings.reduce(((a,b)=>a.concat(b)),[]))),map}let storedPrefix=null;let currentKeyEvent=null;function runHandlers(map,event,view,scope){currentKeyEvent=event;let name=function(event){var name=!(mac&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie$1&&event.shiftKey&&event.key&&1==event.key.length||"Unidentified"==event.key)&&event.key||(event.shiftKey?shift:base)[event.keyCode]||event.key||"Unidentified";return"Esc"==name&&(name="Escape"),"Del"==name&&(name="Delete"),"Left"==name&&(name="ArrowLeft"),"Up"==name&&(name="ArrowUp"),"Right"==name&&(name="ArrowRight"),"Down"==name&&(name="ArrowDown"),name}(event),isChar=codePointSize(codePointAt(name,0))==name.length&&" "!=name,prefix="",handled=!1,prevented=!1,stopPropagation=!1;storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope&&(prefix=storedPrefix.prefix+" ",modifierCodes.indexOf(event.keyCode)<0&&(prevented=!0,storedPrefix=null));let baseName,shiftName,ran=new Set,runFor=binding=>{if(binding){for(let cmd of binding.run)if(!ran.has(cmd)&&(ran.add(cmd),cmd(view)))return binding.stopPropagation&&(stopPropagation=!0),!0;binding.preventDefault&&(binding.stopPropagation&&(stopPropagation=!0),prevented=!0)}return!1},scopeObj=map[scope];return scopeObj&&(runFor(scopeObj[prefix+modifiers(name,event,!isChar)])?handled=!0:isChar&&(event.altKey||event.metaKey||event.ctrlKey)&&!(browser.windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name?(runFor(scopeObj[prefix+modifiers(baseName,event,!0)])||event.shiftKey&&(shiftName=shift[event.keyCode])!=name&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,!1)]))&&(handled=!0):isChar&&event.shiftKey&&runFor(scopeObj[prefix+modifiers(name,event,!0)])&&(handled=!0),!handled&&runFor(scopeObj._any)&&(handled=!0)),prevented&&(handled=!0),handled&&stopPropagation&&event.stopPropagation(),currentKeyEvent=null,handled}class RectangleMarker{constructor(className,left,top,width,height){this.className=className,this.left=left,this.top=top,this.width=width,this.height=height}draw(){let elt=document.createElement("div");return elt.className=this.className,this.adjust(elt),elt}update(elt,prev){return prev.className==this.className&&(this.adjust(elt),!0)}adjust(elt){elt.style.left=this.left+"px",elt.style.top=this.top+"px",null!=this.width&&(elt.style.width=this.width+"px"),elt.style.height=this.height+"px"}eq(p){return this.left==p.left&&this.top==p.top&&this.width==p.width&&this.height==p.height&&this.className==p.className}static forRange(view,className,range){if(range.empty){let pos=view.coordsAtPos(range.head,range.assoc||1);if(!pos)return[];let base=getBase(view);return[new RectangleMarker(className,pos.left-base.left,pos.top-base.top,null,pos.bottom-pos.top)]}return function(view,className,range){if(range.to<=view.viewport.from||range.from>=view.viewport.to)return[];let from=Math.max(range.from,view.viewport.from),to=Math.min(range.to,view.viewport.to),ltr=view.textDirection==Direction.LTR,content=view.contentDOM,contentRect=content.getBoundingClientRect(),base=getBase(view),lineElt=content.querySelector(".cm-line"),lineStyle=lineElt&&window.getComputedStyle(lineElt),leftSide=contentRect.left+(lineStyle?parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent)):0),rightSide=contentRect.right-(lineStyle?parseInt(lineStyle.paddingRight):0),startBlock=blockAt(view,from),endBlock=blockAt(view,to),visualStart=startBlock.type==BlockType.Text?startBlock:null,visualEnd=endBlock.type==BlockType.Text?endBlock:null;visualStart&&(view.lineWrapping||startBlock.widgetLineBreaks)&&(visualStart=wrappedLine(view,from,1,visualStart));visualEnd&&(view.lineWrapping||endBlock.widgetLineBreaks)&&(visualEnd=wrappedLine(view,to,-1,visualEnd));if(visualStart&&visualEnd&&visualStart.from==visualEnd.from&&visualStart.to==visualEnd.to)return pieces(drawForLine(range.from,range.to,visualStart));{let top=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,!1),bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,!0),between=[];return(visualStart||startBlock).to<(visualEnd||endBlock).from-(visualStart&&visualEnd?1:0)||startBlock.widgetLineBreaks>1&&top.bottom+view.defaultLineHeight/2start&&r.from=endPos)break;spanTo>pos&&addSpan(Math.max(spanFrom,pos),null==from&&spanFrom<=start,Math.min(spanTo,endPos),null==to&&spanTo>=end,span.dir)}if(pos=docLine.to+1,pos>=endPos)break}return 0==horizontal.length&&addSpan(start,null==from,end,null==to,view.textDirection),{top:top,bottom:bottom,horizontal:horizontal}}function drawForWidget(block,top){let y=contentRect.top+(top?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}}(view,className,range)}}function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();return{left:(view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth*view.scaleX)-view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-view.scrollDOM.scrollTop*view.scaleY}}function wrappedLine(view,pos,side,inside){let coords=view.coordsAtPos(pos,2*side);if(!coords)return inside;let editorRect=view.dom.getBoundingClientRect(),y=(coords.top+coords.bottom)/2,left=view.posAtCoords({x:editorRect.left+1,y:y}),right=view.posAtCoords({x:editorRect.right-1,y:y});return null==left||null==right?inside:{from:Math.max(inside.from,Math.min(left,right)),to:Math.min(inside.to,Math.max(left,right))}}class LayerView{constructor(view,layer){this.view=view,this.layer=layer,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=view.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),layer.above&&this.dom.classList.add("cm-layer-above"),layer.class&&this.dom.classList.add(layer.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(view.state),view.requestMeasure(this.measureReq),layer.mount&&layer.mount(this.dom,view)}update(update){update.startState.facet(layerOrder)!=update.state.facet(layerOrder)&&this.setOrder(update.state),(this.layer.update(update,this.dom)||update.geometryChanged)&&(this.scale(),update.view.requestMeasure(this.measureReq))}docViewUpdate(view){!1!==this.layer.updateOnDocViewUpdate&&view.requestMeasure(this.measureReq)}setOrder(state){let pos=0,order=state.facet(layerOrder);for(;pos{return a=p,b=this.drawn[i],!(a.constructor==b.constructor&&a.eq(b));var a,b}))){let old=this.dom.firstChild,oldI=0;for(let marker of markers)marker.update&&old&&marker.constructor&&this.drawn[oldI].constructor&&marker.update(old,this.drawn[oldI])?(old=old.nextSibling,oldI++):this.dom.insertBefore(marker.draw(),old);for(;old;){let next=old.nextSibling;old.remove(),old=next}this.drawn=markers}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const layerOrder=Facet.define();function layer(config){return[ViewPlugin.define((v=>new LayerView(v,config))),layerOrder.of(config)]}const CanHidePrimary=!browser.ios,selectionConfig=Facet.define({combine:configs=>combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})});function drawSelection(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[selectionConfig.of(config),cursorLayer,selectionLayer,hideNativeSelection,nativeSelectionHidden.of(!0)]}function configChanged(update){return update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig)}const cursorLayer=layer({above:!0,markers(view){let{state:state}=view,conf=state.facet(selectionConfig),cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let className=prim?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",cursor=r.empty?r:EditorSelection.cursor(r.head,r.head>r.anchor?-1:1);for(let piece of RectangleMarker.forRange(view,className,cursor))cursors.push(piece)}}return cursors},update(update,dom){update.transactions.some((tr=>tr.selection))&&(dom.style.animationName="cm-blink"==dom.style.animationName?"cm-blink2":"cm-blink");let confChange=configChanged(update);return confChange&&setBlinkRate(update.state,dom),update.docChanged||update.selectionSet||confChange},mount(dom,view){setBlinkRate(view.state,dom)},class:"cm-cursorLayer"});function setBlinkRate(state,dom){dom.style.animationDuration=state.facet(selectionConfig).cursorBlinkRate+"ms"}const selectionLayer=layer({above:!1,markers:view=>view.state.selection.ranges.map((r=>r.empty?[]:RectangleMarker.forRange(view,"cm-selectionBackground",r))).reduce(((a,b)=>a.concat(b))),update:(update,dom)=>update.docChanged||update.selectionSet||update.viewportChanged||configChanged(update),class:"cm-selectionLayer"}),themeSpec={".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"}},".cm-content":{"& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}};CanHidePrimary&&(themeSpec[".cm-line"].caretColor=themeSpec[".cm-content"].caretColor="transparent !important");const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec)),setDropCursorPos=StateEffect.define({map:(pos,mapping)=>null==pos?null:mapping.mapPos(pos)}),dropCursorPos=StateField.define({create:()=>null,update:(pos,tr)=>(null!=pos&&(pos=tr.changes.mapPos(pos)),tr.effects.reduce(((pos,e)=>e.is(setDropCursorPos)?e.value:pos),pos))}),drawDropCursor=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(update){var _a;let cursorPos=update.state.field(dropCursorPos);null==cursorPos?null!=this.cursor&&(null===(_a=this.cursor)||void 0===_a||_a.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:view}=this,pos=view.state.field(dropCursorPos),rect=null!=pos&&view.coordsAtPos(pos);if(!rect)return null;let outer=view.scrollDOM.getBoundingClientRect();return{left:rect.left-outer.left+view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-outer.top+view.scrollDOM.scrollTop*view.scaleY,height:rect.bottom-rect.top}}drawCursor(pos){if(this.cursor){let{scaleX:scaleX,scaleY:scaleY}=this.view;pos?(this.cursor.style.left=pos.left/scaleX+"px",this.cursor.style.top=pos.top/scaleY+"px",this.cursor.style.height=pos.height/scaleY+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(pos){this.view.state.field(dropCursorPos)!=pos&&this.view.dispatch({effects:setDropCursorPos.of(pos)})}},{eventObservers:{dragover(event){this.setDropPos(this.view.posAtCoords({x:event.clientX,y:event.clientY}))},dragleave(event){event.target!=this.view.contentDOM&&this.view.contentDOM.contains(event.relatedTarget)||this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function iterMatches(doc,re,from,to,f){re.lastIndex=0;for(let m,cursor=doc.iterRange(from,to),pos=from;!cursor.next().done;pos+=cursor.value.length)if(!cursor.lineBreak)for(;m=re.exec(cursor.value);)f(pos+m.index,m)}class MatchDecorator{constructor(config){const{regexp:regexp,decoration:decoration,decorate:decorate,boundary:boundary,maxLength:maxLength=1e3}=config;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=regexp,decorate)this.addMatch=(match,view,from,add)=>decorate(add,from,from+match[0].length,match,view);else if("function"==typeof decoration)this.addMatch=(match,view,from,add)=>{let deco=decoration(match,view,from);deco&&add(from,from+match[0].length,deco)};else{if(!decoration)throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.addMatch=(match,_view,from,add)=>add(from,from+match[0].length,decoration)}this.boundary=boundary,this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add=build.add.bind(build);for(let{from:from,to:to}of function(view,maxLength){let visible=view.visibleRanges;if(1==visible.length&&visible[0].from==view.viewport.from&&visible[0].to==view.viewport.to)return visible;let result=[];for(let{from:from,to:to}of visible)from=Math.max(view.state.doc.lineAt(from).from,from-maxLength),to=Math.min(view.state.doc.lineAt(to).to,to+maxLength),result.length&&result[result.length-1].to>=from?result[result.length-1].to=to:result.push({from:from,to:to});return result}(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,((from,m)=>this.addMatch(m,view,from,add)));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;return update.docChanged&&update.changes.iterChanges(((_f,_t,from,to)=>{to>update.view.viewport.from&&from1e3?this.createDeco(update.view):changeTo>-1?this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo):deco}updateRange(view,deco,updateFrom,updateTo){for(let r of view.visibleRanges){let from=Math.max(r.from,updateFrom),to=Math.min(r.to,updateTo);if(to>from){let fromLine=view.state.doc.lineAt(from),toLine=fromLine.tofromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;toranges.push(deco.range(from,to));if(fromLine==toLine)for(this.regexp.lastIndex=start-fromLine.from;(m=this.regexp.exec(fromLine.text))&&m.indexthis.addMatch(m,view,from,add)));deco=deco.update({filterFrom:start,filterTo:end,filter:(from,to)=>fromend,add:ranges})}}return deco}}const UnicodeRegexpSupport=null!=/x/.unicode?"gu":"g",Specials=new RegExp("[\0-\b\n--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\ufeff-]",UnicodeRegexpSupport),Names={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let _supportsTabSize=null;const specialCharConfig=Facet.define({combine(configs){let config=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});return(config.replaceTabs=!function(){var _a;if(null==_supportsTabSize&&"undefined"!=typeof document&&document.body){let styles=document.body.style;_supportsTabSize=null!=(null!==(_a=styles.tabSize)&&void 0!==_a?_a:styles.MozTabSize)}return _supportsTabSize||!1}())&&(config.specialChars=new RegExp("\t|"+config.specialChars.source,UnicodeRegexpSupport)),config.addSpecialChars&&(config.specialChars=new RegExp(config.specialChars.source+"|"+config.addSpecialChars.source,UnicodeRegexpSupport)),config}});function highlightSpecialChars(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[specialCharConfig.of(config),specialCharPlugin()]}let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=Decoration.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(view.state.facet(specialCharConfig)),this.decorations=this.decorator.createDeco(view)}makeDecorator(conf){return new MatchDecorator({regexp:conf.specialChars,decoration:(m,view,pos)=>{let{doc:doc}=view.state,code=codePointAt(m[0],0);if(9==code){let line=doc.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}class SpecialCharWidget extends WidgetType{constructor(options,code){super(),this.options=options,this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=function(code){return code>=32?"•":10==code?"␤":String.fromCharCode(9216+code)}(this.code),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}}class TabWidget extends WidgetType{constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent="\t",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}}const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.docChanged||update.selectionSet)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations});function getPos(view,event){let offset=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset),off=offset-line.from,col=off>2e3?-1:off==line.length?function(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}(view,event.clientX):countColumn(line.text,view.state.tabSize,offset-line.from);return{line:line.number,col:col,off:off}}function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)},startSel=startSel.map(update.changes)}},get(event,_extend,multiple){let cur=getPos(view,event);if(!cur)return startSel;let ranges=function(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),ranges=[];if(a.off>2e3||b.off>2e3||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);line.length<=endOff&&ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}(view.state,start,cur);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}function rectangularSelection(options){let filter=(null==options?void 0:options.eventFilter)||(e=>e.altKey&&0==e.button);return EditorView.mouseSelectionStyle.of(((view,event)=>filter(event)?rectangleSelectionStyle(view,event):null))}const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){e.keyCode!=code&&getter(e)||this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of((view=>{var _a;return(null===(_a=view.plugin(plugin))||void 0===_a?void 0:_a.isDown)?showCrosshair:null}))]}class TooltipViewManager{constructor(view,facet,createTooltipView,removeTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.removeTooltipView=removeTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter((t=>t));let prev=null;this.tooltipViews=this.tooltips.map((t=>prev=createTooltipView(t,prev)))}update(update,above){var _a;let input=update.state.facet(this.facet),tooltips=input.filter((x=>x));if(input===this.input){for(let t of this.tooltipViews)t.update&&t.update(update);return!1}let tooltipViews=[],newAbove=above?[]:null;for(let i=0;iabove[i]=val)),above.length=newAbove.length),this.input=input,this.tooltips=tooltips,this.tooltipViews=tooltipViews,!0}}function windowSpace(view){let{win:win}=view;return{top:0,left:0,bottom:win.innerHeight,right:win.innerWidth}}const tooltipConfig=Facet.define({combine:values=>{var _a,_b,_c;return{position:browser.ios?"absolute":(null===(_a=values.find((conf=>conf.position)))||void 0===_a?void 0:_a.position)||"fixed",parent:(null===(_b=values.find((conf=>conf.parent)))||void 0===_b?void 0:_b.parent)||null,tooltipSpace:(null===(_c=values.find((conf=>conf.tooltipSpace)))||void 0===_c?void 0:_c.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config=view.state.facet(tooltipConfig);this.position=config.position,this.parent=config.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver="function"==typeof ResizeObserver?new ResizeObserver((()=>this.measureSoon())):null,this.manager=new TooltipViewManager(view,showTooltip,((t,p)=>this.createTooltip(t,p)),(t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()})),this.above=this.manager.tooltips.map((t=>!!t.above)),this.intersectionObserver="function"==typeof IntersectionObserver?new IntersectionObserver((entries=>{Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1&&this.measureSoon()}),{threshold:[1]}):null,this.observeIntersection(),view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout((()=>{this.measureTimeout=-1,this.maybeMeasure()}),50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update,this.above);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t of this.manager.tooltipViews)t.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t of this.manager.tooltipViews)this.container.appendChild(t.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip,prev){let tooltipView=tooltip.create(this.view),before=prev?prev.dom:null;if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top="-10000px",tooltipView.dom.style.left="0px",this.container.insertBefore(tooltipView.dom,before),tooltipView.mount&&tooltipView.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(tooltipView.dom),tooltipView}destroy(){var _a,_b,_c;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),null===(_a=tooltipView.destroy)||void 0===_a||_a.call(tooltipView);this.parent&&this.container.remove(),null===(_b=this.resizeObserver)||void 0===_b||_b.disconnect(),null===(_c=this.intersectionObserver)||void 0===_c||_c.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if("fixed"==this.position&&this.manager.tooltipViews.length){let{dom:dom}=this.manager.tooltipViews[0];if(browser.gecko)makeAbsolute=dom.offsetParent!=this.container.ownerDocument.body;else if("-10000px"==dom.style.top&&"0px"==dom.style.left){let rect=dom.getBoundingClientRect();makeAbsolute=Math.abs(rect.top+1e4)>1||Math.abs(rect.left)>1}}if(makeAbsolute||"absolute"==this.position)if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX:scaleX,scaleY:scaleY}=this.view.viewState);return{editor:editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map(((t,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t.pos):this.view.coordsAtPos(t.pos)})),size:this.manager.tooltipViews.map((_ref7=>{let{dom:dom}=_ref7;return dom.getBoundingClientRect()})),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX:scaleX,scaleY:scaleY,makeAbsolute:makeAbsolute}}writeMeasure(measured){var _a;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t of this.manager.tooltipViews)t.dom.style.position="absolute"}let{editor:editor,space:space,scaleX:scaleX,scaleY:scaleY}=measured,others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top="-10000px";continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=null!==(_a=knownHeight.get(tView))&&void 0!==_a?_a:size.bottom-size.top,offset=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset.x),above=this.above[i];!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=this.above[i]=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVertleft&&r.toptop&&(top=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if("absolute"==this.position?(dom.style.top=(top-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset.x:-offset.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}!0!==tView.overlap&&others.push({left:left,top:top,right:right,bottom:top+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top="-10000px"}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$4=EditorView.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"".concat(7,"px"),width:"".concat(14,"px"),position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"".concat(7,"px solid transparent"),borderRight:"".concat(7,"px solid transparent")},".cm-tooltip-above &":{bottom:"-".concat(7,"px"),"&:before":{borderTop:"".concat(7,"px solid #bbb")},"&:after":{borderTop:"".concat(7,"px solid #f5f5f5"),bottom:"1px"}},".cm-tooltip-below &":{top:"-".concat(7,"px"),"&:before":{borderBottom:"".concat(7,"px solid #bbb")},"&:after":{borderBottom:"".concat(7,"px solid #f5f5f5"),top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$4]}),showHoverTooltip=Facet.define({combine:inputs=>inputs.reduce(((a,i)=>a.concat(i)),[])});class HoverTooltipHost{static create(view){return new HoverTooltipHost(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,((t,p)=>this.createHostedView(t,p)),(t=>t.dom.remove()))}createHostedView(tooltip,prev){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(hostedView.dom,prev?prev.dom.nextSibling:this.dom.firstChild),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a;for(let t of this.manager.tooltipViews)null===(_a=t.destroy)||void 0===_a||_a.call(t)}passProp(name){let value;for(let view of this.manager.tooltipViews){let given=view[name];if(void 0!==given)if(void 0===value)value=given;else if(value!==given)return}return value}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],(state=>{let tooltips=state.facet(showHoverTooltip);return 0===tooltips.length?null:{pos:Math.min(...tooltips.map((t=>t.pos))),end:Math.max(...tooltips.map((t=>{var _a;return null!==(_a=t.end)&&void 0!==_a?_a:t.pos}))),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some((t=>t.arrow))}}));class HoverPlugin{constructor(view,source,field,setHover,hoverTime){this.view=view,this.source=source,this.field=field,this.setHover=setHover,this.hoverTime=hoverTime,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:view.dom,time:0},this.checkHover=this.checkHover.bind(this),view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout((()=>this.startHover()),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let hovered=Date.now()-this.lastMove.time;hoveredposCoords.bottom||lastMove.xposCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find((s=>s.from<=pos&&s.to>=pos)),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x{this.pending==pending&&(this.pending=null,!result||Array.isArray(result)&&!result.length||view.dispatch({effects:this.setHover.of(Array.isArray(result)?result:[result])}))}),(e=>logException(view.state,e,"hover tooltip")))}else!open||Array.isArray(open)&&!open.length||view.dispatch({effects:this.setHover.of(Array.isArray(open)?open:[open])})}get tooltip(){let plugin=this.view.plugin(tooltipPlugin),index=plugin?plugin.manager.tooltips.findIndex((t=>t.create==HoverTooltipHost.create)):-1;return index>-1?plugin.manager.tooltipViews[index]:null}mousemove(event){var _a,_b;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:active,tooltip:tooltip}=this;if(active.length&&tooltip&&!function(tooltip,event){let rect=tooltip.getBoundingClientRect();return event.clientX>=rect.left-4&&event.clientX<=rect.right+4&&event.clientY>=rect.top-4&&event.clientY<=rect.bottom+4}(tooltip.dom,event)||this.pending){let{pos:pos}=active[0]||this.pending,end=null!==(_b=null===(_a=active[0])||void 0===_a?void 0:_a.end)&&void 0!==_b?_b:pos;(pos==end?this.view.posAtCoords(this.lastMove)==pos:function(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.righty||Math.min(rect.bottom,docBottom)=from&&pos<=to}(this.view,pos,end,event.clientX,event.clientY))||(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(event){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:active}=this;if(active.length){let{tooltip:tooltip}=this;tooltip&&tooltip.dom.contains(event.relatedTarget)?this.watchTooltipLeave(tooltip.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(tooltip){let watch=event=>{tooltip.removeEventListener("mouseleave",watch),this.active.length&&!this.view.dom.contains(event.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};tooltip.addEventListener("mouseleave",watch)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer:topContainer,bottomContainer:bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index=plugin?plugin.specs.indexOf(panel):-1;return index>-1?plugin.panels[index]:null}const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter((s=>s)),this.panels=this.specs.map((spec=>spec(view)));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,conf.bottomContainer),this.top.sync(this.panels.filter((p=>p.top))),this.bottom.sync(this.panels.filter((p=>!p.top)));for(let p of this.panels)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter((x=>x)),panels=[],top=[],bottom=[],mount=[];for(let spec of specs){let panel,known=this.specs.indexOf(spec);known<0?(panel=spec(update.view),mount.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top),this.bottom.sync(bottom);for(let p of mount)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of((view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}}))});class PanelGroup{constructor(view,top,container){this.view=view,this.top=top,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(0==this.panels.length)return void(this.dom&&(this.dom.remove(),this.dom=void 0));if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels)if(panel.dom.parentNode==this.dom){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;curDOM;)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(this.container&&this.classes!=this.view.themeClasses){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}}function rm(node){let next=node.nextSibling;return node.remove(),next}const showPanel=Facet.define({enables:panelPlugin});class GutterMarker extends RangeValue{compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}}GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config))]}const unfixGutters=Facet.define({combine:values=>values.some((x=>x))});function gutters(config){let result=[gutterView];return config&&!1===config.fixed&&result.push(unfixGutters.of(!0)),result}const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=view.state.facet(activeGutters).map((conf=>new SingleGutterView(view,conf)));for(let gutter of this.gutters)this.dom.appendChild(gutter.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<.8*(vpB.to-vpB.from))}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map((gutter=>new UpdateContext(gutter,this.view.viewport,-this.view.documentPadding.top)));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;for(let b of line.type)if(b.type==BlockType.Text&&first){advanceCursor(lineClasses,classSet,b.from);for(let cx of contexts)cx.line(this.view,b,classSet);first=!1}else if(b.widget)for(let cx of contexts)cx.widget(this.view,b)}else if(line.type==BlockType.Text){advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,line,classSet)}else if(line.widget)for(let cx of contexts)cx.widget(this.view,line);for(let cx of contexts)cx.finish();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur)for(let gutter of this.gutters)gutter.update(update)&&(change=!0);else{change=!0;let gutters=[];for(let conf of cur){let known=prev.indexOf(conf);known<0?gutters.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters.indexOf(g)<0&&g.destroy();for(let g of gutters)this.dom.appendChild(g.dom);this.gutters=gutters}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of((view=>{let value=view.plugin(plugin);return value&&0!=value.gutters.length&&value.fixed?view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}:null}))});function asArray(val){return Array.isArray(val)?val:[val]}function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}class UpdateContext{constructor(gutter,viewport,height){this.gutter=gutter,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter.elements.push(newElt),gutter.dom.appendChild(newElt.dom)}else gutter.elements[this.i].update(view,height,above,markers);this.height=block.bottom,this.i++}line(view,line,extraMarkers){let localMarkers=[];advanceCursor(this.cursor,localMarkers,line.from),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter=this.gutter;(0!=localMarkers.length||gutter.config.renderEmptyElements)&&this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter=this.gutter;for(;gutter.elements.length>this.i;){let last=gutter.elements.pop();gutter.dom.removeChild(last.dom),last.destroy()}}}class SingleGutterView{constructor(view,config){this.view=view,this.config=config,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config.domEventHandlers)this.dom.addEventListener(prop,(event=>{let y,target=event.target;if(target!=this.dom&&this.dom.contains(target)){for(;target.parentNode!=this.dom;)target=target.parentNode;let rect=target.getBoundingClientRect();y=(rect.top+rect.bottom)/2}else y=event.clientY;let line=view.lineBlockAtHeight(y-view.documentTop);config.domEventHandlers[prop](view,line,event)&&event.preventDefault()}));this.markers=asArray(config.markers(view)),config.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||!!this.config.lineMarkerChange&&this.config.lineMarkerChange(update)}destroy(){for(let elt of this.elements)elt.destroy()}}class GutterElement{constructor(view,height,above,markers){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(view,height,above,markers)}update(view,height,above,markers){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),function(a,b){if(a.length!=b.length)return!1;for(let i=0;icombineConfig(values,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(a,b){let result=Object.assign({},a);for(let event in b){let exists=result[event],add=b[event];result[event]=exists?(view,line,event)=>exists(view,line,event)||add(view,line,event):add}return result}})});class NumberMarker extends GutterMarker{constructor(number){super(),this.number=number}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}}function formatNumber(view,number){return view.state.facet(lineNumberConfig).formatNumber(number,view.state)}const lineNumberGutter=activeGutters.compute([lineNumberConfig],(state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers:view=>view.state.facet(lineNumberMarkers),lineMarker:(view,line,others)=>others.some((m=>m.toDOM))?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number)),widgetMarker:()=>null,lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer:view=>new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines))),updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers})));function lineNumbers(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[lineNumberConfig.of(config),gutters(),lineNumberGutter]}function maxLineNumber(lines){let last=9;for(;last{let marks=[],last=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last&&(last=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)}));const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from,this.to=to}}class NodeProp{constructor(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.id=nextPropID++,this.perNode=!!config.perNode,this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof match&&(match=NodeType.match(match)),type=>{let result=match(type);return void 0===result?null:[this,result]}}}NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});class MountedTree{constructor(tree,overlay,parser){this.tree=tree,this.overlay=overlay,this.parser=parser}}const noProps=Object.create(null);class NodeType{constructor(name,props,id){let flags=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;this.name=name,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(null==spec.name?8:0),type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}return type}prop(prop){return this.props[prop.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(name){if("string"==typeof name){if(this.name==name)return!0;let group=this.prop(NodeProp.group);return!!group&&group.indexOf(name)>-1}return this.id==name}static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(types){this.types=types;for(let i=0;i0&&void 0!==arguments[0]?arguments[0]:0;return new TreeCursor(this.topNode,mode)}cursorAt(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,scope=CachedNode.get(this)||this.topNode,cursor=new TreeCursor(scope);return cursor.moveTo(pos,side),CachedNode.set(this,cursor._tree),cursor}get topNode(){return new TreeNode(this,0,0,null)}resolve(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,!1);return CachedNode.set(this,node),node}resolveInner(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,!0);return CachedInnerNode.set(this,node),node}iterate(spec){let{enter:enter,leave:leave,from:from=0,to:to=this.length}=spec,mode=spec.mode||0,anon=(mode&IterMode.IncludeAnonymous)>0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||!1!==enter(c))){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((children,positions,length)=>new Tree(this.type,children,positions,length,this.propValues)),config.makeTree||((children,positions,length)=>new Tree(NodeType.none,children,positions,length)))}static build(data){return function(data){var _a;let{buffer:buffer,nodeSet:nodeSet,maxBufferLength:maxBufferLength=DefaultBufferLength,reused:reused=[],minRepeatType:minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id:id,start:start,end:end,size:size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;){if(cursor.next(),-1==size){let node=reused[id];return children.push(node),void positions.push(start-parentStart)}if(-3==size)return void(contextHash=id);if(-4==size)return void(lookAhead=id);throw new RangeError("Unrecognized record size: ".concat(size))}let node,buffer,type=types[id],startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){let data=new Uint16Array(buffer.size-buffer.skip),endPos=cursor.pos-buffer.size,index=data.length;for(;cursor.pos>endPos;)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet),startPos=buffer.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children.push(node),positions.push(startPos)}function makeBalanced(type){return(children,positions,length)=>{let last,lookAheadProp,lookAhead=0,lastI=children.length-1;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;(lookAheadProp=last.prop(NodeProp.lookAhead))&&(lookAhead=positions[lastI]+last.length+lookAheadProp)}return makeTree(type,children,positions,length,lookAhead)}}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];for(;children.length>i;)localChildren.push(children.pop()),localPositions.push(positions.pop()+base-from);children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to)),positions.push(from-base)}function makeTree(type,children,positions,length){let lookAhead=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,props=arguments.length>5?arguments[5]:void 0;if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair]}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair]}return new Tree(type,children,positions,length,props)}function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;if(fork.id==inRepeat&&nodeSize>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos=minRepeatType?4:0,nodeStart=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0){if(-3!=fork.size)break scan;localSkipped+=4}else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart,size+=nodeSize,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}function copyToBuffer(bufferStart,buffer,index){let{id:id,start:start,end:end,size:size}=cursor;if(cursor.next(),size>=0&&id4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index=copyToBuffer(bufferStart,buffer,index)}buffer[--index]=startIndex,buffer[--index]=end-bufferStart,buffer[--index]=start-bufferStart,buffer[--index]=id}else-3==size?contextHash=id:-4==size&&(lookAhead=id);return index}let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=null!==(_a=data.length)&&void 0!==_a?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length)}(data)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer,this.index=index}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index=0;index0));i=buffer[i+3]);return pick}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i=pos&&frompos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last=scan.lastChild;if(!last||last.to!=scan.to)break;last.type.isError&&last.from==last.to?(node=scan,scan=last.prevSibling):scan=last}return node}function resolveNode(node,pos,side,overlays){for(var _a;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to4&&void 0!==arguments[4]?arguments[4]:0;for(let parent=this;;){for(let{children:children,positions:positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length))if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(i=parent.index>=0?parent.index+dir:dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side){let mounted,mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from:from,to:to}of mounted.overlay)if((side>0?from<=rPos:from=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;val.type.isAnonymous&&val._parent;)val=val._parent;return val}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(){return new TreeCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!1)}resolveInner(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}getChild(type){let r=getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null);return r.length?r[0]:null}getChildren(type){return getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(null!=before)for(;!cur.type.is(before);)if(!cur.nextSibling())return result;for(;;){if(null!=after&&cur.type.is(after))return result;if(cur.type.is(type)&&result.push(cur.node),!cur.nextSibling())return null==after?result:[]}}function matchNodeContext(node,context){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:context.length-1;for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent,this.buffer=buffer,this.index=index,this.start=start}}class BufferNode{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(context,_parent,index){this.context=context,this._parent=_parent,this.index=index,this.type=context.buffer.set.types[context.buffer.buffer[index]]}child(dir,pos,side){let{buffer:buffer}=this.context,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side){if((arguments.length>2&&void 0!==arguments[2]?arguments[2]:0)&IterMode.ExcludeBuffers)return null;let{buffer:buffer}=this.context,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4)}get nextSibling(){let{buffer:buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new BufferNode(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer:buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(){return new TreeCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}get tree(){return null}toTree(){let children=[],positions=[],{buffer:buffer}=this.context,startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1];children.push(buffer.slice(startI,endI,from)),positions.push(0)}return new Tree(this.type,children,positions,this.to-this.from)}resolve(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!1)}resolveInner(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}getChild(type){let r=getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null);return r.length?r[0]:null}getChildren(type){return getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}}class TreeCursor{get name(){return this.type.name}constructor(node){let mode=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return!!node&&(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0)}yieldBuf(index,type){this.index=index;let{start:start,buffer:buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index]],this.from=start+buffer.buffer[index+1],this.to=start+buffer.buffer[index+2],!0}yield(node){return!!node&&(node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer:buffer}=this.buffer,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return!(index<0)&&(this.stack.push(this.index),this.yieldBuf(index))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side){let mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.mode;return this.buffer?!(mode&IterMode.ExcludeBuffers)&&this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode));let{buffer:buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4))}else{let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after)}return d<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index,parent,{buffer:buffer}=this;if(buffer){if(dir>0){if(this.index-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(){let enter=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.move(1,enter)}prev(){let enter=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.move(-1,enter)}moveTo(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c,depth=d+1;break scan}index=this.stack[--d]}for(let i=depth;i=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}}function hasChild(tree){return tree.children.some((ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch)))}const nodeSizeCache=new WeakMap;function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(null==size){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break}size+=nodeSize(balanceType,child)}nodeSizeCache.set(node,size)}return size}function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue}localChildren.push(children[groupFrom])}else{let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree))}localPositions.push(groupStart+offset-start)}}(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}class NodeWeakMap{constructor(){this.map=new WeakMap}setBuffer(buffer,index,value){let inner=this.map.get(buffer);inner||this.map.set(buffer,inner=new Map),inner.set(index,value)}getBuffer(buffer,index){let inner=this.map.get(buffer);return inner&&inner.get(index)}set(node,value){node instanceof BufferNode?this.setBuffer(node.context.buffer,node.index,value):node instanceof TreeNode&&this.map.set(node.tree,value)}get(node){return node instanceof BufferNode?this.getBuffer(node.context.buffer,node.index):node instanceof TreeNode?this.map.get(node.tree):void 0}cursorSet(cursor,value){cursor.buffer?this.setBuffer(cursor.buffer.buffer,cursor.index,value):this.map.set(cursor.tree,value)}cursorGet(cursor){return cursor.buffer?this.getBuffer(cursor.buffer.buffer,cursor.index):this.map.get(cursor.tree)}}class TreeFragment{constructor(from,to,tree,offset){let openStart=arguments.length>4&&void 0!==arguments[4]&&arguments[4],openEnd=arguments.length>5&&void 0!==arguments[5]&&arguments[5];this.from=from,this.to=to,this.tree=tree,this.offset=offset,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(1&this.open)>0}get openEnd(){return(2&this.open)>0}static addTree(tree){let fragments=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],partial=arguments.length>2&&void 0!==arguments[2]&&arguments[2],result=[new TreeFragment(0,tree.length,tree,0,!1,partial)];for(let f of fragments)f.to>tree.length&&result.push(f);return result}static applyChanges(fragments,changes){let minGap=arguments.length>2&&void 0!==arguments[2]?arguments[2]:128;if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off=0;;cI++){let nextC=cI=minGap)for(;nextF&&nextF.from=cut.from||nextPos<=cut.to||off){let fFrom=Math.max(cut.from,pos)-off,fTo=Math.min(cut.to,nextPos)-off;cut=fFrom>=fTo?null:new TreeFragment(fFrom,fTo,cut.tree,cut.offset+off,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fInew Range(r.from,r.to))):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done}}}class StringInput{constructor(string){this.string=string}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}}function parseMixed(nest){return(parse,input,fragments,ranges)=>new MixedParse(parse,nest,input,fragments,ranges)}class InnerParse{constructor(parser,parse,overlay,target,ranges){if(this.parser=parser,this.parse=parse,this.overlay=overlay,this.target=target,this.ranges=ranges,!ranges.length||ranges.some((r=>r.from>=r.to)))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(ranges))}}class ActiveOverlay{constructor(parser,predicate,mounts,index,start,target,prev){this.parser=parser,this.predicate=predicate,this.mounts=mounts,this.index=index,this.start=start,this.target=target,this.prev=prev,this.depth=0,this.ranges=[]}}const stoppedInner=new NodeProp({perNode:!0});class MixedParse{constructor(base,nest,input,fragments,ranges){this.nest=nest,this.input=input,this.fragments=fragments,this.ranges=ranges,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=base}advance(){if(this.baseParse){let done=this.baseParse.advance();if(!done)return null;if(this.baseParse=null,this.baseTree=done,this.startInner(),null!=this.stoppedAt)for(let inner of this.inner)inner.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let result=this.baseTree;return null!=this.stoppedAt&&(result=new Tree(result.type,result.children,result.positions,result.length,result.propValues.concat([[stoppedInner,this.stoppedAt]]))),result}let inner=this.inner[this.innerDone],done=inner.parse.advance();if(done){this.innerDone++;let props=Object.assign(Object.create(null),inner.target.props);props[NodeProp.mounted.id]=new MountedTree(done,inner.overlay,inner.parser),inner.target.props=props}return null}get parsedPos(){if(this.baseParse)return 0;let pos=this.input.length;for(let i=this.innerDone;im.frag.from<=cursor.from&&m.frag.to>=cursor.to&&m.mount.overlay));if(match)for(let r of match.mount.overlay){let from=r.from+match.pos,to=r.to+match.pos;from>=cursor.from&&to<=cursor.to&&!overlay.ranges.some((r=>r.fromfrom))&&overlay.ranges.push({from:from,to:to})}}enter=!1}else if(covered&&(isCovered=checkCover(covered.ranges,cursor.from,cursor.to)))enter=2!=isCovered;else if(!cursor.type.isAnonymous&&cursor.fromnew Range(r.from-cursor.from,r.to-cursor.from))):null,cursor.tree,ranges)),nest.overlay?ranges.length&&(covered={ranges:ranges,depth:0,prev:covered}):enter=!1}}else overlay&&(range=overlay.predicate(cursor))&&(!0===range&&(range=new Range(cursor.from,cursor.to)),range.fromnew Range(r.from-overlay.start,r.to-overlay.start))),overlay.target,ranges)),overlay=overlay.prev}covered&&!--covered.depth&&(covered=covered.prev)}}}}function checkCover(covered,from,to){for(let range of covered){if(range.from>=to)break;if(range.to>from)return range.from<=from&&range.to>=to?2:1}return 0}function sliceBuf(buf,startI,endI,nodes,positions,off){if(startI=node.to);i++);let buf=base.children[i],b=buf.buffer;base.children[i]=function split(startI,endI,type,innerOffset,length){let i=startI;for(;b[i+2]+off<=node.from;)i=b[i+3];let children=[],positions=[];sliceBuf(buf,startI,i,children,positions,innerOffset);let from=b[i+1],to=b[i+2],isTarget=from+off==node.from&&to+off==node.to&&b[i]==node.type.id;return children.push(isTarget?node.toTree():split(i+4,b[i+3],buf.set.types[b[i]],from,to-from)),positions.push(from-innerOffset),sliceBuf(buf,b[i+3],endI,children,positions,innerOffset),new Tree(type,children,positions,length)}(0,b.length,NodeType.none,0,buf.length);for(let d=0;d<=depth;d++)cursor.childAfter(node.from)}class StructureCursor{constructor(root,offset){this.offset=offset,this.done=!1,this.cursor=root.cursor(IterMode.IncludeAnonymous|IterMode.IgnoreMounts)}moveTo(pos){let{cursor:cursor}=this,p=pos-this.offset;for(;!this.done&&cursor.from=pos&&cursor.enter(p,1,IterMode.IgnoreOverlays|IterMode.ExcludeBuffers)||cursor.next(!1)||(this.done=!0)}hasNode(cursor){if(this.moveTo(cursor.from),!this.done&&this.cursor.from+this.offset==cursor.from&&this.cursor.tree)for(let tree=this.cursor.tree;;){if(tree==cursor.tree)return!0;if(!(tree.children.length&&0==tree.positions[0]&&tree.children[0]instanceof Tree))break;tree=tree.children[0]}return!1}}let FragmentCursor$1=class{constructor(fragments){var _a;if(this.fragments=fragments,this.curTo=0,this.fragI=0,fragments.length){let first=this.curFrag=fragments[0];this.curTo=null!==(_a=first.tree.prop(stoppedInner))&&void 0!==_a?_a:first.to,this.inner=new StructureCursor(first.tree,-first.offset)}else this.curFrag=this.inner=null}hasNode(node){for(;this.curFrag&&node.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=node.from&&this.curTo>=node.to&&this.inner.hasNode(node)}nextFrag(){var _a;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let frag=this.curFrag=this.fragments[this.fragI];this.curTo=null!==(_a=frag.tree.prop(stoppedInner))&&void 0!==_a?_a:frag.to,this.inner=new StructureCursor(frag.tree,-frag.offset)}}findMounts(pos,parser){var _a;let result=[];if(this.inner){this.inner.cursor.moveTo(pos,1);for(let pos=this.inner.cursor.node;pos;pos=pos.parent){let mount=null===(_a=pos.tree)||void 0===_a?void 0:_a.prop(NodeProp.mounted);if(mount&&mount.parser==parser)for(let i=this.fragI;i=pos.to)break;frag.tree==this.curFrag.tree&&result.push({frag:frag,pos:pos.from-frag.offset,mount:mount})}}}return result}};function punchRanges(outer,ranges){let copy=null,current=ranges;for(let i=1,j=0;i=gapTo)break;r.to<=gapFrom||(copy||(current=copy=ranges.slice()),r.fromgapTo&©.splice(j+1,0,new Range(gapTo,r.to))):r.to>gapTo?copy[j--]=new Range(gapTo,r.to):copy.splice(j--,1))}}return current}function findCoverChanges(a,b,from,to){let iA=0,iB=0,inA=!1,inB=!1,pos=-1e9,result=[];for(;;){let nextA=iA==a.length?1e9:inA?a[iA].to:a[iA].from,nextB=iB==b.length?1e9:inB?b[iB].to:b[iB].from;if(inA!=inB){let start=Math.max(pos,from),end=Math.min(nextA,nextB,to);startnew Range(r.from+pos,r.to+pos))),from,to);for(let i=0,pos=from;;i++){let last=i==changes.length,end=last?to:changes[i].from;if(end>pos&&result.push(new TreeFragment(pos,end,mount.tree,-startPos,frag.from>=pos||frag.openStart,frag.to<=end||frag.openEnd)),last)break;pos=changes[i].to}}else result.push(new TreeFragment(from,to,mount.tree,-startPos,frag.from>=startPos||frag.openStart,frag.to<=endPos||frag.openEnd))}return result}let nextTagID=0;class Tag{constructor(set,base,modified){this.set=set,this.base=base,this.modified=modified,this.id=nextTagID++}static define(parent){if(null==parent?void 0:parent.base)throw new Error("Can not derive from a modified tag");let tag=new Tag([],null,[]);if(tag.set.push(tag),parent)for(let t of parent.set)tag.set.push(t);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort(((a,b)=>a.id-b.id)))}}let nextModifierID=0;class Modifier{constructor(){this.instances=[],this.id=nextModifierID++}static get(base,mods){if(!mods.length)return base;let exists=mods[0].instances.find((t=>{return t.base==base&&(a=mods,b=t.modified,a.length==b.length&&a.every(((x,i)=>x==b[i])));var a,b}));if(exists)return exists;let set=[],tag=new Tag(set,base,mods);for(let m of mods)m.instances.push(tag);let configs=function(array){let sets=[[]];for(let i=0;ib.length-a.length))}(mods);for(let parent of base.set)if(!parent.modified.length)for(let config of configs)set.push(Modifier.get(parent,config));return tag}}function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags=spec[prop];Array.isArray(tags)||(tags=[tags]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if("..."==rest&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push("*"==m[0]?"":'"'==m[0][0]?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&"!"==next){mode=0;break}if("/"!=next)throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last=pieces.length-1,inner=pieces[last];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags,mode,last>0?pieces.slice(0,last):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}const ruleNodeProp=new NodeProp;class Rule{constructor(tags,mode,context,next){this.tags=tags,this.mode=mode,this.context=context,this.next=next}get opaque(){return 0==this.mode}get inherit(){return 1==this.mode}sort(other){return!other||other.depth{let cls=all;for(let tag of tags)for(let sub of tag.set){let tagClass=map[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope}}function highlightTree(tree,highlighter,putStyle){let from=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,to=arguments.length>4&&void 0!==arguments[4]?arguments[4]:tree.length,builder=new HighlightBuilder(from,Array.isArray(highlighter)?highlighter:[highlighter],putStyle);builder.highlightRange(tree.cursor(),from,to,"",builder.highlighters),builder.flush(to)}Rule.empty=new Rule([],2,null);class HighlightBuilder{constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){to>this.at&&this.class&&this.span(this.at,to,this.class)}highlightRange(cursor,from,to,inheritedClass,highlighters){let{type:type,from:start,to:end}=cursor;if(start>=to||end<=from)return;type.isTop&&(highlighters=this.highlighters.filter((h=>!h.scope||h.scope(type))));let cls=inheritedClass,rule=function(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}(cursor)||Rule.empty,tagCls=function(highlighters,tags){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags);value&&(result=result?result+" "+value:value)}return result}(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,1==rule.mode&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),rule.opaque)return;let mounted=cursor.tree&&cursor.tree.prop(NodeProp.mounted);if(mounted&&mounted.overlay){let inner=cursor.node.enter(mounted.overlay[0].from+start,1),innerHighlighters=this.highlighters.filter((h=>!h.scope||h.scope(mounted.tree.type))),hasChild=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i=nextPos)&&cursor.nextSibling()););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do{if(!(cursor.to<=from)){if(cursor.from>=to)break;this.highlightRange(cursor,from,to,inheritedClass,highlighters),this.startSpan(Math.min(to,cursor.to),cls)}}while(cursor.nextSibling());cursor.parent()}}}const t=Tag.define,comment$1=t(),name=t(),typeName=t(name),propertyName=t(name),literal=t(),string=t(literal),number=t(literal),content=t(),heading=t(content),keyword=t(),operator=t(),punctuation=t(),bracket=t(punctuation),meta=t(),tags$1={comment:comment$1,lineComment:t(comment$1),blockComment:t(comment$1),docComment:t(comment$1),name:name,variableName:t(name),typeName:typeName,tagName:t(typeName),propertyName:propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal:literal,string:string,docString:t(string),character:t(string),attributeValue:t(string),number:number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword:keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator:operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation:punctuation,separator:t(punctuation),bracket:bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content:content,heading:heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta:meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};var _a;tagHighlighter([{tag:tags$1.link,class:"tok-link"},{tag:tags$1.heading,class:"tok-heading"},{tag:tags$1.emphasis,class:"tok-emphasis"},{tag:tags$1.strong,class:"tok-strong"},{tag:tags$1.keyword,class:"tok-keyword"},{tag:tags$1.atom,class:"tok-atom"},{tag:tags$1.bool,class:"tok-bool"},{tag:tags$1.url,class:"tok-url"},{tag:tags$1.labelName,class:"tok-labelName"},{tag:tags$1.inserted,class:"tok-inserted"},{tag:tags$1.deleted,class:"tok-deleted"},{tag:tags$1.literal,class:"tok-literal"},{tag:tags$1.string,class:"tok-string"},{tag:tags$1.number,class:"tok-number"},{tag:[tags$1.regexp,tags$1.escape,tags$1.special(tags$1.string)],class:"tok-string2"},{tag:tags$1.variableName,class:"tok-variableName"},{tag:tags$1.local(tags$1.variableName),class:"tok-variableName tok-local"},{tag:tags$1.definition(tags$1.variableName),class:"tok-variableName tok-definition"},{tag:tags$1.special(tags$1.variableName),class:"tok-variableName2"},{tag:tags$1.definition(tags$1.propertyName),class:"tok-propertyName tok-definition"},{tag:tags$1.typeName,class:"tok-typeName"},{tag:tags$1.namespace,class:"tok-namespace"},{tag:tags$1.className,class:"tok-className"},{tag:tags$1.macroName,class:"tok-macroName"},{tag:tags$1.propertyName,class:"tok-propertyName"},{tag:tags$1.operator,class:"tok-operator"},{tag:tags$1.comment,class:"tok-comment"},{tag:tags$1.meta,class:"tok-meta"},{tag:tags$1.invalid,class:"tok-invalid"},{tag:tags$1.punctuation,class:"tok-punctuation"}]);const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}const sublanguageProp=new NodeProp;class Language{constructor(data,parser){let extraExtensions=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],name=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";this.data=data,this.name=name,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser,this.extension=[language.of(this),EditorState.languageData.of(((state,pos,side)=>{let top=topNodeAt(state,pos,side),data=top.type.prop(languageDataProp);if(!data)return[];let base=state.facet(data),sub=top.type.prop(sublanguageProp);if(sub){let innerNode=top.resolve(pos-top.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data=state.facet(sublang.facet);return"replace"==sublang.type?data:data.concat(base)}}return base}))].concat(extraExtensions)}isActiveAt(state,pos){return topNodeAt(state,pos,arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if((null==lang?void 0:lang.data)==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=(tree,from)=>{if(tree.prop(languageDataProp)==this.data)return void result.push({from:from,to:from+tree.length});let mount=tree.prop(NodeProp.mounted);if(mount){if(mount.tree.prop(languageDataProp)==this.data){if(mount.overlay)for(let r of mount.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from:from,to:from+tree.length});return}if(mount.overlay){let size=result.length;if(explore(mount.tree,mount.overlay[0].from+from),result.length>size)return}}for(let i=0;itype.isTop?data:void 0))]}),spec.name)}configure(options,name){return new LRLanguage(this.data,this.parser.configure(options),name||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}class DocInput{constructor(doc){this.doc=doc,this.cursorPos=0,this.string="",this.cursor=doc.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}}let currentContext=null;class ParseContext{constructor(parser,state){let fragments=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],tree=arguments.length>3?arguments[3]:void 0,treeLen=arguments.length>4?arguments[4]:void 0,viewport=arguments.length>5?arguments[5]:void 0,skipped=arguments.length>6?arguments[6]:void 0,scheduleOn=arguments.length>7?arguments[7]:void 0;this.parser=parser,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser,state,viewport){return new ParseContext(parser,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return null!=upto&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(null!=upto?upto:this.state.doc.length)?(this.takeTree(),!0):this.withContext((()=>{var _a;if("number"==typeof until){let endTime=Date.now()+until;until=()=>Date.now()>endTime}for(this.parse||(this.parse=this.startParse()),null!=upto&&(null==this.parse.stoppedAt||this.parse.stoppedAt>upto)&&upto=this.treeLen&&((null==this.parse.stoppedAt||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext((()=>{for(;!(tree=this.parse.advance()););})),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(f){let prev=currentContext;currentContext=this;try{return f()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments:fragments,tree:tree,treeLen:treeLen,viewport:viewport,skipped:skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(changes.iterChangedRanges(((fromA,toA,fromB,toB)=>ranges.push({fromA:fromA,toA:toA,fromB:fromB,toB:toB}))),fragments=TreeFragment.applyChanges(fragments,ranges),tree=Tree.empty,treeLen=0,viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);fromviewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return!(this.skipped.length>=startLen)&&(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from:from,to:to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&0==frags[0].from&&frags[0].to>=upto}static get(){return currentContext}}function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}class LanguageState{constructor(context){this.context=context,this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new LanguageState(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new LanguageState(parseState)}}Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=callback=>{let timeout=setTimeout((()=>callback()),500);return()=>clearTimeout(timeout)};"undefined"!=typeof requestIdleCallback&&(requestIdle=callback=>{let idle=-1,timeout=setTimeout((()=>{idle=requestIdleCallback(callback,{timeout:400})}),100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)});const isInputPending="undefined"!=typeof navigator&&(null===(_a=navigator.scheduling)||void 0===_a?void 0:_a.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state:state}=this.view,field=state.field(Language.state);field.tree==field.context.tree&&field.context.isDone(state.doc.length)||(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now=Date.now();if(this.chunkEndvpTo+1e3,done=field.context.work((()=>isInputPending&&isInputPending()||Date.now()>endTime),vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&(!done||viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then((()=>this.scheduleWork())).catch((err=>logException(this.view.state,err))).then((()=>this.workScheduled--)),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine:languages=>languages.length?languages[0]:null,enables:language=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language],(state=>{let lang=state.facet(language);return lang&&lang.name?{"data-language":lang.name}:{}}))]});class LanguageSupport{constructor(language){let support=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.language=language,this.support=support,this.extension=[language,support]}}const indentService=Facet.define(),indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";let unit=values[0];if(!unit||/\S/.test(unit)||Array.from(unit).some((e=>e!=unit[0])))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return unit}});function getIndentUnit(state){let unit=state.facet(indentUnit);return 9==unit.charCodeAt(0)?state.tabSize*unit.length:unit.length}function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if("\t"==ch){for(;cols>=ts;)result+="\t",cols-=ts;ch=" "}for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:{};this.state=state,this.options=options,this.unit=getIndentUnit(state)}lineAt(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,line=this.state.doc.lineAt(pos),{simulateBreak:simulateBreak,simulateDoubleBreak:simulateDoubleBreak}=this.options;return null!=simulateBreak&&simulateBreak>=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak1&&void 0!==arguments[1]?arguments[1]:1;if(this.options.simulateDoubleBreak&&pos==this.options.simulateBreak)return"";let{text:text,from:from}=this.lineAt(pos,bias);return text.slice(pos-from,Math.min(text.length,pos+100-from))}column(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,{text:text,from:from}=this.lineAt(pos,bias),result=this.countColumn(text,pos-from),override=this.options.overrideIndentation?this.options.overrideIndentation(from):-1;return override>-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line){let pos=arguments.length>1&&void 0!==arguments[1]?arguments[1]:line.length;return countColumn(line,this.state.tabSize,pos)}lineIndent(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,{text:text,from:from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const indentNodeProp=new NodeProp;function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let close,first=tree.firstChild;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last=tree.lastChild,closed=last&&close.indexOf(last.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!function(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}(cx)?last.from:void 0)}return null==tree.parent?topIndent:null}function indentFrom(node,pos,base){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base,pos,node))}return null}function topIndent(){return 0}class TreeIndentContext extends IndentContext{constructor(base,pos,node){super(base.state,base.options),this.base=base,this.pos=pos,this.node=node}static create(base,pos,node){return new TreeIndentContext(base,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;atBreak.parent&&atBreak.parent.from==atBreak.from;)atBreak=atBreak.parent;if(isParent(atBreak,node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}}function isParent(parent,of){for(let cur=of;cur;cur=cur.parent)if(parent==cur)return!0;return!1}function delimitedStrategy(context,align,units,closing,closedAt){let after=context.textAfter,space=after.match(/^\s*/)[0].length,closed=closing&&after.slice(space,space+closing.length)==closing||closedAt==context.pos+space,aligned=align?function(context){let tree=context.node,openToken=tree.childAfter(tree.from),last=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),lineEnd=null==sim||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last)return null;if(!next.type.isSkipped)return next.from0&&void 0!==arguments[0]?arguments[0]:{};return context=>{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last=node.lastChild;return first&&first.toend)continue;if(found&&cur.from=start&&value.to>end&&(found=value)}}return found}(state,lineStart,lineEnd)}function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from:from,to:to}}const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head:head}of view.state.selection.ranges)lines.some((l=>l.from<=head&&l.to>=head))||lines.push(view.lineBlockAt(head));return lines}const foldState=StateField.define({create:()=>Decoration.none,update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):e.is(unfoldEffect)&&(folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to}));if(tr.selection){let onSelection=!1,{head:head}=tr.selection.main;folded.between(head,head,((a,b)=>{ahead&&(onSelection=!0)})),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,((from,to)=>{ranges.push(from,to)})),ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i{(!found||found.from>from)&&(found={from:from,to:to})})),found}function foldExists(folded,from,to){let found=!1;return folded.between(from,from,((a,b)=>{a==from&&b==to&&(found=!0)})),found}function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}function announceFold(view,range){let fold=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of("".concat(view.state.phrase(fold?"Folded lines":"Unfolded lines")," ").concat(lineFrom," ").concat(view.state.phrase("to")," ").concat(lineTo,"."))}const foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1}},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects:effects}),effects.length>0}},{key:"Ctrl-Alt-[",run:view=>{let{state:state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,((from,to)=>{effects.push(unfoldEffect.of({from:from,to:to}))})),view.dispatch({effects:effects}),!0}}],defaultConfig={placeholderDOM:null,placeholderText:"…"},foldConfig=Facet.define({combine:values=>combineConfig(values,defaultConfig)});function codeFolding(config){let result=[foldState,baseTheme$1$2];return config&&result.push(foldConfig.of(config)),result}const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state:state}=view,conf=state.facet(foldConfig),onclick=event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()};if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class FoldMarker extends GutterMarker{constructor(config,open){super(),this.config=config,this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}}function foldGutter(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))&&(this.markers=this.buildMarkers(update.view))}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers:domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a;return(null===(_a=view.plugin(markers))||void 0===_a?void 0:_a.markers)||RangeSet.empty},initialSpacer:()=>new FoldMarker(fullConfig,!1),domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return!!range&&(view.dispatch({effects:foldEffect.of(range)}),!0)}})}),codeFolding()]}const baseTheme$1$2=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class HighlightStyle{constructor(specs,options){let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}this.specs=specs;const all="string"==typeof options.all?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map((style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))}))),{all:all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new HighlightStyle(specs,options||{})}}const highlighterFacet=Facet.define(),fallbackHighlighter=Facet.define({combine:values=>values.length?[values[0]]:null});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}function syntaxHighlighting(highlighter,options){let themeType,ext=[treeHighlighter];return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),(null==options?void 0:options.fallback)?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],(state=>state.facet(EditorView.darkTheme)==("dark"==themeType)?[highlighter]:[]))):ext.push(highlighterFacet.of(highlighter)),ext}const treeHighlighter=Prec.high(ViewPlugin.fromClass(class{constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length{builder.add(from,to,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))}),from,to);return builder.finish()}},{decorations:v=>v.decorations})),defaultHighlightStyle=HighlightStyle.define([{tag:tags$1.meta,color:"#404740"},{tag:tags$1.link,textDecoration:"underline"},{tag:tags$1.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags$1.emphasis,fontStyle:"italic"},{tag:tags$1.strong,fontWeight:"bold"},{tag:tags$1.strikethrough,textDecoration:"line-through"},{tag:tags$1.keyword,color:"#708"},{tag:[tags$1.atom,tags$1.bool,tags$1.url,tags$1.contentSeparator,tags$1.labelName],color:"#219"},{tag:[tags$1.literal,tags$1.inserted],color:"#164"},{tag:[tags$1.string,tags$1.deleted],color:"#a11"},{tag:[tags$1.regexp,tags$1.escape,tags$1.special(tags$1.string)],color:"#e40"},{tag:tags$1.definition(tags$1.variableName),color:"#00f"},{tag:tags$1.local(tags$1.variableName),color:"#30a"},{tag:[tags$1.typeName,tags$1.namespace],color:"#085"},{tag:tags$1.className,color:"#167"},{tag:[tags$1.special(tags$1.variableName),tags$1.macroName],color:"#256"},{tag:tags$1.definition(tags$1.propertyName),color:"#00c"},{tag:tags$1.comment,color:"#940"},{tag:tags$1.invalid,color:"#f00"}]),baseTheme$3=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),bracketMatchingConfig=Facet.define({combine:configs=>combineConfig(configs,{afterCursor:!0,brackets:"()[]{}",maxScanDistance:1e4,renderMatch:defaultRenderMatch})}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match){let decorations=[],mark=match.matched?matchingMark:nonmatchingMark;return decorations.push(mark.range(match.start.from,match.start.to)),match.end&&decorations.push(mark.range(match.end.from,match.end.to)),decorations}const bracketMatchingState=StateField.define({create:()=>Decoration.none,update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations=[],config=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match=matchBrackets(tr.state,range.head,-1,config)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config)||config.afterCursor&&(matchBrackets(tr.state,range.head,1,config)||range.headEditorView.decorations.from(f)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$3];function bracketMatching(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[bracketMatchingConfig.of(config),bracketMatchingUnique]}const bracketMatchingHandle=new NodeProp;function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(1==node.name.length){let index=brackets.indexOf(node.name);if(index>-1&&index%2==(dir<0?1:0))return[brackets[index+dir]]}return null}function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}function matchBrackets(state,pos,dir){let config=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},maxScanDistance=config.maxScanDistance||1e4,brackets=config.brackets||"()[]{}",tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from0?pos>=handle.from&&poshandle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur,handle,matches,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=null==parent?void 0:parent.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do{if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(0==depth&&matching.indexOf(cursor.type.name)>-1&&cursor.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(!(found<0||tree.resolveInner(basePos+pos,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(1==depth)return{start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags$1[part];value?"function"==typeof value?tag?tag=value(tag):warnForPart(part,"Modifier ".concat(part," used at start of tag")):tag?warnForPart(part,"Tag ".concat(part," used as modifier")):tag=value:warnForPart(part,"Unknown highlighting tag ".concat(part))}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name,props:[styleTags({[name]:tag})]});return typeArray.push(type),type.id}function command(f,option){return _ref9=>{let{state:state,dispatch:dispatch}=_ref9;if(state.readOnly)return!1;let tr=f(option,state);return!!tr&&(dispatch(state.update(tr)),!0)}}const toggleLineComment=command((function(option,state){let ranges=arguments.length>2&&void 0!==arguments[2]?arguments[2]:state.selection.ranges,lines=[],prevLine=-1;for(let{from:from,to:to}of ranges){let startI=lines.length,minIndent=1e9,token=getConfig(state,from).line;if(token){for(let pos=from;pos<=to;){let line=state.doc.lineAt(pos);if(line.from>prevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty=indent==line.length,comment=line.text.slice(indent,indent+token.length)==token?indent:-1;indentl.comment<0&&(!l.empty||l.single)))){let changes=[];for(let{line:line,token:token,indent:indent,empty:empty,single:single}of lines)!single&&empty||changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}if(1!=option&&lines.some((l=>l.comment>=0))){let changes=[];for(let{line:line,comment:comment,token:token}of lines)if(comment>=0){let from=line.from+comment,to=from+token.length;" "==line.text[to-line.from]&&to++,changes.push({from:from,to:to})}return{changes:changes}}return null}),0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command(((o,s)=>changeBlockComment(o,s,function(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last=ranges.length-1;last>=0&&ranges[last].to>fromLine.from?ranges[last].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}(s))),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}function findBlockComment(state,_ref10,from,to){let startText,endText,{open:open,close:close}=_ref10,textBefore=state.sliceDoc(from-50,from),textAfter=state.sliceDoc(to,to+50),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close)return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}};to-from<=100?startText=endText=state.sliceDoc(from,to):(startText=state.sliceDoc(from,from+50),endText=state.sliceDoc(to-50,to));let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}:null}function changeBlockComment(option,state){let ranges=arguments.length>2&&void 0!==arguments[2]?arguments[2]:state.selection.ranges,tokens=ranges.map((r=>getConfig(state,r.from).block));if(!tokens.every((c=>c)))return null;let comments=ranges.map(((r,i)=>findBlockComment(state,tokens[i],r.from,r.to)));if(2!=option&&!comments.every((c=>c)))return{changes:state.changes(ranges.map(((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}])))};if(1!=option&&comments.some((c=>c))){let changes=[];for(let comment,i=0;icombineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent)=>isAdjacent},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})});const historyField_=StateField.define({create:()=>HistoryState.empty,update(state,tr){let config=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(function(changes){let end=0;return changes.iterChangedRanges(((_,to)=>end=to)),end}(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=0==from?state.undone:state.done;return other=item?updateBranch(other,other.length,config.minDepth,item):addSelection(other,tr.startState.selection),new HistoryState(0==from?fromHist.rest:other,0==from?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if("full"!=isolate&&"before"!=isolate||(state=state.isolate()),!1===tr.annotation(Transaction.addToHistory))return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config.newGroupDelay)),"full"!=isolate&&"after"!=isolate||(state=state.isolate()),state},toJSON:value=>({done:value.done.map((e=>e.toJSON())),undone:value.undone.map((e=>e.toJSON()))}),fromJSON:json=>new HistoryState(json.done.map(HistEvent.fromJSON),json.undone.map(HistEvent.fromJSON))});function history(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[historyField_,historyConfig.of(config),EditorView.domEventHandlers({beforeinput(e,view){let command="historyUndo"==e.inputType?undo:"historyRedo"==e.inputType?redo:null;return!!command&&(e.preventDefault(),command(view))}})]}function cmd(side,selection){return function(_ref11){let{state:state,dispatch:dispatch}=_ref11;if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return!!tr&&(dispatch(tr),!0)}}const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0);class HistEvent{constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new HistEvent(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a,_b,_c;return{changes:null===(_a=this.changes)||void 0===_a?void 0:_a.toJSON(),mapped:null===(_b=this.mapped)||void 0===_b?void 0:_b.toJSON(),startSelection:null===(_c=this.startSelection)||void 0===_c?void 0:_c.toJSON(),selectionsAfter:this.selectionsAfter.map((s=>s.toJSON()))}}static fromJSON(json){return new HistEvent(json.changes&&ChangeSet.fromJSON(json.changes),[],json.mapped&&ChangeDesc.fromJSON(json.mapped),json.startSelection&&EditorSelection.fromJSON(json.startSelection),json.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none$1;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new HistEvent(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none$1)}static selection(selections){return new HistEvent(void 0,none$1,void 0,void 0,selections)}}function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}function conc(a,b){return a.length?b.length?a.concat(b):a:b}const none$1=[];function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-200));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}return[HistEvent.selection([selection])]}function popSelection(branch){let last=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last.setSelAfter(last.selectionsAfter.slice(0,last.selectionsAfter.length-1)),newBranch}function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none$1;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none$1}function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map((s=>s.map(mapping))):none$1,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}const joinableUserEvent=/^(input\.type|delete)($|\.)/;class HistoryState{constructor(done,undone){let prevTime=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,prevUserEvent=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new HistoryState(this.done,this.undone):this}addChanges(event,time,userEvent,config,tr){let done=this.done,lastEvent=done[done.length-1];return done=lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTimeranges.push(f,t))),b.iterChangedRanges(((_f,_t,f,t)=>{for(let i=0;i=from&&f<=to&&(isAdjacent=!0)}})),isAdjacent}(lastEvent.changes,event.changes))||"input.type.compose"==userEvent)?updateBranch(done,done.length-1,config.minDepth,new HistEvent(event.changes.compose(lastEvent.changes),conc(event.effects,lastEvent.effects),lastEvent.mapped,lastEvent.startSelection,none$1)):updateBranch(done,done.length,config.minDepth,event),new HistoryState(done,none$1,time,userEvent)}addSelection(selection,time,userEvent,newGroupDelay){let last=this.done.length?this.done[this.done.length-1].selectionsAfter:none$1;return last.length>0&&time-this.prevTimer.empty!=b.ranges[i].empty)).length)?this:new HistoryState(addSelection(this.done,selection),this.undone,time,userEvent);var a,b}addMapping(mapping){return new HistoryState(addMappingToBranch(this.done,mapping),addMappingToBranch(this.undone,mapping),this.prevTime,this.prevUserEvent)}pop(side,state,selection){let branch=0==side?this.done:this.undone;if(0==branch.length)return null;let event=branch[branch.length-1];if(selection&&event.selectionsAfter.length)return state.update({selection:event.selectionsAfter[event.selectionsAfter.length-1],annotations:fromHistory.of({side:side,rest:popSelection(branch)}),userEvent:0==side?"select.undo":"select.redo",scrollIntoView:!0});if(event.changes){let rest=1==branch.length?none$1:branch.slice(0,branch.length-1);return event.mapped&&(rest=addMappingToBranch(rest,event.mapped)),state.update({changes:event.changes,selection:event.startSelection,effects:event.effects,annotations:fromHistory.of({side:side,rest:rest}),filter:!1,userEvent:0==side?"undo":"redo",scrollIntoView:!0})}return null}}HistoryState.empty=new HistoryState(none$1,none$1);const historyKeymap=[{key:"Mod-z",run:undo,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:redo,preventDefault:!0},{linux:"Ctrl-Shift-z",run:redo,preventDefault:!0},{key:"Mod-u",run:undoSelection,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:redoSelection,preventDefault:!0}];function updateSel(sel,by){return EditorSelection.create(sel.ranges.map(by),sel.mainIndex)}function setSel(state,selection){return state.update({selection:selection,scrollIntoView:!0,userEvent:"select"})}function moveSel(_ref12,how){let{state:state,dispatch:dispatch}=_ref12,selection=updateSel(state.selection,how);return!selection.eq(state.selection)&&(dispatch(setSel(state,selection)),!0)}function rangeEnd(range,forward){return EditorSelection.cursor(forward?range.to:range.from)}function cursorByChar(view,forward){return moveSel(view,(range=>range.empty?view.moveByChar(range,forward):rangeEnd(range,forward)))}function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}const cursorCharLeft=view=>cursorByChar(view,!ltrAtCursor(view)),cursorCharRight=view=>cursorByChar(view,ltrAtCursor(view));function cursorByGroup(view,forward){return moveSel(view,(range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward)))}function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}function moveBySyntax(state,start,forward){let match,newPos,pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}return newPos=pos.type.prop(bracketProp)&&(match=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match.matched?forward?match.end.to:match.end.from:forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}function cursorByLine(view,forward){return moveSel(view,(range=>{if(!range.empty)return rangeEnd(range,forward);let moved=view.moveVertically(range,forward);return moved.head!=range.head?moved:view.moveToLineBoundary(range,forward)}))}const cursorLineUp=view=>cursorByLine(view,!1),cursorLineDown=view=>cursorByLine(view,!0);function pageInfo(view){let height,selfScroll=view.scrollDOM.clientHeightrange.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward)));if(selection.eq(state.selection))return!1;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottomcursorByPage(view,!1),cursorPageDown=view=>cursorByPage(view,!0);function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved=view.moveToLineBoundary(start,forward);if(moved.head==start.head&&moved.head!=(forward?line.to:line.from)&&(moved=view.moveToLineBoundary(start,forward,!1)),!forward&&moved.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved=EditorSelection.cursor(line.from+space))}return moved}function extendSel(view,how){let selection=updateSel(view.state.selection,(range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)}));return!selection.eq(view.state.selection)&&(view.dispatch(setSel(view.state,selection)),!0)}function selectByChar(view,forward){return extendSel(view,(range=>view.moveByChar(range,forward)))}const selectCharLeft=view=>selectByChar(view,!ltrAtCursor(view)),selectCharRight=view=>selectByChar(view,ltrAtCursor(view));function selectByGroup(view,forward){return extendSel(view,(range=>view.moveByGroup(range,forward)))}function selectByLine(view,forward){return extendSel(view,(range=>view.moveVertically(range,forward)))}const selectLineUp=view=>selectByLine(view,!1),selectLineDown=view=>selectByLine(view,!0);function selectByPage(view,forward){return extendSel(view,(range=>view.moveVertically(range,forward,pageInfo(view).height)))}const selectPageUp=view=>selectByPage(view,!1),selectPageDown=view=>selectByPage(view,!0),cursorDocStart=_ref14=>{let{state:state,dispatch:dispatch}=_ref14;return dispatch(setSel(state,{anchor:0})),!0},cursorDocEnd=_ref15=>{let{state:state,dispatch:dispatch}=_ref15;return dispatch(setSel(state,{anchor:state.doc.length})),!0},selectDocStart=_ref16=>{let{state:state,dispatch:dispatch}=_ref16;return dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0},selectDocEnd=_ref17=>{let{state:state,dispatch:dispatch}=_ref17;return dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0};function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state:state}=target,changes=state.changeByRange((range=>{let{from:from,to:to}=range;if(from==to){let towards=by(from);towardsfrom&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range:range}:{changes:{from:from,to:to},range:EditorSelection.cursor(from)}}));return!changes.changes.empty&&(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:"delete.selection"==event?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map((f=>f(target))))ranges.between(pos,pos,((from,to)=>{frompos&&(pos=forward?to:from)}));return pos}const deleteByChar=(target,forward)=>deleteBy(target,(pos=>{let before,targetPos,{state:state}=target,line=state.doc.lineAt(pos);if(!forward&&pos>line.from&&posdeleteByChar(view,!1),deleteCharForward=view=>deleteByChar(view,!0),deleteByGroup=(target,forward)=>deleteBy(target,(start=>{let pos=start,{state:state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar);if(null!=cat&&nextCat!=cat)break;" "==nextChar&&pos==start||(cat=nextCat),pos=next}return pos})),deleteGroupBackward=target=>deleteByGroup(target,!1),deleteToLineEnd=view=>deleteBy(view,(pos=>{let lineEnd=view.lineBlockAt(pos).to;return pos=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to,prev.ranges.push(range)}else blocks.push({from:startLine.from,to:endLine.to,ranges:[range]});upto=endLine.number+1}return blocks}function moveLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:0==block.from)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1),size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}return!!changes.length&&(dispatch(state.update({changes:changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0)}function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes:changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return _ref30=>{let{state:state,dispatch:dispatch}=_ref30;if(state.readOnly)return!1;let changes=state.changeByRange((range=>{let{from:from,to:to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&function(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let closedBy,context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos);return before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from?{from:before.to,to:after.from}:null}(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(null==indent&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);line.number>atLine&&(range.empty||range.to>line.from)&&(f(line,changes,range),atLine=line.number),pos=line.to+1}let changeSet=state.changes(changes);return{changes:changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}}))}const standardKeymap=[{key:"ArrowLeft",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:view=>cursorByGroup(view,!ltrAtCursor(view)),shift:view=>selectByGroup(view,!ltrAtCursor(view)),preventDefault:!0},{mac:"Cmd-ArrowLeft",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!ltrAtCursor(view)))),preventDefault:!0},{key:"ArrowRight",run:cursorCharRight,shift:selectCharRight,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:view=>cursorByGroup(view,ltrAtCursor(view)),shift:view=>selectByGroup(view,ltrAtCursor(view)),preventDefault:!0},{mac:"Cmd-ArrowRight",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,ltrAtCursor(view)))),preventDefault:!0},{key:"ArrowUp",run:cursorLineUp,shift:selectLineUp,preventDefault:!0},{mac:"Cmd-ArrowUp",run:cursorDocStart,shift:selectDocStart},{mac:"Ctrl-ArrowUp",run:cursorPageUp,shift:selectPageUp},{key:"ArrowDown",run:cursorLineDown,shift:selectLineDown,preventDefault:!0},{mac:"Cmd-ArrowDown",run:cursorDocEnd,shift:selectDocEnd},{mac:"Ctrl-ArrowDown",run:cursorPageDown,shift:selectPageDown},{key:"PageUp",run:cursorPageUp,shift:selectPageUp},{key:"PageDown",run:cursorPageDown,shift:selectPageDown},{key:"Home",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!1))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!1))),preventDefault:!0},{key:"Mod-Home",run:cursorDocStart,shift:selectDocStart},{key:"End",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!0))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!0))),preventDefault:!0},{key:"Mod-End",run:cursorDocEnd,shift:selectDocEnd},{key:"Enter",run:insertNewlineAndIndent},{key:"Mod-a",run:_ref18=>{let{state:state,dispatch:dispatch}=_ref18;return dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0}},{key:"Backspace",run:deleteCharBackward,shift:deleteCharBackward},{key:"Delete",run:deleteCharForward},{key:"Mod-Backspace",mac:"Alt-Backspace",run:deleteGroupBackward},{key:"Mod-Delete",mac:"Alt-Delete",run:target=>deleteByGroup(target,!0)},{mac:"Mod-Backspace",run:view=>deleteBy(view,(pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}))},{mac:"Mod-Delete",run:deleteToLineEnd}].concat([{key:"Ctrl-b",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Ctrl-f",run:cursorCharRight,shift:selectCharRight},{key:"Ctrl-p",run:cursorLineUp,shift:selectLineUp},{key:"Ctrl-n",run:cursorLineDown,shift:selectLineDown},{key:"Ctrl-a",run:view=>moveSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1))),shift:view=>extendSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)))},{key:"Ctrl-e",run:view=>moveSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1))),shift:view=>extendSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)))},{key:"Ctrl-d",run:deleteCharForward},{key:"Ctrl-h",run:deleteCharBackward},{key:"Ctrl-k",run:deleteToLineEnd},{key:"Ctrl-Alt-h",run:deleteGroupBackward},{key:"Ctrl-o",run:_ref23=>{let{state:state,dispatch:dispatch}=_ref23;if(state.readOnly)return!1;let changes=state.changeByRange((range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)})));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0}},{key:"Ctrl-t",run:_ref24=>{let{state:state,dispatch:dispatch}=_ref24;if(state.readOnly)return!1;let changes=state.changeByRange((range=>{if(!range.empty||0==range.from||range.from==state.doc.length)return{range:range};let pos=range.from,line=state.doc.lineAt(pos),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from:from,to:to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}}));return!changes.changes.empty&&(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)}},{key:"Ctrl-v",run:cursorPageDown}].map((b=>({mac:b.key,run:b.run,shift:b.shift})))),defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:view=>moveSel(view,(range=>moveBySyntax(view.state,range,!ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveBySyntax(view.state,range,!ltrAtCursor(view))))},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:view=>moveSel(view,(range=>moveBySyntax(view.state,range,ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveBySyntax(view.state,range,ltrAtCursor(view))))},{key:"Alt-ArrowUp",run:_ref25=>{let{state:state,dispatch:dispatch}=_ref25;return moveLine(state,dispatch,!1)}},{key:"Shift-Alt-ArrowUp",run:_ref27=>{let{state:state,dispatch:dispatch}=_ref27;return copyLine(state,dispatch,!1)}},{key:"Alt-ArrowDown",run:_ref26=>{let{state:state,dispatch:dispatch}=_ref26;return moveLine(state,dispatch,!0)}},{key:"Shift-Alt-ArrowDown",run:_ref28=>{let{state:state,dispatch:dispatch}=_ref28;return copyLine(state,dispatch,!0)}},{key:"Escape",run:_ref22=>{let{state:state,dispatch:dispatch}=_ref22,cur=state.selection,selection=null;return cur.ranges.length>1?selection=EditorSelection.create([cur.main]):cur.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur.main.head)])),!!selection&&(dispatch(setSel(state,selection)),!0)}},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:_ref19=>{let{state:state,dispatch:dispatch}=_ref19,ranges=selectedLineBlocks(state).map((_ref20=>{let{from:from,to:to}=_ref20;return EditorSelection.range(from,Math.min(to+1,state.doc.length))}));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0}},{key:"Mod-i",run:_ref21=>{let{state:state,dispatch:dispatch}=_ref21,selection=updateSel(state.selection,(range=>{var _a;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from=range.to||context.to>range.to&&context.from<=range.from)&&(null===(_a=context.parent)||void 0===_a?void 0:_a.parent);)context=context.parent;return EditorSelection.range(context.to,context.from)}));return dispatch(setSel(state,selection)),!0},preventDefault:!0},{key:"Mod-[",run:_ref33=>{let{state:state,dispatch:dispatch}=_ref33;return!state.readOnly&&(dispatch(state.update(changeBySelectedLine(state,((line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep{let{state:state,dispatch:dispatch}=_ref32;return!state.readOnly&&(dispatch(state.update(changeBySelectedLine(state,((line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})})),{userEvent:"input.indent"})),!0)}},{key:"Mod-Alt-\\",run:_ref31=>{let{state:state,dispatch:dispatch}=_ref31;if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return null==found?-1:found}}),changes=changeBySelectedLine(state,((line,changes,range)=>{let indent=getIndentation(context,line.from);if(null==indent)return;/\S/.test(line.text)||(indent=0);let cur=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur!=norm||range.from{if(view.state.readOnly)return!1;let{state:state}=view,changes=state.changes(selectedLineBlocks(state).map((_ref29=>{let{from:from,to:to}=_ref29;return from>0?from--:toview.moveVertically(range,!0))).map(changes);return view.dispatch({changes:changes,selection:selection,scrollIntoView:!0,userEvent:"delete.line"}),!0}},{key:"Shift-Mod-\\",run:_ref13=>{let{state:state,dispatch:dispatch}=_ref13;return function(state,dispatch,extend){let found=!1,selection=updateSel(state.selection,(range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.head{let{state:state}=target,line=state.doc.lineAt(state.selection.main.from),config=getConfig(target.state,line.from);return config.line?toggleLineComment(target):!!config.block&&toggleBlockCommentByLine(target)}},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap);function crelt(){var elt=arguments[0];"string"==typeof elt&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&"object"==typeof next&&null==next.nodeType&&!Array.isArray(next)){for(var name in next)if(Object.prototype.hasOwnProperty.call(next,name)){var value=next[name];"string"==typeof value?elt.setAttribute(name,value):null!=value&&(elt[name]=value)}i++}for(;ix.normalize("NFKD"):x=>x;class SearchCursor{constructor(text,query){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3&&void 0!==arguments[3]?arguments[3]:text.length,normalize=arguments.length>4?arguments[4]:void 0,test=arguments.length>5?arguments[5]:void 0;this.test=test,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=text.iterRange(from,to),this.bufferStart=from,this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize,this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match=this.match(code,pos);if(match)return this.value=match,this;if(i==norm.length-1)break;pos==start&&i3&&void 0!==arguments[3]?arguments[3]:0,to=arguments.length>4&&void 0!==arguments[4]?arguments[4]:text.length;if(this.text=text,this.to=to,this.curLine="",this.done=!1,this.value=empty,/\\[sWDnr]|\n|\r|\[\^/.test(query))return new MultilineRegExpCursor(text,query,options,from,to);this.re=new RegExp(query,baseFlags+((null==options?void 0:options.ignoreCase)?"i":"")),this.test=null==options?void 0:options.test,this.iter=text.iter();let startLine=text.lineAt(from);this.curLineStart=startLine.from,this.matchPos=toCharEnd(text,from),this.getLine(this.curLineStart)}getLine(skip){this.iter.next(skip),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off=this.matchPos-this.curLineStart;;){this.re.lastIndex=off;let match=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match){let from=this.curLineStart+match.index,to=from+match[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(fromthis.value.to)&&(!this.test||this.test(from,to,match)))return this.value={from:from,to:to,match:match},this;off=this.matchPos-this.curLineStart}else{if(!(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new FlattenedDoc(from,doc.sliceString(from,to));return flattened.set(doc,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text:text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off=this.re.lastIndex=this.matchPos-this.flat.from,match=this.re.exec(this.flat.text);if(match&&!match[0]&&match.index==off&&(this.re.lastIndex=off+1,match=this.re.exec(this.flat.text)),match){let from=this.flat.from+match.index,to=from+match[0].length;if((this.flat.to>=this.to||match.index+match[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match)))return this.value={from:from,to:to,match:match},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+2*this.flat.text.length))}}}function toCharEnd(text,pos){if(pos>=text.length)return pos;let next,line=text.lineAt(pos);for(;pos=56320&&next<57344;)pos++;return pos}function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"});function go(){let match=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match)return;let{state:state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*("-"==sign?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*("-"==sign?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line)));view.dispatch({effects:dialogEffect.of(!1),selection:EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length))),scrollIntoView:!0}),view.focus()}return{dom:crelt("form",{class:"cm-gotoLine",onkeydown:event=>{27==event.keyCode?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):13==event.keyCode&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")))}}"undefined"!=typeof Symbol&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});const dialogEffect=StateEffect.define(),dialogField=StateField.define({create:()=>!0,update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f=>showPanel.from(f,(val=>val?createLineDialog:null))}),baseTheme$1$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine:options=>combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return!(0!=from&&check(state.sliceDoc(from-1,from))==CharCategory.Word||to!=state.doc.length&&check(state.sliceDoc(to,to+1))==CharCategory.Word)}const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state:state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let query,range=sel.main,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!insideWordBoundaries(check,state,range.from,range.to)||!function(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}(check,state,range.from,range.to))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from:from,to:to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const searchConfigFacet=Facet.define({combine:configs=>combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})});class SearchQuery{constructor(config){this.search=config.search,this.caseSensitive=!!config.caseSensitive,this.literal=!!config.literal,this.regexp=!!config.regexp,this.replace=config.replace||"",this.valid=!!this.search&&(!this.regexp||function(source){try{return new RegExp(source,baseFlags),!0}catch(_a){return!1}}(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,((_,ch)=>"n"==ch?"\n":"r"==ch?"\r":"t"==ch?"\t":"\\"))}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state){let from=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,to=arguments.length>2?arguments[2]:void 0,st=state.doc?state:EditorState.create({doc:state});return null==to&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}}class QueryType{constructor(spec){this.spec=spec}}function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?function(doc,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add(cursor.value.from,cursor.value.to)}}function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?(categorizer=state.charCategorizer(state.selection.main.head),(_from,_to,match)=>!match[0].length||(categorizer(charBefore(match.input,match.index))!=CharCategory.Word||categorizer(charAfter(match.input,match.index))!=CharCategory.Word)&&(categorizer(charAfter(match.input,match.index+match[0].length))!=CharCategory.Word||categorizer(charBefore(match.input,match.index+match[0].length))!=CharCategory.Word)):void 0},from,to);var categorizer}function charBefore(str,index){return str.slice(findClusterBreak(str,index,!1),index)}function charAfter(str,index){return str.slice(index,findClusterBreak(str,index))}class RegExpQuery extends QueryType{nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-1e4*size),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!cursor.next().done;)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,((m,i)=>"$"==i?"$":"&"==i?result.match[0]:"0"!=i&&+i=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add(cursor.value.from,cursor.value.to)}}const setSearchQuery=StateEffect.define(),togglePanel$1=StateEffect.define(),searchState=StateField.define({create:state=>new SearchState(defaultQuery(state).create(),null),update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel$1)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f=>showPanel.from(f,(val=>val.panel))});class SearchState{constructor(query,panel){this.query=query,this.panel=panel}}const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)&&(this.decorations=this.highlight(state))}highlight(_ref36){let{query:query,panel:panel}=_ref36;if(!panel||!query.spec.valid)return Decoration.none;let{view:view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l=ranges.length;iranges[i+1].from-500;)to=ranges[++i].to;query.highlight(view.state,from,to,((from,to)=>{let selected=view.state.selection.ranges.some((r=>r.from==from&&r.to==to));builder.add(from,to,selected?selectedMatchMark:matchMark)}))}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}const findNext=searchCommand(((view,_ref37)=>{let{query:query}=_ref37,{to:to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config=view.state.facet(searchConfigFacet);return view.dispatch({selection:selection,effects:[announceMatch(view,next),config.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0})),findPrevious=searchCommand(((view,_ref38)=>{let{query:query}=_ref38,{state:state}=view,{from:from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config=view.state.facet(searchConfigFacet);return view.dispatch({selection:selection,effects:[announceMatch(view,prev),config.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0})),selectMatches=searchCommand(((view,_ref39)=>{let{query:query}=_ref39,ranges=query.matchAll(view.state,1e3);return!(!ranges||!ranges.length)&&(view.dispatch({selection:EditorSelection.create(ranges.map((r=>EditorSelection.range(r.from,r.to)))),userEvent:"select.search.matches"}),!0)})),replaceNext=searchCommand(((view,_ref41)=>{let{query:query}=_ref41,{state:state}=view,{from:from,to:to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let selection,replacement,changes=[],effects=[];if(next.from==from&&next.to==to&&(replacement=state.toText(query.getReplacement(next)),changes.push({from:next.from,to:next.to,insert:replacement}),next=query.nextMatch(state,next.from,next.to),effects.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off=0==changes.length||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off,next.to-off),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes:changes,selection:selection,effects:effects,userEvent:"input.replace"}),!0})),replaceAll=searchCommand(((view,_ref42)=>{let{query:query}=_ref42;if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map((match=>{let{from:from,to:to}=match;return{from:from,to:to,insert:query.getReplacement(match)}}));if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes:changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0}));function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}function defaultQuery(state,fallback){var _a,_b,_c,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config=state.facet(searchConfigFacet);return new SearchQuery({search:(null!==(_a=null==fallback?void 0:fallback.literal)&&void 0!==_a?_a:config.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:null!==(_b=null==fallback?void 0:fallback.caseSensitive)&&void 0!==_b?_b:config.caseSensitive,literal:null!==(_c=null==fallback?void 0:fallback.literal)&&void 0!==_c?_c:config.literal,regexp:null!==(_d=null==fallback?void 0:fallback.regexp)&&void 0!==_d?_d:config.regexp,wholeWord:null!==(_e=null==fallback?void 0:fallback.wholeWord)&&void 0!==_e?_e:config.wholeWord})}function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}const openSearchPanel=view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel$1.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},closeSearchPanel=view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel$1.of(!1)}),!0},searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:_ref40=>{let{state:state,dispatch:dispatch}=_ref40,sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from:from,to:to}=sel.main,ranges=[],main=0;for(let cur=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur.next().done;){if(ranges.length>1e3)return!1;cur.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur.value.from,cur.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0}},{key:"Alt-g",run:view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];null==view.state.field(dialogField,!1)&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1$1])),view.dispatch({effects:effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0}},{key:"Mod-d",run:_ref35=>{let{state:state,dispatch:dispatch}=_ref35,{ranges:ranges}=state.selection;if(ranges.some((sel=>sel.from===sel.to)))return(_ref34=>{let{state:state,dispatch:dispatch}=_ref34,{selection:selection}=state,newSel=EditorSelection.create(selection.ranges.map((range=>state.wordAt(range.head)||EditorSelection.cursor(range.head))),selection.mainIndex);return!newSel.eq(selection)&&(dispatch(state.update({selection:newSel})),!0)})({state:state,dispatch:dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some((r=>state.sliceDoc(r.from,r.to)!=searchedText)))return!1;let range=function(state,query){let{main:main,ranges:ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;){if(cursor.next(),!cursor.done){if(cycled&&ranges.some((r=>r.from==cursor.value.from)))continue;if(fullWord){let word=state.wordAt(cursor.value.from);if(!word||word.from!=cursor.value.from||word.to!=cursor.value.to)continue}return cursor.value}if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}}(state,searchedText);return!!range&&(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0)},preventDefault:!0}];class SearchPanel{constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;function button(name,onclick,content){return crelt("button",{class:"cm-button",name:name,onclick:onclick,type:"button"},content)}this.commit=this.commit.bind(this),this.searchField=crelt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=crelt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit}),this.dom=crelt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",(()=>findNext(view)),[phrase(view,"next")]),button("prev",(()=>findPrevious(view)),[phrase(view,"previous")]),button("select",(()=>selectMatches(view)),[phrase(view,"all")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",(()=>replaceNext(view)),[phrase(view,"replace")]),button("replaceAll",(()=>replaceAll(view)),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["×"])])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){var view,event,scope;view=this.view,event=e,scope="search-panel",runHandlers(getKeymap(view.state),event,view,scope)?e.preventDefault():13==e.keyCode&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):13==e.keyCode&&e.target==this.replaceField&&(e.preventDefault(),replaceNext(this.view))}update(update){for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setSearchQuery)&&!effect.value.eq(this.query)&&this.setQuery(effect.value)}setQuery(query){this.query=query,this.searchField.value=query.search,this.replaceField.value=query.replace,this.caseField.checked=query.caseSensitive,this.reField.checked=query.regexp,this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}}function phrase(view,phrase){return view.state.phrase(phrase)}const Break=/[\s\.,:;?!]/;function announceMatch(view,_ref43){let{from:from,to:to}=_ref43,line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-30),end=Math.min(lineEnd,to+30),text=view.state.sliceDoc(start,end);if(start!=line.from)for(let i=0;i<30;i++)if(!Break.test(text[i+1])&&Break.test(text[i])){text=text.slice(i);break}if(end!=lineEnd)for(let i=text.length-1;i>text.length-30;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}return EditorView.announce.of("".concat(view.state.phrase("current match"),". ").concat(text," ").concat(view.state.phrase("on line")," ").concat(line.number,"."))}const baseTheme$2=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme$2];class CompletionContext{constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types.indexOf(token.name)<0;)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return null==this.abortListeners}addEventListener(type,listener){"abort"==type&&this.abortListeners&&this.abortListeners.push(listener)}}function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),"[".concat(words?"\\w":"").concat(flat.replace(/[^\w\s]/g,"\\$&"),"]")}function completeFromList(list){let options=list.map((o=>"string"==typeof o?{label:o}:o)),[validFor,match]=options.every((o=>/^\w+$/.test(o.label)))?[/\w*$/,/\w+$/]:function(options){let first=Object.create(null),rest=Object.create(null);for(let{label:label}of options){first[label[0]]=!0;for(let i=1;i{let token=context.matchBefore(match);return token||context.explicit?{from:token?token.from:context.pos,options:options,validFor:validFor}:null}}function ifNotIn(nodes,source){return context=>{for(let pos=syntaxTree(context.state).resolveInner(context.pos,-1);pos;pos=pos.parent){if(nodes.indexOf(pos.name)>-1)return null;if(pos.type.isTop)break}return source(context)}}class Option{constructor(completion,source,match,score){this.completion=completion,this.source=source,this.match=match,this.score=score}}function cur(state){return state.selection.main.from}function ensureAnchor(expr,start){var _a;let{source:source}=expr,addStart=start&&"^"!=source[0],addEnd="$"!=source[source.length-1];return addStart||addEnd?new RegExp("".concat(addStart?"^":"","(?:").concat(source,")").concat(addEnd?"$":""),null!==(_a=expr.flags)&&void 0!==_a?_a:expr.ignoreCase?"i":""):expr}const pickedCompletion=Annotation.define();const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define();class FuzzyMatcher{constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||1==type&&hasLower||0==prevType&&0!=type)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&0==byWord[0]&&wordAdjacent?this.result((byWordFolded?-200:0)-100,byWord,word):adjacentTo==len&&0==adjacentStart?[-200-word.length+(adjacentEnd==word.length?0:-100),0,adjacentEnd]:direct>-1?[-700-word.length,direct,direct+this.pattern.length]:adjacentTo==len?[-900-word.length,adjacentStart,adjacentEnd]:byWordTo==len?this.result((byWordFolded?-200:0)-100-700+(wordAdjacent?0:-1100),byWord,word):2==chars.length?null:this.result((any[0]?-700:0)-200-1100,any,word)}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i>1&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return result}}const completionConfig=Facet.define({combine:configs=>combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,tooltipClass:(a,b)=>c=>joinClass(a(c),b(c)),optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})});function joinClass(a,b){return a?b?a+" "+b:a:b}function defaultPositionInfo(view,list,option,info,space){let offset,maxWidth,rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft=infoHeight||spaceBelow>list.top?offset=option.bottom-list.top:(side="bottom",offset=list.bottom-option.top)}return{style:"".concat(side,": ").concat(offset,"px; max-width: ").concat(maxWidth,"px"),class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off=Math.floor(selected/max);return{from:off*max,to:(off+1)*max}}let off=Math.floor((total-selected)/max);return{from:total-(off+1)*max,to:total-off*max}}class CompletionTooltip{constructor(view,stateField,applyCompletion){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:pos=>this.placeInfo(pos),key:this},this.space=null,this.currentClass="";let cState=view.state.field(stateField),{options:options,selected:selected}=cState.open,config=view.state.facet(completionConfig);this.optionContent=function(config){let content=config.addToOptions.slice();return config.icons&&content.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map((cls=>"cm-completionIcon-"+cls))),icon.setAttribute("aria-hidden","true"),icon},position:20}),content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label:label}=completion,off=0;for(let j=1;joff&&labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off=to}return offa.position-b.position)).map((a=>a.render))}(config),this.optionClass=config.optionClass,this.tooltipClass=config.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",(e=>{for(let match,dom=e.target;dom&&dom!=this.dom;dom=dom.parentNode)if("LI"==dom.nodeName&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})})),this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))}mount(){this.updateSel()}update(update){var _a,_b,_c;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);this.updateTooltipClass(update.state),cState!=prevState&&(this.updateSel(),(null===(_a=cState.open)||void 0===_a?void 0:_a.disabled)!=(null===(_b=prevState.open)||void 0===_b?void 0:_b.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!(null===(_c=cState.open)||void 0===_c?void 0:_c.disabled)))}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if((open.selected>-1&&open.selected=this.range.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion:completion}=open.options[open.selected],{info:info}=completion;if(!info)return;let infoResult="string"==typeof info?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then((obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)})).catch((e=>logException(this.view.state,e,"completion info"))):this.addInfoPane(infoResult,completion)}}addInfoPane(content,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",null!=content.nodeType)wrap.appendChild(content),this.infoDestroy=null;else{let{dom:dom,destroy:destroy}=content;wrap.appendChild(dom),this.infoDestroy=destroy||null}this.dom.appendChild(wrap),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++)"LI"==opt.nodeName&&opt.id?i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected"):i--;return set&&function(container,element){let parent=container.getBoundingClientRect(),self=element.getBoundingClientRect();self.topparent.bottom&&(container.scrollTop+=self.bottom-parent.bottom)}(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottomrange.from||0==range.from))if(curSection=name,"string"!=typeof section&§ion.header)ul.appendChild(section.header(section));else{ul.appendChild(document.createElement("completion-section")).textContent=name}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.tonew CompletionTooltip(view,stateField,applyCompletion)}function score(option){return 100*(option.boost||0)+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0)}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected,disabled){this.options=options,this.attrs=attrs,this.tooltip=tooltip,this.timestamp=timestamp,this.selected=selected,this.disabled=disabled}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=function(active,state){let options=[],sections=null,addOption=option=>{options.push(option);let{section:section}=option.completion;if(section){sections||(sections=[]);let name="string"==typeof section?section:section.name;sections.some((s=>s.name==name))||sections.push("string"==typeof section?{name:name}:section)}};for(let a of active)if(a.hasResult())if(!1===a.result.filter){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-options.length];if(getMatch)for(let n of getMatch(option))match.push(n);addOption(new Option(option,a.source,match,match[0]))}}else{let match,matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option of a.result.options)(match=matcher.match(option.label))&&addOption(new Option(option,a.source,match,match[0]+(option.boost||0)))}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=(a,b)=>{var _a,_b;return(null!==(_a=a.rank)&&void 0!==_a?_a:1e9)-(null!==(_b=b.rank)&&void 0!==_b?_b:1e9)||(a.nameb.score-a.score||compare(a.completion,b.completion)))){let cur=opt.completion;!prev||prev.label!=cur.label||prev.detail!=cur.detail||null!=prev.type&&null!=cur.type&&prev.type!=cur.type||prev.apply!=cur.apply||prev.boost!=cur.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}(active,state);if(!options.length)return prev&&active.some((a=>1==a.state))?new CompletionDialog(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&-1!=prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;ib.hasResult()?Math.min(a,b.from):a),1e8),create:completionTooltip(completionState,applyCompletion),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}}class CompletionState{constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(2e6*Math.random()).toString(36),null)}update(tr){let{state:state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map((source=>(this.active.find((s=>s.source==source))||new ActiveSource(source,this.active.some((a=>0!=a.state))?1:0)).update(tr,conf)));active.length==this.active.length&&active.every(((a,i)=>a==this.active[i]))&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some((a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to)))||!function(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA1==a.state))&&(open=null),!open&&active.every((a=>1!=a.state))&&active.some((a=>a.hasResult()))&&(active=active.map((a=>a.hasResult()?new ActiveSource(a.source,0):a)));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){let result={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":id};return selected>-1&&(result["aria-activedescendant"]=id+"-"+selected),result}const none=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}class ActiveSource{constructor(source,state){let explicitPos=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&0!=value.state&&(value=new ActiveSource(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return"delete"!=type&&conf.activateOnTyping?new ActiveSource(this.source,1):this.map(tr.changes)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos))}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||"delete"==type&&cur(tr.startState)==this.from)return new ActiveSource(this.source,"input"==type&&conf.activateOnTyping?1:0);let updated,explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos);return function(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return"function"==typeof validFor?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}(this.result.validFor,tr.state,from,to)?new ActiveResult(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new ActiveResult(this.source,explicitPos,updated,updated.from,null!==(_a=updated.to)&&void 0!==_a?_a:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}}const setActiveEffect=StateEffect.define({map:(sources,mapping)=>sources.map((s=>s.map(mapping)))}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create:()=>CompletionState.start(),update:(value,tr)=>value.update(tr),provide:f=>[showTooltip.from(f,(val=>val.tooltip)),EditorView.contentAttributes.from(f,(state=>state.attrs))]});function applyCompletion(view,option){const apply=option.completion.apply||option.completion.label;let result=view.state.field(completionState).active.find((a=>a.source==option.source));return result instanceof ActiveResult&&("string"==typeof apply?view.dispatch(Object.assign(Object.assign({},function(state,text,from,to){let{main:main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange((range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range:range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)}))),{userEvent:"input.complete"})}(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option.completion)})):apply(view,option.completion,result.from,result.to),!0)}function moveCompletionSelection(forward){let by=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"option";return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected="page"==by?0:length-1:selected>=length&&(selected="page"==by?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}class RunningQuery{constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}}const completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)1==active.state&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some((tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr)));for(let i=0;i50&&Date.now()-query.time>1e3){for(let handler of query.context.abortListeners)try{handler()}catch(e){logException(this.view.state,e)}query.context.abortListeners=null,this.running.splice(i--,1)}else query.updates.push(...update.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=cState.active.some((a=>1==a.state&&!this.running.some((q=>q.active.source==a.source))))?setTimeout((()=>this.startUpdate()),50):-1,0!=this.composing)for(let tr of update.transactions)"input"==getUserEvent(tr)?this.composing=2:2==this.composing&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state:state}=this.view,cState=state.field(completionState);for(let active of cState.active)1!=active.state||this.running.some((r=>r.active.source==active.source))||this.startQuery(active)}startQuery(active){let{state:state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then((result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())}),(err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)}))}scheduleAccept(){this.running.every((q=>void 0!==q.done))?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout((()=>this.accept()),50))}accept(){var _a;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source));if(current&&1==current.state)if(null==query.done){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);1!=active.state&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);dialog&&dialog.dom.contains(event.relatedTarget)||this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){3==this.composing&&setTimeout((()=>this.view.dispatch({effects:startCompletionEffect.of(!1)})),20),this.composing=0}}}),baseTheme$1=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"".concat(400,"px"),boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"".concat(30,"px")},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"".concat(30,"px")},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class FieldPos{constructor(field,line,from,to){this.field=field,this.line=line,this.from=from,this.to=to}}class FieldRange{constructor(field,from,to){this.field=field,this.from=from,this.to=to}map(changes){let from=changes.mapPos(this.from,-1,MapMode.TrackDel),to=changes.mapPos(this.to,1,MapMode.TrackDel);return null==from||null==to?null:new FieldRange(this.field,from,to)}}class Snippet{constructor(lines,fieldPositions){this.lines=lines,this.fieldPositions=fieldPositions}instantiate(state,pos){let text=[],lineStart=[pos],lineObj=state.doc.lineAt(pos),baseIndent=/^\s*/.exec(lineObj.text)[0];for(let line of this.lines){if(text.length){let indent=baseIndent,tabs=/^\t*/.exec(line)[0].length;for(let i=0;inew FieldRange(pos.field,lineStart[pos.line]+pos.from,lineStart[pos.line]+pos.to)));return{text:text,ranges:ranges}}static parse(template){let m,fields=[],lines=[],positions=[];for(let line of template.split(/\r\n?|\n/)){for(;m=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line);){let seq=m[1]?+m[1]:null,name=m[2]||m[3]||"",found=-1;for(let i=0;i=found&&pos.field++}positions.push(new FieldPos(found,lines.length,m.index,m.index+name.length)),line=line.slice(0,m.index)+name+line.slice(m.index+m[0].length)}for(let esc;esc=/\\([{}])/.exec(line);){line=line.slice(0,esc.index)+esc[1]+line.slice(esc.index+esc[0].length);for(let pos of positions)pos.line==lines.length&&pos.from>esc.index&&(pos.from--,pos.to--)}lines.push(line)}return new Snippet(lines,positions)}}let fieldMarker=Decoration.widget({widget:new class extends WidgetType{toDOM(){let span=document.createElement("span");return span.className="cm-snippetFieldPosition",span}ignoreEvent(){return!1}}}),fieldRange=Decoration.mark({class:"cm-snippetField"});class ActiveSnippet{constructor(ranges,active){this.ranges=ranges,this.active=active,this.deco=Decoration.set(ranges.map((r=>(r.from==r.to?fieldMarker:fieldRange).range(r.from,r.to))))}map(changes){let ranges=[];for(let r of this.ranges){let mapped=r.map(changes);if(!mapped)return null;ranges.push(mapped)}return new ActiveSnippet(ranges,this.active)}selectionInsideField(sel){return sel.ranges.every((range=>this.ranges.some((r=>r.field==this.active&&r.from<=range.from&&r.to>=range.to))))}}const setActive=StateEffect.define({map:(value,changes)=>value&&value.map(changes)}),moveToField=StateEffect.define(),snippetState=StateField.define({create:()=>null,update(value,tr){for(let effect of tr.effects){if(effect.is(setActive))return effect.value;if(effect.is(moveToField)&&value)return new ActiveSnippet(value.ranges,effect.value)}return value&&tr.docChanged&&(value=value.map(tr.changes)),value&&tr.selection&&!value.selectionInsideField(tr.selection)&&(value=null),value},provide:f=>EditorView.decorations.from(f,(val=>val?val.deco:Decoration.none))});function fieldSelection(ranges,field){return EditorSelection.create(ranges.filter((r=>r.field==field)).map((r=>EditorSelection.range(r.from,r.to))))}function snippet(template){let snippet=Snippet.parse(template);return(editor,completion,from,to)=>{let{text:text,ranges:ranges}=snippet.instantiate(editor.state,from),spec={changes:{from:from,to:to,insert:Text.of(text)},scrollIntoView:!0,annotations:completion?pickedCompletion.of(completion):void 0};if(ranges.length&&(spec.selection=fieldSelection(ranges,0)),ranges.length>1){let active=new ActiveSnippet(ranges,0),effects=spec.effects=[setActive.of(active)];void 0===editor.state.field(snippetState,!1)&&effects.push(StateEffect.appendConfig.of([snippetState,addSnippetKeymap,snippetPointerHandler,baseTheme$1]))}editor.dispatch(editor.state.update(spec))}}function moveField(dir){return _ref44=>{let{state:state,dispatch:dispatch}=_ref44,active=state.field(snippetState,!1);if(!active||dir<0&&0==active.active)return!1;let next=active.active+dir,last=dir>0&&!active.ranges.some((r=>r.field==next+dir));return dispatch(state.update({selection:fieldSelection(active.ranges,next),effects:setActive.of(last?null:new ActiveSnippet(active.ranges,next))})),!0}}const defaultSnippetKeymap=[{key:"Tab",run:moveField(1),shift:moveField(-1)},{key:"Escape",run:_ref45=>{let{state:state,dispatch:dispatch}=_ref45;return!!state.field(snippetState,!1)&&(dispatch(state.update({effects:setActive.of(null)})),!0)}}],snippetKeymap=Facet.define({combine:maps=>maps.length?maps[0]:defaultSnippetKeymap}),addSnippetKeymap=Prec.highest(keymap.compute([snippetKeymap],(state=>state.facet(snippetKeymap))));function snippetCompletion(template,completion){return Object.assign(Object.assign({},completion),{apply:snippet(template)})}const snippetPointerHandler=EditorView.domEventHandlers({mousedown(event,view){let pos,active=view.state.field(snippetState,!1);if(!active||null==(pos=view.posAtCoords({x:event.clientX,y:event.clientY})))return!1;let match=active.ranges.find((r=>r.from<=pos&&r.to>=pos));return!(!match||match.field==active.active)&&(view.dispatch({selection:fieldSelection(active.ranges,match.field),effects:setActive.of(active.ranges.some((r=>r.field>match.field))?new ActiveSnippet(active.ranges,match.field):null)}),!0)}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return null==mapped?void 0:mapped}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create:()=>RangeSet.empty,update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closing(ch){for(let i=0;i<"()[]{}<>".length;i+=2)if("()[]{}<>".charCodeAt(i)==ch)return"()[]{}<>".charAt(i+1);return fromCodePoint(ch<128?ch:ch+1)}function config(state,pos){return state.languageDataAt("closeBrackets",pos)[0]||defaults}const android$1="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),inputHandler=EditorView.inputHandler.of(((view,from,to,insert)=>{if((android$1?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert.length>2||2==insert.length&&1==codePointSize(codePointAt(insert,0))||from!=sel.from||to!=sel.to)return!1;let tr=function(state,bracket){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}(view.state,insert);return!!tr&&(view.dispatch(tr),!0)})),closeBracketsKeymap=[{key:"Backspace",run:_ref46=>{let{state:state,dispatch:dispatch}=_ref46;if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,dont=null,changes=state.changeByRange((range=>{if(range.empty){let before=function(doc,pos){let prev=doc.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}(state.doc,range.head);for(let token of tokens)if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}}));return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont}}];function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,(from=>{from==pos&&(found=!0)})),found}function nextChar(doc,pos){let next=doc.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange((range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function handleClose(state,_open,close){let dont=null,changes=state.changeByRange((range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range:range}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function handleSame(state,token,allowTriple,config){let stringPrefixes=config.stringPrefixes||defaults.stringPrefixes,dont=null,changes=state.changeByRange((range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let start,pos=range.head,next=nextChar(state.doc,pos);if(next==token){if(nodeStart(state,pos))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(closedBracketAt(state,pos)){let content=allowTriple&&state.sliceDoc(pos,pos+3*token.length)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content.length,insert:content},range:EditorSelection.cursor(pos+content.length)}}}else{if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start))return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&canStartStringAt(state,pos,stringPrefixes)>-1&&!function(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),maxPrefix=prefixes.reduce(((m,p)=>Math.max(m,p.length)),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}function autocompletion(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1]}const completionKeymap=[{key:"Ctrl-Space",run:view=>!!view.state.field(completionState,!1)&&(view.dispatch({effects:startCompletionEffect.of(!0)}),!0)},{key:"Escape",run:view=>{let cState=view.state.field(completionState,!1);return!(!cState||!cState.active.some((a=>0!=a.state)))&&(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)}},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:view=>{let cState=view.state.field(completionState,!1);return!(view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestampstate.facet(completionConfig).defaultKeymap?[completionKeymap]:[])));class SelectedDiagnostic{constructor(from,to,diagnostic){this.from=from,this.to=to,this.diagnostic=diagnostic}}class LintState{constructor(diagnostics,panel,selected){this.diagnostics=diagnostics,this.panel=panel,this.selected=selected}static init(diagnostics,panel,state){let markedDiagnostics=diagnostics,diagnosticFilter=state.facet(lintConfig).markerFilter;diagnosticFilter&&(markedDiagnostics=diagnosticFilter(markedDiagnostics));let ranges=Decoration.set(markedDiagnostics.map((d=>d.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to))),!0);return new LintState(ranges,panel,findDiagnostic(ranges))}}function findDiagnostic(diagnostics){let diagnostic=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,after=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,found=null;return diagnostics.between(after,1e9,((from,to,_ref47)=>{let{spec:spec}=_ref47;if(!diagnostic||spec.diagnostic==diagnostic)return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1})),found}const setDiagnosticsEffect=StateEffect.define(),togglePanel=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create:()=>new LintState(Decoration.none,null,null),update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f=>[showPanel.from(f,(val=>val.panel)),EditorView.decorations.from(f,(s=>s.diagnostics))]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function diagnosticsTooltip(view,diagnostics){return crelt("ul",{class:"cm-tooltip-lint"},diagnostics.map((d=>renderDiagnostic(view,d,!1))))}const closeLintPanel=view=>{let field=view.state.field(lintState,!1);return!(!field||!field.panel)&&(view.dispatch({effects:togglePanel.of(!1)}),!0)},lintKeymap=[{key:"Mod-Shift-m",run:view=>{let field=view.state.field(lintState,!1);var state,effects;field&&field.panel||view.dispatch({effects:(state=view.state,effects=[togglePanel.of(!0)],state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions)))});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},preventDefault:!0},{key:"F8",run:view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!(!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to))&&(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)}}],lintConfig=Facet.define({combine:input=>Object.assign({sources:input.map((i=>i.source))},combineConfig(input.map((i=>i.config)),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))});function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name}of actions){for(let i=0;ic.toLowerCase()==ch.toLowerCase()))){assigned.push(ch);continue actions}}assigned.push("")}return assigned}function renderDiagnostic(view,diagnostic,inPanel){var _a;let keys=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),null===(_a=diagnostic.actions)||void 0===_a?void 0:_a.map(((action,i)=>{let fired=!1,click=e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},{name:name}=action,keyIndex=keys[i]?name.indexOf(keys[i]):-1,nameElt=keyIndex<0?name:[name.slice(0,keyIndex),crelt("u",name.slice(keyIndex,keyIndex+1)),name.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":" Action: ".concat(name).concat(keyIndex<0?"":' (access key "'.concat(keys[i],')"'),".")},nameElt)})),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}class DiagnosticWidget extends WidgetType{constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class PanelItem{constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(4294967295*Math.random()).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class LintPanel{constructor(view){this.view=view,this.items=[];this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:event=>{if(27==event.keyCode)closeLintPanel(this.view),this.view.focus();else if(38==event.keyCode||33==event.keyCode)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(40==event.keyCode||34==event.keyCode)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(36==event.keyCode)this.moveSelection(0);else if(35==event.keyCode)this.moveSelection(this.items.length-1);else if(13==event.keyCode)this.view.focus();else{if(!(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0))return;{let{diagnostic:diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i{for(let i=0;icloseLintPanel(this.view)},"×")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i{let item,{spec:spec}=_ref49,found=-1;for(let j=i;ji&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++}));i({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:_ref50=>{let{sel:sel,panel:panel}=_ref50;sel.toppanel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let selection=findDiagnostic(this.view.state.field(lintState).diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new LintPanel(view)}}function underline(color){return function(content){return'url(\'data:image/svg+xml,1&&void 0!==arguments[1]?arguments[1]:'viewBox="0 0 40 40"',">").concat(encodeURIComponent(content),"')")}(''),'width="6" height="3"')}const baseTheme=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],(state=>{let{selected:selected,panel:panel}=state.field(lintState);return selected&&panel&&selected.from!=selected.to?Decoration.set([activeMark.range(selected.from,selected.to)]):Decoration.none})),function(source){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},setHover=StateEffect.define(),hoverState=StateField.define({create:()=>[],update(value,tr){if(value.length&&(options.hideOnChange&&(tr.docChanged||tr.selection)?value=[]:options.hideOn&&(value=value.filter((v=>!options.hideOn(tr,v)))),tr.docChanged)){let mapped=[];for(let tooltip of value){let newPos=tr.changes.mapPos(tooltip.pos,-1,MapMode.TrackDel);if(null!=newPos){let copy=Object.assign(Object.create(null),tooltip);copy.pos=newPos,null!=copy.end&&(copy.end=tr.changes.mapPos(copy.end)),mapped.push(copy)}}value=mapped}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=[]);return value},provide:f=>showHoverTooltip.from(f)});return[hoverState,ViewPlugin.define((view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300))),showHoverTooltipHost]}((function(view,pos,side){let{diagnostics:diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),((from,to,_ref48)=>{let{spec:spec}=_ref48;pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(pos({dom:diagnosticsTooltip(view,found)})}:null}),{hideOn:function(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!(!tr.effects.some((e=>e.is(setDiagnosticsEffect)))&&!tr.changes.touchesRange(line.from,line.to))}}),baseTheme],basicSetup=[lineNumbers(),activeLineGutterHighlighter,highlightSpecialChars(),history(),foldGutter(),drawSelection(),[dropCursorPos,drawDropCursor],EditorState.allowMultipleSelections.of(!0),EditorState.transactionFilter.of((tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc=tr.newDoc,{head:head}=tr.newSelection.main,line=doc.lineAt(head);if(head>line.from+200)return tr;let lineStart=doc.sliceString(line.from,head);if(!rules.some((r=>r.test(lineStart))))return tr;let{state:state}=tr,last=-1,changes=[];for(let{head:head}of state.selection.ranges){let line=state.doc.lineAt(head);if(line.from==last)continue;last=line.from;let indent=getIndentation(state,line.from);if(null==indent)continue;let cur=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);cur!=norm&&changes.push({from:line.from,to:line.from+cur.length,insert:norm})}return changes.length?[tr,{changes:changes,sequential:!0}]:tr})),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),[inputHandler,bracketState],autocompletion(),rectangularSelection(),crosshairCursor(),activeLineHighlighter,highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])];class Stack{constructor(p,stack,state,reducePos,pos,score,buffer,bufferBase,curContext){let lookAhead=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,parent=arguments.length>10?arguments[10]:void 0;this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return"[".concat(this.stack.filter(((_,i)=>i%3==0)).concat(this.state),"]@").concat(this.pos).concat(this.score?"!"+this.score:"")}static start(p,state){let pos=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a;let depth=action>>19,type=65535&action,{parser:parser}=this.p,dPrec=parser.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),0==depth)return this.pushState(parser.getGoto(this.state,type,!0),this.reducePos),type=2e3&&!(null===(_a=this.p.parser.nodeSet.types[type])||void 0===_a?void 0:_a.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSizebase;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end){let size=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,isReduce=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(0==term&&(!this.stack.length||this.stack[this.stack.length-1]0&&0==cur.buffer[top-4]&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start)return void(cur.buffer[top-2]=end)}}if(isReduce&&this.pos!=end){let index=this.buffer.length;if(index>0&&0!=this.buffer[index-4])for(;index>0&&this.buffer[index-2]>end;)this.buffer[index]=this.buffer[index-4],this.buffer[index+1]=this.buffer[index-3],this.buffer[index+2]=this.buffer[index-2],this.buffer[index+3]=this.buffer[index-1],index-=4,size>4&&(size-=4);this.buffer[index]=term,this.buffer[index+1]=start,this.buffer[index+2]=end,this.buffer[index+3]=size}else this.buffer.push(term,start,end,size)}shift(action,next,nextEnd){let start=this.pos;if(131072&action)this.pushState(65535&action,this.pos);else if(0==(262144&action)){let nextState=action,{parser:parser}=this.p;(nextEnd>this.pos||next<=parser.maxNode)&&(this.pos=nextEnd,parser.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser.maxNode&&this.buffer.push(next,start,nextEnd,4)}else this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4)}apply(action,next,nextEnd){65536&action?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index=this.p.reused.length-1;(index<0||this.p.reused[index]!=value)&&(this.p.reused.push(value),index++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off=parent.buffer.length;for(;off>0&&parent.buffer[off-2]>parent.reducePos;)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;for(;parent&&base==parent.bufferBase;)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(0==action)return!1;if(0==(65536&action))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let s,i=0;i1&i&&v==s))||best.push(nextStates[i],s)}nextStates=best}let result=[];for(let i=0;i>19,term=65535&reduce,target=this.stack.length-3*depth;if(target<0||parser.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(null==backup)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser}=this.p,seen=[],explore=(state,depth)=>{if(!seen.includes(state))return seen.push(state),parser.allActions(state,(action=>{if(393216&action);else if(65536&action){let rDepth=(action>>19)-depth;if(rDepth>1){let term=65535&action,target=this.stack.length-3*rDepth;if(target>=0&&parser.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(null!=found)return found}}))};return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:parser}=this.p;return 65535==parser.data[parser.stateSlot(this.state,1)]&&!parser.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;ithis.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}}var Recover;!function(Recover){Recover[Recover.Insert=200]="Insert",Recover[Recover.Delete=190]="Delete",Recover[Recover.Reduce=100]="Reduce",Recover[Recover.MaxNext=4]="MaxNext",Recover[Recover.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover[Recover.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover[Recover.MinBigReduction=2e3]="MinBigReduction"}(Recover||(Recover={}));class SimulatedStack{constructor(start){this.start=start,this.state=start.state,this.stack=start.stack,this.base=this.stack.length}reduce(action){let term=65535&action,depth=action>>19;0==depth?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(depth-1);let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}}class StackBufferCursor{constructor(stack,pos,index){this.stack=stack,this.pos=pos,this.index=index,this.buffer=stack.buffer,0==this.index&&this.maybeNext()}static create(stack){let pos=arguments.length>1&&void 0!==arguments[1]?arguments[1]:stack.bufferBase+stack.buffer.length;return new StackBufferCursor(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;null!=next&&(this.index=this.stack.bufferBase-next.bufferBase,this.stack=next,this.buffer=next.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}function decodeArray(input){let Type=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Uint16Array;if("string"!=typeof input)return input;let array=null;for(let pos=0,out=0;pos=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=ranges[0].from,this.range=ranges[0],this.end=ranges[ranges.length-1].to,this.readNext()}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex,pos=this.pos+offset;for(;posrange.to:pos>=range.to;){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pospos)return Math.max(pos,range.from);return this.end}peek(offset){let pos,result,idx=this.chunkOff+offset;if(idx>=0&&idx=this.chunk2Pos&&posrange.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token){let endOffset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(null==end||end=this.chunk2Pos&&this.posthis.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;for(this.chunkOff+=n;this.pos+n>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}}class TokenGroup{constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser}=stack.p;readToken(this.data,input,stack,this.id,parser.data,parser.tokenPrecTable)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class LocalTokenGroup{constructor(data,precTable,elseToken){this.precTable=precTable,this.elseToken=elseToken,this.data="string"==typeof data?decodeArray(data):data}token(input,stack){let start=input.pos,skipped=0;for(;;){let atEof=input.next<0,nextPos=input.resolveOffset(1,1);if(readToken(this.data,input,stack,0,this.data,this.precTable),input.token.value>-1)break;if(null==this.elseToken)return;if(atEof||skipped++,null==nextPos)break;input.reset(nextPos,input.token)}skipped&&(input.reset(start,input.token),input.acceptToken(this.elseToken,skipped))}}LocalTokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(token){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.token=token,this.contextual=!!options.contextual,this.fallback=!!options.fallback,this.extend=!!options.extend}}function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<0){let term=data[i];if(dialect.allows(term)&&(-1==input.token.value||input.token.value==term||overrides(term,input.token.value,precTable,precOffset))){input.acceptToken(term);break}}let next=input.next,low=0,high=data[state+2];if(!(input.next<0&&high>low&&65535==data[accEnd+3*high-3]&&65535==data[accEnd+3*high-3])){for(;low>1,index=accEnd+mid+(mid<<1),from=data[index],to=data[index+1]||65536;if(next=to)){state=data[index+2],input.advance();continue scan}low=mid+1}}break}state=data[accEnd+3*high-1]}}function findOffset(data,start,term){for(let next,i=start;65535!=(next=data[i]);i++)if(next==term)return i-start;return-1}function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}!function(Safety){Safety[Safety.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments,this.nodeSet=nodeSet,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){for(this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from,this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(fr.tree),this.start.push(-fr.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(pos){if(pospos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last]++,this.nextStart=start+next.length}}}class TokenCache{constructor(parser,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser.tokenizers.map((_=>new CachedToken))}getActions(stack){let actionIndex=0,main=null,{parser:parser}=stack.p,{tokenizers:tokenizers}=parser,mask=parser.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;itoken.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),0!=token.value)){let startIndex=actionIndex;if(token.extended>-1&&(actionIndex=this.addActions(stack,token.extended,token.end,actionIndex)),actionIndex=this.addActions(stack,token.value,token.end,actionIndex),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),main||stack.pos!=this.stream.end||(main=new CachedToken,main.value=stack.p.parser.eofTerm,main.start=main.end=stack.pos,actionIndex=this.addActions(stack,main.value,main.end,actionIndex)),this.mainToken=main,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos:pos,p:p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser}=stack.p;for(let i=0;i=0&&stack.p.parser.dialect.allows(result>>1)){0==(1&result)?token.value=result>>1:token.extended=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index){for(let i=0;i4*parser.bufferLength?new FragmentCursor(fragments,parser.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stopped,stoppedTokens,stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[];if(this.bigReductionCount>300&&1==stacks.length){let[s]=stacks;for(;s.forceReduce()&&s.stack.length&&s.stack[s.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;ipos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{stopped||(stopped=[],stoppedTokens=[]),stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end)}}break}}if(!newStacks.length){let finished=stopped&&function(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;(stack.pos==stack.p.stream.end||null!=stopped&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.scorethis.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=1==this.recovering?1:3*this.recovering;if(newStacks.length>maxRemaining)for(newStacks.sort(((a,b)=>b.score-a.score));newStacks.length>maxRemaining;)newStacks.pop();newStacks.some((s=>s.reducePos>pos))&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i500&&other.buffer.length>500){if(!((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)){newStacks.splice(i--,1);continue outer}newStacks.splice(j--,1)}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i ":"";if(null!=this.stoppedAt&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match),verbose&&console.log(base+this.stackID(stack)+" (via reuse of ".concat(parser.getName(cached.type.id),")")),!0;if(!(cached instanceof Tree)||0==cached.children.length||cached.positions[0]>0)break;let inner=cached.children[0];if(!(inner instanceof Tree&&0==cached.positions[0]))break;cached=inner}}let defaultReduce=parser.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base+this.stackID(stack)+" (via always-reduce ".concat(parser.getName(65535&defaultReduce),")")),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;istart?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i ":"";if(stack.deadEnd){if(restarted)continue;if(restarted=!0,stack.restart(),verbose&&console.log(base+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))continue}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10;j++){if(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),this.advanceFully(force,newStacks))break;verbose&&(forceBase=this.stackID(force)+" -> ")}for(let insert of stack.recoverByInsert(token))verbose&&console.log(base+this.stackID(insert)+" (via recover-insert)"),this.advanceFully(insert,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base+this.stackID(stack)+" (via recover-delete ".concat(this.parser.getName(token),")")),pushStackDedup(stack,newStacks)):(!finished||finished.scorex;class ContextTracker{constructor(spec){this.start=spec.start,this.shift=spec.shift||id,this.reduce=spec.reduce||id,this.reuse=spec.reuse||id,this.hash=spec.hash||(()=>0),this.strict=!1!==spec.strict}}class LRParser extends Parser{constructor(spec){if(super(),this.wrappers=[],14!=spec.version)throw new RangeError("Parser version (".concat(spec.version,") doesn't match runtime version (",14,")"));let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;ispec.topRules[r][1])),nodeProps=[];for(let i=0;i=0)setProp(next,prop,propSpec[i++]);else{let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++}}}this.nodeSet=new NodeSet(nodeNames.map(((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:0==i,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context,this.specializerSpecs=spec.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let i=0;i"number"==typeof value?new TokenGroup(tokenArray,value):value)),this.topRules=spec.topRules,this.dialects=spec.dialects||{},this.dynamicPrecedences=spec.dynamicPrecedences||null,this.tokenPrecTable=spec.tokenPrec,this.termNames=spec.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse}getGoto(state,term){let loose=arguments.length>2&&void 0!==arguments[2]&&arguments[2],table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=1&groupTag,target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos0}validAction(state,action){return!!this.allActions(state,(a=>a==action||null))}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);null==result;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=pair(this.data,i+2)}result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=pair(this.data,i+2)}if(0==(1&this.data[i+2])){let value=this.data[i+1];result.some(((v,i)=>1&i&&v==value))||result.push(this.data[i],value)}}return result}configure(config){let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props&&(copy.nodeSet=this.nodeSet.extend(...config.props)),config.top){let info=this.topRules[config.top];if(!info)throw new RangeError("Invalid top rule name ".concat(config.top));copy.top=info}return config.tokenizers&&(copy.tokenizers=this.tokenizers.map((t=>{let found=config.tokenizers.find((r=>r.from==t));return found?found.to:t}))),config.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map(((s,i)=>{let found=config.specializers.find((r=>r.from==s.external));if(!found)return s;let spec=Object.assign(Object.assign({},s),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec}))),config.contextTracker&&(copy.context=config.contextTracker),config.dialect&&(copy.dialect=this.parseDialect(config.dialect)),null!=config.strict&&(copy.strict=config.strict),config.wrap&&(copy.wrappers=copy.wrappers.concat(config.wrap)),null!=config.bufferLength&&(copy.bufferLength=config.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec=this.dynamicPrecedences;return null==prec?0:prec[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map((()=>!1));if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;ispec.external(value,stack)<<1|mask}return spec.get}const selfClosers$1={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},closeOnOpen={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function isSpace(ch){return 9==ch||10==ch||13==ch||32==ch}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(input,offset){let pos=input.pos+offset;if(cachedPos==pos&&cachedInput==input)return cachedName;let next=input.peek(offset);for(;isSpace(next);)next=input.peek(++offset);let name="";for(;45==(ch=next)||46==ch||58==ch||ch>=65&&ch<=90||95==ch||ch>=97&&ch<=122||ch>=161;)name+=String.fromCharCode(next),next=input.peek(++offset);var ch;return cachedInput=input,cachedPos=pos,cachedName=name?name.toLowerCase():next==question||next==bang?void 0:null}const question=63,bang=33;function ElementContext(name,parent){this.name=name,this.parent=parent,this.hash=parent?parent.hash:0;for(let i=0;istartTagTerms.indexOf(term)>-1?new ElementContext(tagNameAfter(input,1)||"",context):context,reduce:(context,term)=>20==term&&context?context.parent:context,reuse(context,node,stack,input){let type=node.type.id;return 6==type||36==type?new ElementContext(tagNameAfter(input,1)||"",context):context},hash:context=>context?context.hash:0,strict:!1}),tagStart=new ExternalTokenizer(((input,stack)=>{if(60!=input.next)return void(input.next<0&&stack.context&&input.acceptToken(57));input.advance();let close=47==input.next;close&&input.advance();let name=tagNameAfter(input,0);if(void 0===name)return;if(!name)return input.acceptToken(close?14:6);let parent=stack.context?stack.context.name:null;if(close){if(name==parent)return input.acceptToken(11);if(parent&&implicitlyClosed[parent])return input.acceptToken(57,-2);if(stack.dialectEnabled(0))return input.acceptToken(12);for(let cx=stack.context;cx;cx=cx.parent)if(cx.name==name)return;input.acceptToken(13)}else{if("script"==name)return input.acceptToken(7);if("style"==name)return input.acceptToken(8);if("textarea"==name)return input.acceptToken(9);if(selfClosers$1.hasOwnProperty(name))return input.acceptToken(10);parent&&closeOnOpen[parent]&&closeOnOpen[parent][name]?input.acceptToken(57,-1):input.acceptToken(6)}}),{contextual:!0}),commentContent=new ExternalTokenizer((input=>{for(let dashes=0,i=0;;i++){if(input.next<0){i&&input.acceptToken(58);break}if(45==input.next)dashes++;else{if(62==input.next&&dashes>=2){i>3&&input.acceptToken(58,-2);break}dashes=0}input.advance()}}));const endTag=new ExternalTokenizer(((input,stack)=>{if(47==input.next&&62==input.peek(1)){let selfClosing=stack.dialectEnabled(1)||function(context){for(;context;context=context.parent)if("svg"==context.name||"math"==context.name)return!0;return!1}(stack.context);input.acceptToken(selfClosing?5:4,2)}else 62==input.next&&input.acceptToken(4,1)}));function contentTokenizer(tag,textToken,endToken){let lastState=2+tag.length;return new ExternalTokenizer((input=>{for(let state=0,matchedLen=0,i=0;;i++){if(input.next<0){i&&input.acceptToken(textToken);break}if(0==state&&60==input.next||1==state&&47==input.next||state>=2&&statematchedLen?input.acceptToken(textToken,-matchedLen):input.acceptToken(endToken,-(matchedLen-2));break}if((10==input.next||13==input.next)&&i){input.acceptToken(textToken,1);break}state=matchedLen=0}else matchedLen++;input.advance()}}))}const scriptTokens=contentTokenizer("script",54,1),styleTokens=contentTokenizer("style",55,2),textareaTokens=contentTokenizer("textarea",56,3),htmlHighlighting=styleTags({"Text RawText":tags$1.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":tags$1.angleBracket,TagName:tags$1.tagName,"MismatchedCloseTag/TagName":[tags$1.tagName,tags$1.invalid],AttributeName:tags$1.attributeName,"AttributeValue UnquotedAttributeValue":tags$1.attributeValue,Is:tags$1.definitionOperator,"EntityReference CharacterReference":tags$1.character,Comment:tags$1.blockComment,ProcessingInst:tags$1.processingInstruction,DoctypeDecl:tags$1.documentMeta}),parser$2=LRParser.deserialize({version:14,states:",xOVO!rOOO!WQ#tO'#CqO!]Q#tO'#CzO!bQ#tO'#C}O!gQ#tO'#DQO!lQ#tO'#DSO!qOaO'#CpO!|ObO'#CpO#XOdO'#CpO$eO!rO'#CpOOO`'#Cp'#CpO$lO$fO'#DTO$tQ#tO'#DVO$yQ#tO'#DWOOO`'#Dk'#DkOOO`'#DY'#DYQVO!rOOO%OQ&rO,59]O%WQ&rO,59fO%`Q&rO,59iO%hQ&rO,59lO%sQ&rO,59nOOOa'#D^'#D^O%{OaO'#CxO&WOaO,59[OOOb'#D_'#D_O&`ObO'#C{O&kObO,59[OOOd'#D`'#D`O&sOdO'#DOO'OOdO,59[OOO`'#Da'#DaO'WO!rO,59[O'_Q#tO'#DROOO`,59[,59[OOOp'#Db'#DbO'dO$fO,59oOOO`,59o,59oO'lQ#|O,59qO'qQ#|O,59rOOO`-E7W-E7WO'vQ&rO'#CsOOQW'#DZ'#DZO(UQ&rO1G.wOOOa1G.w1G.wO(^Q&rO1G/QOOOb1G/Q1G/QO(fQ&rO1G/TOOOd1G/T1G/TO(nQ&rO1G/WOOO`1G/W1G/WOOO`1G/Y1G/YO(yQ&rO1G/YOOOa-E7[-E7[O)RQ#tO'#CyOOO`1G.v1G.vOOOb-E7]-E7]O)WQ#tO'#C|OOOd-E7^-E7^O)]Q#tO'#DPOOO`-E7_-E7_O)bQ#|O,59mOOOp-E7`-E7`OOO`1G/Z1G/ZOOO`1G/]1G/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pezabcde{}!P!R!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ}bQ!PcQ!RdQ!UeZ!e{}!P!R!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag EndTag SelfClosingEndTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:67,context:elementContext,nodeProps:[["closedBy",-10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,21,30,33,36,"CloseTag"],["openedBy",4,"StartTag StartCloseTag",5,"StartTag",-4,29,32,35,37,"OpenTag"],["group",-9,14,17,18,19,20,39,40,41,42,"Entity",16,"Entity TextContent",-3,28,31,34,"TextContent Entity"]],propSources:[htmlHighlighting],skippedNodes:[0],repeatNodeCount:9,tokenData:"#%g!aR!YOX$qXY,QYZ,QZ[$q[]&X]^,Q^p$qpq,Qqr-_rs4ysv-_vw5iwxJ^x}-_}!OKP!O!P-_!P!Q$q!Q![-_![!]!!O!]!^-_!^!_!&W!_!`#$o!`!a&X!a!c-_!c!}!!O!}#R-_#R#S!!O#S#T3V#T#o!!O#o#s-_#s$f$q$f%W-_%W%o!!O%o%p-_%p&a!!O&a&b-_&b1p!!O1p4U-_4U4d!!O4d4e-_4e$IS!!O$IS$I`-_$I`$Ib!!O$Ib$Kh-_$Kh%#t!!O%#t&/x-_&/x&Et!!O&Et&FV-_&FV;'S!!O;'S;:j!&Q;:j;=`4s<%l?&r-_?&r?Ah!!O?Ah?B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=`<%l!Ey!V#$zXiS`P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X",tokenizers:[scriptTokens,styleTokens,textareaTokens,endTag,tagStart,commentContent,0,1,2,3,4,5],topRules:{Document:[0,15]},dialects:{noMatch:0,selfClosing:485},tokenPrec:487});function getAttrs(openTag,input){let attrs=Object.create(null);for(let att of openTag.getChildren(23)){let name=att.getChild(24),value=att.getChild(26)||att.getChild(27);name&&(attrs[input.read(name.from,name.to)]=value?26==value.type.id?input.read(value.from+1,value.to-1):input.read(value.from,value.to):"")}return attrs}function findTagName(openTag,input){let tagNameNode=openTag.getChild(22);return tagNameNode?input.read(tagNameNode.from,tagNameNode.to):" "}function maybeNest(node,input,tags){let attrs;for(let tag of tags)if(!tag.attrs||tag.attrs(attrs||(attrs=getAttrs(node.node.parent.firstChild,input))))return{parser:tag.parser};return null}function configureNesting(){let tags=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],attributes=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],script=[],style=[],textarea=[],other=[];for(let tag of tags){("script"==tag.tag?script:"style"==tag.tag?style:"textarea"==tag.tag?textarea:other).push(tag)}let attrs=attributes.length?Object.create(null):null;for(let attr of attributes)(attrs[attr.name]||(attrs[attr.name]=[])).push(attr);return parseMixed(((node,input)=>{let id=node.type.id;if(28==id)return maybeNest(node,input,script);if(31==id)return maybeNest(node,input,style);if(34==id)return maybeNest(node,input,textarea);if(20==id&&other.length){let attrs,n=node.node,open=n.firstChild,tagName=open&&findTagName(open,input);if(tagName)for(let tag of other)if(tag.tag==tagName&&(!tag.attrs||tag.attrs(attrs||(attrs=getAttrs(n,input))))){let close=n.lastChild;return{parser:tag.parser,overlay:[{from:open.to,to:37==close.type.id?close.from:n.to}]}}}if(attrs&&23==id){let nameNode,n=node.node;if(nameNode=n.firstChild){let matches=attrs[input.read(nameNode.from,nameNode.to)];if(matches)for(let attr of matches){if(attr.tagName&&attr.tagName!=findTagName(n.parent,input))continue;let value=n.lastChild;if(26==value.type.id){let from=value.from+1,last=value.lastChild,to=value.to-(last&&last.isError?0:1);if(to>from)return{parser:attr.parser,overlay:[{from:from,to:to}]}}else if(27==value.type.id)return{parser:attr.parser,overlay:[{from:value.from,to:value.to}]}}}}return null}))}const space$1=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288];function isAlpha(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=161}const identifiers=new ExternalTokenizer(((input,stack)=>{for(let inside=!1,dashes=0,i=0;;i++){let{next:next}=input;if(!(isAlpha(next)||45==next||95==next||inside&&(ch=next,ch>=48&&ch<=57))){inside&&input.acceptToken(40==next?97:2==dashes&&stack.canShift(2)?2:98);break}!inside&&(45!=next||i>0)&&(inside=!0),dashes===i&&45==next&&dashes++,input.advance()}var ch})),descendant=new ExternalTokenizer((input=>{if(space$1.includes(input.peek(-1))){let{next:next}=input;(isAlpha(next)||95==next||35==next||46==next||91==next||58==next||45==next)&&input.acceptToken(96)}})),unitToken=new ExternalTokenizer((input=>{if(!space$1.includes(input.peek(-1))){let{next:next}=input;if(37==next&&(input.advance(),input.acceptToken(1)),isAlpha(next)){do{input.advance()}while(isAlpha(input.next));input.acceptToken(1)}}})),cssHighlighting=styleTags({"AtKeyword import charset namespace keyframes media supports":tags$1.definitionKeyword,"from to selector":tags$1.keyword,NamespaceName:tags$1.namespace,KeyframeName:tags$1.labelName,KeyframeRangeName:tags$1.operatorKeyword,TagName:tags$1.tagName,ClassName:tags$1.className,PseudoClassName:tags$1.constant(tags$1.className),IdName:tags$1.labelName,"FeatureName PropertyName":tags$1.propertyName,AttributeName:tags$1.attributeName,NumberLiteral:tags$1.number,KeywordQuery:tags$1.keyword,UnaryQueryOp:tags$1.operatorKeyword,"CallTag ValueName":tags$1.atom,VariableName:tags$1.variableName,Callee:tags$1.operatorKeyword,Unit:tags$1.unit,"UniversalSelector NestingSelector":tags$1.definitionOperator,MatchOp:tags$1.compareOperator,"ChildOp SiblingOp, LogicOp":tags$1.logicOperator,BinOp:tags$1.arithmeticOperator,Important:tags$1.modifier,Comment:tags$1.blockComment,ColorLiteral:tags$1.color,"ParenthesizedContent StringLiteral":tags$1.string,":":tags$1.punctuation,"PseudoOp #":tags$1.derefOperator,"; ,":tags$1.separator,"( )":tags$1.paren,"[ ]":tags$1.squareBracket,"{ }":tags$1.brace}),spec_callee={__proto__:null,lang:32,"nth-child":32,"nth-last-child":32,"nth-of-type":32,"nth-last-of-type":32,dir:32,"host-context":32,url:60,"url-prefix":60,domain:60,regexp:60,selector:134},spec_AtKeyword={__proto__:null,"@import":114,"@media":138,"@charset":142,"@namespace":146,"@keyframes":152,"@supports":164},spec_identifier$1={__proto__:null,not:128,only:128},parser$1=LRParser.deserialize({version:14,states:"9bQYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#ChO$qQ[O'#DPO$vQ[O'#DTOOQP'#Ej'#EjO${QdO'#DeO%gQ[O'#DrO${QdO'#DtO%xQ[O'#DvO&TQ[O'#DyO&]Q[O'#EPO&kQ[O'#EROOQS'#Ei'#EiOOQS'#EU'#EUQYQ[OOO&rQXO'#CdO'gQWO'#DaO'lQWO'#EpO'wQ[O'#EpQOQWOOP(RO#tO'#C_POOO)C@X)C@XOOQP'#Cg'#CgOOQP,59Q,59QO#kQ[O,59QO(^Q[O'#EXO(xQWO,58{O)QQ[O,59SO$qQ[O,59kO$vQ[O,59oO(^Q[O,59sO(^Q[O,59uO(^Q[O,59vO)]Q[O'#D`OOQS,58{,58{OOQP'#Ck'#CkOOQO'#C}'#C}OOQP,59S,59SO)dQWO,59SO)iQWO,59SOOQP'#DR'#DROOQP,59k,59kOOQO'#DV'#DVO)nQ`O,59oOOQS'#Cp'#CpO${QdO'#CqO)vQvO'#CsO+TQtO,5:POOQO'#Cx'#CxO)iQWO'#CwO+iQW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Gj#c;'S%^;'S;=`%o<%lO%^bGoUo`Oy%^z#W%^#W#XHR#X;'S%^;'S;=`%o<%lO%^bHYS!`Qo`Oy%^z;'S%^;'S;=`%o<%lO%^bHiUOy%^z#f%^#f#gHR#g;'S%^;'S;=`%o<%lO%^fIQS!RUOy%^z;'S%^;'S;=`%o<%lO%^nIcS!Q^Oy%^z;'S%^;'S;=`%o<%lO%^fItU!PQOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^`JZP;=`<%l$}",tokenizers:[descendant,unitToken,identifiers,1,2,3,4,new LocalTokenGroup("m~RRYZ[z{a~~g~aO#Z~~dP!P!Qg~lO#[~~",28,102)],topRules:{StyleSheet:[0,4],Styles:[1,84]},specialized:[{term:97,get:value=>spec_callee[value]||-1},{term:56,get:value=>spec_AtKeyword[value]||-1},{term:98,get:value=>spec_identifier$1[value]||-1}],tokenPrec:1169});let _properties=null;function properties(){if(!_properties&&"object"==typeof document&&document.body){let{style:style}=document.body,names=[],seen=new Set;for(let prop in style)"cssText"!=prop&&"cssFloat"!=prop&&"string"==typeof style[prop]&&(/[A-Z]/.test(prop)&&(prop=prop.replace(/[A-Z]/g,(ch=>"-"+ch.toLowerCase()))),seen.has(prop)||(names.push(prop),seen.add(prop)));_properties=names.sort().map((name=>({type:"property",label:name})))}return _properties||[]}const pseudoClasses=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map((name=>({type:"class",label:name}))),values=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map((name=>({type:"keyword",label:name}))).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map((name=>({type:"constant",label:name})))),tags=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map((name=>({type:"type",label:name}))),identifier$1=/^(\w[\w-]*|-\w[\w-]*|)$/,variable=/^-(-[\w-]*)?$/;const VariablesByNode=new NodeWeakMap,declSelector=["Declaration"];function astTop(node){for(let cur=node;;){if(cur.type.isTop)return cur;if(!(cur=cur.parent))return node}}function variableNames(doc,node,isVariable){if(node.to-node.from>4096){let known=VariablesByNode.get(node);if(known)return known;let result=[],seen=new Set,cursor=node.cursor(IterMode.IncludeAnonymous);if(cursor.firstChild())do{for(let option of variableNames(doc,cursor.node,isVariable))seen.has(option.label)||(seen.add(option.label),result.push(option))}while(cursor.nextSibling());return VariablesByNode.set(node,result),result}{let result=[],seen=new Set;return node.cursor().iterate((node=>{var _a;if(isVariable(node)&&node.matchContext(declSelector)&&":"==(null===(_a=node.node.nextSibling)||void 0===_a?void 0:_a.name)){let name=doc.sliceString(node.from,node.to);seen.has(name)||(seen.add(name),result.push({label:name,type:"variable"}))}})),result}}const cssCompletionSource=(isVariable=n=>"VariableName"==n.name,context=>{let{state:state,pos:pos}=context,node=syntaxTree(state).resolveInner(pos,-1),isDash=node.type.isError&&node.from==node.to-1&&"-"==state.doc.sliceString(node.from,node.to);if("PropertyName"==node.name||(isDash||"TagName"==node.name)&&/^(Block|Styles)$/.test(node.resolve(node.to).name))return{from:node.from,options:properties(),validFor:identifier$1};if("ValueName"==node.name)return{from:node.from,options:values,validFor:identifier$1};if("PseudoClassName"==node.name)return{from:node.from,options:pseudoClasses,validFor:identifier$1};if(isVariable(node)||(context.explicit||isDash)&&function(node,doc){var _a;if(("("==node.name||node.type.isError)&&(node=node.parent||node),"ArgList"!=node.name)return!1;let callee=null===(_a=node.parent)||void 0===_a?void 0:_a.firstChild;return"Callee"==(null==callee?void 0:callee.name)&&"var"==doc.sliceString(callee.from,callee.to)}(node,state.doc))return{from:isVariable(node)||isDash?node.from:pos,options:variableNames(state.doc,astTop(node),isVariable),validFor:variable};if("TagName"==node.name){for(let{parent:parent}=node;parent;parent=parent.parent)if("Block"==parent.name)return{from:node.from,options:properties(),validFor:identifier$1};return{from:node.from,options:tags,validFor:identifier$1}}if(!context.explicit)return null;let above=node.resolve(pos),before=above.childBefore(pos);return before&&":"==before.name&&"PseudoClassSelector"==above.name?{from:pos,options:pseudoClasses,validFor:identifier$1}:before&&":"==before.name&&"Declaration"==above.name||"ArgList"==above.name?{from:pos,options:values,validFor:identifier$1}:"Block"==above.name||"Styles"==above.name?{from:pos,options:properties(),validFor:identifier$1}:null});var isVariable;const cssLanguage=LRLanguage.define({name:"css",parser:parser$1.configure({props:[indentNodeProp.add({Declaration:continuedIndent()}),foldNodeProp.add({Block:foldInside})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function css(){return new LanguageSupport(cssLanguage,cssLanguage.data.of({autocomplete:cssCompletionSource}))}const space=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],trackNewline=new ContextTracker({start:!1,shift:(context,term)=>3==term||4==term||306==term?context:307==term,strict:!1}),insertSemicolon=new ExternalTokenizer(((input,stack)=>{let{next:next}=input;(125==next||-1==next||stack.context)&&input.acceptToken(304)}),{contextual:!0,fallback:!0}),noSemicolon=new ExternalTokenizer(((input,stack)=>{let after,{next:next}=input;space.indexOf(next)>-1||(47!=next||47!=(after=input.peek(1))&&42!=after)&&(125==next||59==next||-1==next||stack.context||input.acceptToken(303))}),{contextual:!0}),incdecToken=new ExternalTokenizer(((input,stack)=>{let{next:next}=input;if((43==next||45==next)&&(input.advance(),next==input.next)){input.advance();let mayPostfix=!stack.context&&stack.canShift(1);input.acceptToken(mayPostfix?1:2)}}),{contextual:!0}),jsHighlight=styleTags({"get set async static":tags$1.modifier,"for while do if else switch try catch finally return throw break continue default case":tags$1.controlKeyword,"in of await yield void typeof delete instanceof":tags$1.operatorKeyword,"let var const function class extends":tags$1.definitionKeyword,"import export from":tags$1.moduleKeyword,"with debugger as new":tags$1.keyword,TemplateString:tags$1.special(tags$1.string),super:tags$1.atom,BooleanLiteral:tags$1.bool,this:tags$1.self,null:tags$1.null,Star:tags$1.modifier,VariableName:tags$1.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":tags$1.function(tags$1.variableName),VariableDefinition:tags$1.definition(tags$1.variableName),Label:tags$1.labelName,PropertyName:tags$1.propertyName,PrivatePropertyName:tags$1.special(tags$1.propertyName),"CallExpression/MemberExpression/PropertyName":tags$1.function(tags$1.propertyName),"FunctionDeclaration/VariableDefinition":tags$1.function(tags$1.definition(tags$1.variableName)),"ClassDeclaration/VariableDefinition":tags$1.definition(tags$1.className),PropertyDefinition:tags$1.definition(tags$1.propertyName),PrivatePropertyDefinition:tags$1.definition(tags$1.special(tags$1.propertyName)),UpdateOp:tags$1.updateOperator,LineComment:tags$1.lineComment,BlockComment:tags$1.blockComment,Number:tags$1.number,String:tags$1.string,Escape:tags$1.escape,ArithOp:tags$1.arithmeticOperator,LogicOp:tags$1.logicOperator,BitOp:tags$1.bitwiseOperator,CompareOp:tags$1.compareOperator,RegExp:tags$1.regexp,Equals:tags$1.definitionOperator,Arrow:tags$1.function(tags$1.punctuation),": Spread":tags$1.punctuation,"( )":tags$1.paren,"[ ]":tags$1.squareBracket,"{ }":tags$1.brace,"InterpolationStart InterpolationEnd":tags$1.special(tags$1.brace),".":tags$1.derefOperator,", ;":tags$1.separator,"@":tags$1.meta,TypeName:tags$1.typeName,TypeDefinition:tags$1.definition(tags$1.typeName),"type enum interface implements namespace module declare":tags$1.definitionKeyword,"abstract global Privacy readonly override":tags$1.modifier,"is keyof unique infer":tags$1.operatorKeyword,JSXAttributeValue:tags$1.attributeValue,JSXText:tags$1.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":tags$1.angleBracket,"JSXIdentifier JSXNameSpacedName":tags$1.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":tags$1.attributeName,"JSXBuiltin/JSXIdentifier":tags$1.standard(tags$1.tagName)}),spec_identifier={__proto__:null,export:14,as:19,from:27,default:30,async:35,function:36,extends:46,this:50,true:58,false:58,null:70,void:74,typeof:78,super:96,new:130,delete:146,yield:155,await:159,class:164,public:221,private:221,protected:221,readonly:223,instanceof:242,satisfies:245,in:246,const:248,import:280,keyof:335,unique:339,infer:345,is:381,abstract:401,implements:403,type:405,let:408,var:410,using:413,interface:419,enum:423,namespace:429,module:431,declare:435,global:439,for:458,of:467,while:470,with:474,do:478,if:482,else:484,switch:488,case:494,try:500,catch:504,finally:508,return:512,throw:516,break:520,continue:524,debugger:528},spec_word={__proto__:null,async:117,get:119,set:121,declare:181,public:183,private:183,protected:183,static:185,abstract:187,override:189,readonly:195,accessor:197,new:385},spec_LessThan={__proto__:null,"<":137},parser=LRParser.deserialize({version:14,states:"$6tO`QUOOO%TQUOOO'WQWOOP(eOSOOO*sQ(CjO'#CfO*zOpO'#CgO+YO!bO'#CgO+hO07`O'#DZO-yQUO'#DaO.ZQUO'#DlO%TQUO'#DvO0_QUO'#EOOOQ(CY'#EW'#EWO0xQSO'#ETOOQO'#Ei'#EiOOQO'#Ic'#IcO1QQSO'#GkO1]QSO'#EhO1bQSO'#EhO3dQ(CjO'#JdO6TQ(CjO'#JeO6qQSO'#FWO6vQ#tO'#FoOOQ(CY'#F`'#F`O7RO&jO'#F`O7aQ,UO'#FvO8wQSO'#FuOOQ(CY'#Je'#JeOOQ(CW'#Jd'#JdO8|QSO'#GoOOQQ'#KP'#KPO9XQSO'#IPO9^Q(C[O'#IQOOQQ'#JQ'#JQOOQQ'#IU'#IUQ`QUOOO%TQUO'#DnO9fQUO'#DzO9mQUO'#D|O9SQSO'#GkO9tQ,UO'#ClO:SQSO'#EgO:_QSO'#ErO:dQ,UO'#F_O;RQSO'#GkOOQO'#KQ'#KQO;WQSO'#KQO;fQSO'#GsO;fQSO'#GtO;fQSO'#GvO9SQSO'#GyO<]QSO'#G|O=tQSO'#CbO>UQSO'#HYO>^QSO'#H`O>^QSO'#HbO`QUO'#HdO>^QSO'#HfO>^QSO'#HiO>cQSO'#HoO>hQ(C]O'#HuO%TQUO'#HwO>sQ(C]O'#HyO?OQ(C]O'#H{O9^Q(C[O'#H}O?ZQ(CjO'#CfO@]QWO'#DfQOQSOOO%TQUO'#D|O@sQSO'#EPO9tQ,UO'#EgOAOQSO'#EgOAZQ`O'#F_OOQQ'#Cd'#CdOOQ(CW'#Dk'#DkOOQ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!V&iT&g!V&iT1h,f1i",nodeNames:"⚠ ArithOp ArithOp LineComment BlockComment Script ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:366,context:trackNewline,nodeProps:[["group",-26,6,14,16,62,199,203,207,208,210,213,216,226,228,234,236,238,240,243,249,255,257,259,261,263,265,266,"Statement",-32,10,11,25,28,29,35,45,48,49,51,56,64,72,76,78,80,81,103,104,113,114,131,134,136,137,138,139,141,142,162,163,165,"Expression",-23,24,26,30,34,36,38,166,168,170,171,173,174,175,177,178,179,181,182,183,193,195,197,198,"Type",-3,84,96,102,"ClassItem"],["openedBy",31,"InterpolationStart",50,"[",54,"{",69,"(",143,"JSXStartTag",155,"JSXStartTag JSXStartCloseTag"],["closedBy",33,"InterpolationEnd",44,"]",55,"}",70,")",144,"JSXSelfCloseEndTag JSXEndTag",160,"JSXEndTag"]],propSources:[jsHighlight],skippedNodes:[0,3,4,269],repeatNodeCount:33,tokenData:"$>y(CSR!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tu>PuvBavwDxwxGgxyMvyz! Qz{!![{|!%O|}!&]}!O!%O!O!P!'g!P!Q!1w!Q!R#0t!R![#3T![!]#@T!]!^#Aa!^!_#Bk!_!`#GS!`!a#In!a!b#N{!b!c$$z!c!}>P!}#O$&U#O#P$'`#P#Q$,w#Q#R$.R#R#S>P#S#T$/`#T#o$0j#o#p$4z#p#q$5p#q#r$7Q#r#s$8^#s$f%Z$f$g+g$g#BY>P#BY#BZ$9h#BZ$IS>P$IS$I_$9h$I_$I|>P$I|$I}$P$JT$JU$9h$JU$KV>P$KV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#BY#BZ$9h#BZ$IS>P$IS$I_$9h$I_$JT>P$JT$JU$9h$JU$KV>P$KV$KW$9h$KW&FU>P&FU&FV$9h&FV;'S>P;'S;=`BZ<%l?HT>P?HT?HU$9h?HUO>P(CS$=Uk$d&j'xp'{!b'o(;d(V!LY'u&;d$W#tOY%ZYZ&cZr%Zrs&}st%Ztu>Puw%Zwx(rx}%Z}!O@T!O!Q%Z!Q![>P![!^%Z!^!_*g!_!c%Z!c!}>P!}#O%Z#O#P&c#P#R%Z#R#S>P#S#T%Z#T#o>P#o#p*g#p$g%Z$g;'S>P;'S;=`BZ<%lO>P",tokenizers:[noSemicolon,incdecToken,2,3,4,5,6,7,8,9,10,11,12,13,insertSemicolon,new LocalTokenGroup("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOq~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!O~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(U~~",141,327),new LocalTokenGroup("j~RQYZXz{^~^O'r~~aP!P!Qd~iO's~~",25,309)],topRules:{Script:[0,5],SingleExpression:[1,267],SingleClassItem:[2,268]},dialects:{jsx:12810,ts:12812},dynamicPrecedences:{76:1,78:1,163:1,191:1},specialized:[{term:313,get:value=>spec_identifier[value]||-1},{term:329,get:value=>spec_word[value]||-1},{term:67,get:value=>spec_LessThan[value]||-1}],tokenPrec:12836}),snippets=[snippetCompletion("function ${name}(${params}) {\n\t${}\n}",{label:"function",detail:"definition",type:"keyword"}),snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}",{label:"for",detail:"loop",type:"keyword"}),snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}",{label:"for",detail:"of loop",type:"keyword"}),snippetCompletion("do {\n\t${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),snippetCompletion("while (${}) {\n\t${}\n}",{label:"while",detail:"loop",type:"keyword"}),snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}",{label:"try",detail:"/ catch block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n}",{label:"if",detail:"block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}",{label:"if",detail:"/ else block",type:"keyword"}),snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}",{label:"class",detail:"definition",type:"keyword"}),snippetCompletion('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),snippetCompletion('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],cache=new NodeWeakMap,ScopeNodes=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function defID(type){return(node,def)=>{let id=node.node.getChild("VariableDefinition");return id&&def(id,type),!0}}const functionContext=["FunctionDeclaration"],gatherCompletions={FunctionDeclaration:defID("function"),ClassDeclaration:defID("class"),ClassExpression:()=>!0,EnumDeclaration:defID("constant"),TypeAliasDeclaration:defID("type"),NamespaceDeclaration:defID("namespace"),VariableDefinition(node,def){node.matchContext(functionContext)||def(node,"variable")},TypeDefinition(node,def){def(node,"type")},__proto__:null};function getScope(doc,node){let cached=cache.get(node);if(cached)return cached;let completions=[],top=!0;function def(node,type){let name=doc.sliceString(node.from,node.to);completions.push({label:name,type:type})}return node.cursor(IterMode.IncludeAnonymous).iterate((node=>{if(top)top=!1;else if(node.name){let gather=gatherCompletions[node.name];if(gather&&gather(node,def)||ScopeNodes.has(node.name))return!1}else if(node.to-node.from>8192){for(let c of getScope(doc,node.node))completions.push(c);return!1}})),cache.set(node,completions),completions}const Identifier=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,dontComplete=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function localCompletionSource(context){let inner=syntaxTree(context.state).resolveInner(context.pos,-1);if(dontComplete.indexOf(inner.name)>-1)return null;let isWord="VariableName"==inner.name||inner.to-inner.from<20&&Identifier.test(context.state.sliceDoc(inner.from,inner.to));if(!isWord&&!context.explicit)return null;let options=[];for(let pos=inner;pos;pos=pos.parent)ScopeNodes.has(pos.name)&&(options=options.concat(getScope(context.state.doc,pos)));return{options:options,from:isWord?inner.from:context.pos,validFor:Identifier}}const javascriptLanguage=LRLanguage.define({name:"javascript",parser:parser.configure({props:[indentNodeProp.add({IfStatement:continuedIndent({except:/^\s*({|else\b)/}),TryStatement:continuedIndent({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:context=>context.baseIndent,SwitchBody:context=>{let after=context.textAfter,closed=/^\s*\}/.test(after),isCase=/^\s*(case|default)\b/.test(after);return context.baseIndent+(closed?0:isCase?1:2)*context.unit},Block:function(_ref8){let{closing:closing,align:align=!0,units:units=1}=_ref8;return context=>delimitedStrategy(context,align,units,closing)}({closing:"}"}),ArrowFunction:cx=>cx.baseIndent+cx.unit,"TemplateString BlockComment":()=>null,"Statement Property":continuedIndent({except:/^{/}),JSXElement(context){let closed=/^\s*<\//.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},JSXEscape(context){let closed=/\s*\}/.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},"JSXOpenTag JSXSelfClosingTag":context=>context.column(context.node.from)+context.unit}),foldNodeProp.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":foldInside,BlockComment:tree=>({from:tree.from+2,to:tree.to-2})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),jsxSublanguage={test:node=>/^JSX/.test(node.name),facet:defineLanguageFacet({commentTokens:{block:{open:"{/*",close:"*/}"}}})},typescriptLanguage=javascriptLanguage.configure({dialect:"ts"},"typescript"),jsxLanguage=javascriptLanguage.configure({dialect:"jsx",props:[sublanguageProp.add((n=>n.isTop?[jsxSublanguage]:void 0))]}),tsxLanguage=javascriptLanguage.configure({dialect:"jsx ts",props:[sublanguageProp.add((n=>n.isTop?[jsxSublanguage]:void 0))]},"typescript"),keywords="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map((kw=>({label:kw,type:"keyword"})));function javascript(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},lang=config.jsx?config.typescript?tsxLanguage:jsxLanguage:config.typescript?typescriptLanguage:javascriptLanguage;return new LanguageSupport(lang,[javascriptLanguage.data.of({autocomplete:ifNotIn(dontComplete,completeFromList(snippets.concat(keywords)))}),javascriptLanguage.data.of({autocomplete:localCompletionSource}),config.jsx?autoCloseTags$1:[]])}function elementName$1(doc,tree){let max=arguments.length>2&&void 0!==arguments[2]?arguments[2]:doc.length;for(let ch=null==tree?void 0:tree.firstChild;ch;ch=ch.nextSibling)if("JSXIdentifier"==ch.name||"JSXBuiltin"==ch.name||"JSXNamespacedName"==ch.name||"JSXMemberExpression"==ch.name)return doc.sliceString(ch.from,Math.min(ch.to,max));return""}const android="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),autoCloseTags$1=EditorView.inputHandler.of(((view,from,to,text)=>{if((android?view.composing:view.compositionStarted)||view.state.readOnly||from!=to||">"!=text&&"/"!=text||!javascriptLanguage.isActiveAt(view.state,from,-1))return!1;let{state:state}=view,changes=state.changeByRange((range=>{var _a;let name,{head:head}=range,around=syntaxTree(state).resolveInner(head,-1);if("JSXStartTag"==around.name&&(around=around.parent),"JSXAttributeValue"==around.name&&around.to>head);else{if(">"==text&&"JSXFragmentTag"==around.name)return{range:EditorSelection.cursor(head+1),changes:{from:head,insert:">"}};if("/"==text&&"JSXFragmentTag"==around.name){let empty=around.parent,base=null==empty?void 0:empty.parent;if(empty.from==head-1&&"JSXEndTag"!=(null===(_a=base.lastChild)||void 0===_a?void 0:_a.name)&&(name=elementName$1(state.doc,null==base?void 0:base.firstChild,head))){let insert="/".concat(name,">");return{range:EditorSelection.cursor(head+insert.length),changes:{from:head,insert:insert}}}}else if(">"==text){let openTag=function(node){for(;;){if("JSXOpenTag"==node.name||"JSXSelfClosingTag"==node.name||"JSXFragmentTag"==node.name)return node;if("JSXEscape"==node.name||!node.parent)return null;node=node.parent}}(around);if(openTag&&(!(node=openTag.lastChild)||"JSXEndTag"!=node.name&&"JSXSelfCloseEndTag"!=node.name)&&"")}}}}var node;return{range:range}}));return!changes.changes.empty&&(view.dispatch(changes,{userEvent:"input.type",scrollIntoView:!0}),!0)})),Targets=["_blank","_self","_top","_parent"],Charsets=["ascii","utf-8","utf-16","latin1","latin1"],Methods=["get","post","put","delete"],Encs=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],Bool=["true","false"],S={},Tags={a:{attrs:{href:null,ping:null,type:null,media:null,target:Targets,hreflang:null}},abbr:S,address:S,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:S,aside:S,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:S,base:{attrs:{href:null,target:Targets}},bdi:S,bdo:S,blockquote:{attrs:{cite:null}},body:S,br:S,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:S,center:S,cite:S,code:S,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:S,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:S,div:S,dl:S,dt:S,em:S,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:S,figure:S,footer:S,form:{attrs:{action:null,name:null,"accept-charset":Charsets,autocomplete:["on","off"],enctype:Encs,method:Methods,novalidate:["novalidate"],target:Targets}},h1:S,h2:S,h3:S,h4:S,h5:S,h6:S,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:S,hgroup:S,hr:S,html:{attrs:{manifest:null}},i:S,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:S,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:S,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:S,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Charsets,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:S,noscript:S,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:S,param:{attrs:{name:null,value:null}},pre:S,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:S,rt:S,ruby:S,samp:S,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Charsets}},section:S,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:S,source:{attrs:{src:null,type:null,media:null}},span:S,strong:S,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:S,summary:S,sup:S,table:S,tbody:S,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:S,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:S,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:S,time:{attrs:{datetime:null}},title:S,tr:S,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:S,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:S},GlobalAttrs={accesskey:null,class:null,contenteditable:Bool,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:Bool,autocorrect:Bool,autocapitalize:Bool,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":Bool,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Bool,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Bool,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Bool,"aria-hidden":Bool,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Bool,"aria-multiselectable":Bool,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Bool,"aria-relevant":null,"aria-required":Bool,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},eventAttributes="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map((n=>"on"+n));for(let a of eventAttributes)GlobalAttrs[a]=null;class Schema{constructor(extraTags,extraAttrs){this.tags=Object.assign(Object.assign({},Tags),extraTags),this.globalAttrs=Object.assign(Object.assign({},GlobalAttrs),extraAttrs),this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}function elementName(doc,tree){let max=arguments.length>2&&void 0!==arguments[2]?arguments[2]:doc.length;if(!tree)return"";let tag=tree.firstChild,name=tag&&tag.getChild("TagName");return name?doc.sliceString(name.from,Math.min(name.to,max)):""}function findParentElement(tree){let skip=arguments.length>1&&void 0!==arguments[1]&&arguments[1];for(;tree;tree=tree.parent)if("Element"==tree.name){if(!skip)return tree;skip=!1}return null}function allowedChildren(doc,tree,schema){let parentInfo=schema.tags[elementName(doc,findParentElement(tree))];return(null==parentInfo?void 0:parentInfo.children)||schema.allTags}function openTags(doc,tree){let open=[];for(let parent=findParentElement(tree);parent&&!parent.type.isTop;parent=findParentElement(parent.parent)){let tagName=elementName(doc,parent);if(tagName&&"CloseTag"==parent.lastChild.name)break;tagName&&open.indexOf(tagName)<0&&("EndTag"==tree.name||tree.from>=parent.firstChild.to)&&open.push(tagName)}return open}Schema.default=new Schema;const identifier=/^[:\-\.\w\u00b7-\uffff]*$/;function completeTag(state,schema,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">",parent=findParentElement(tree,!0);return{from:from,to:to,options:allowedChildren(state.doc,parent,schema).map((tagName=>({label:tagName,type:"type"}))).concat(openTags(state.doc,tree).map(((tag,i)=>({label:"/"+tag,apply:"/"+tag+end,type:"type",boost:99-i})))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function completeCloseTag(state,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">";return{from:from,to:to,options:openTags(state.doc,tree).map(((tag,i)=>({label:tag,apply:tag+end,type:"type",boost:99-i}))),validFor:identifier}}function htmlCompletionFor(schema,context){let{state:state,pos:pos}=context,tree=syntaxTree(state).resolveInner(pos,-1),around=tree.resolve(pos);for(let before,scan=pos;around==tree&&(before=tree.childBefore(scan));){let last=before.lastChild;if(!last||!last.type.isError||last.from({label:attrName,type:"property"}))),validFor:identifier}}(state,schema,tree,"AttributeName"==tree.name?tree.from:pos,pos):"Is"==tree.name||"AttributeValue"==tree.name||"UnquotedAttributeValue"==tree.name?function(state,schema,tree,from,to){var _a;let token,nameNode=null===(_a=tree.parent)||void 0===_a?void 0:_a.getChild("AttributeName"),options=[];if(nameNode){let attrName=state.sliceDoc(nameNode.from,nameNode.to),attrs=schema.globalAttrs[attrName];if(!attrs){let elt=findParentElement(tree),info=elt?schema.tags[elementName(state.doc,elt)]:null;attrs=(null==info?void 0:info.attrs)&&info.attrs[attrName]}if(attrs){let base=state.sliceDoc(from,to).toLowerCase(),quoteStart='"',quoteEnd='"';/^['"]/.test(base)?(token='"'==base[0]?/^[^"]*$/:/^[^']*$/,quoteStart="",quoteEnd=state.sliceDoc(to,to+1)==base[0]?"":base[0],base=base.slice(1),from++):token=/^[^\s<>='"]*$/;for(let value of attrs)options.push({label:value,apply:quoteStart+value+quoteEnd,type:"constant"})}}return{from:from,to:to,options:options,validFor:token}}(state,schema,tree,"Is"==tree.name?pos:tree.from,pos):!context.explicit||"Element"!=around.name&&"Text"!=around.name&&"Document"!=around.name?null:function(state,schema,tree,pos){let options=[],level=0;for(let tagName of allowedChildren(state.doc,tree,schema))options.push({label:"<"+tagName,type:"type"});for(let open of openTags(state.doc,tree))options.push({label:"",type:"type",boost:99-level++});return{from:pos,to:pos,options:options,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}(state,schema,tree,pos)}function htmlCompletionSourceWith(config){let{extraTags:extraTags,extraGlobalAttributes:extraAttrs}=config,schema=extraAttrs||extraTags?new Schema(extraTags,extraAttrs):Schema.default;return context=>htmlCompletionFor(schema,context)}const jsonParser=javascriptLanguage.parser.configure({top:"SingleExpression"}),defaultNesting=[{tag:"script",attrs:attrs=>"text/typescript"==attrs.type||"ts"==attrs.lang,parser:typescriptLanguage.parser},{tag:"script",attrs:attrs=>"text/babel"==attrs.type||"text/jsx"==attrs.type,parser:jsxLanguage.parser},{tag:"script",attrs:attrs=>"text/typescript-jsx"==attrs.type,parser:tsxLanguage.parser},{tag:"script",attrs:attrs=>/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(attrs.type),parser:jsonParser},{tag:"script",attrs:attrs=>!attrs.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(attrs.type),parser:javascriptLanguage.parser},{tag:"style",attrs:attrs=>(!attrs.lang||"css"==attrs.lang)&&(!attrs.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(attrs.type)),parser:cssLanguage.parser}],defaultAttrs=[{name:"style",parser:cssLanguage.parser.configure({top:"Styles"})}].concat(eventAttributes.map((name=>({name:name,parser:javascriptLanguage.parser})))),htmlPlain=LRLanguage.define({name:"html",parser:parser$2.configure({props:[indentNodeProp.add({Element(context){let after=/^(\s*)(<\/)?/.exec(context.textAfter);return context.node.to<=context.pos+after[0].length?context.continue():context.lineIndent(context.node.from)+(after[2]?0:context.unit)},"OpenTag CloseTag SelfClosingTag":context=>context.column(context.node.from)+context.unit,Document(context){if(context.pos+/\s*/.exec(context.textAfter)[0].lengthnode.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"\x3c!--",close:"--\x3e"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-._"}}),htmlLanguage=htmlPlain.configure({wrap:configureNesting(defaultNesting,defaultAttrs)});const selfClosers=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),autoCloseTags=EditorView.inputHandler.of(((view,from,to,text,insertTransaction)=>{if(view.composing||view.state.readOnly||from!=to||">"!=text&&"/"!=text||!htmlLanguage.isActiveAt(view.state,from,-1))return!1;let base=insertTransaction(),{state:state}=base,closeTags=state.changeByRange((range=>{var _a,_b,_c;let name,didType=state.doc.sliceString(range.from-1,range.to)==text,{head:head}=range,after=syntaxTree(state).resolveInner(head,-1);if(didType&&">"==text&&"EndTag"==after.name){let tag=after.parent;if("CloseTag"!=(null===(_b=null===(_a=tag.parent)||void 0===_a?void 0:_a.lastChild)||void 0===_b?void 0:_b.name)&&(name=elementName(state.doc,tag.parent,head))&&!selfClosers.has(name)){return{range:range,changes:{from:head,to:head+(">"===state.doc.sliceString(head,head+1)?1:0),insert:"")}}}}else if(didType&&"/"==text&&"IncompleteCloseTag"==after.name){let tag=after.parent;if(after.from==head-2&&"CloseTag"!=(null===(_c=tag.lastChild)||void 0===_c?void 0:_c.name)&&(name=elementName(state.doc,tag,head))&&!selfClosers.has(name)){let to=head+(">"===state.doc.sliceString(head,head+1)?1:0),insert="".concat(name,">");return{range:EditorSelection.cursor(head+insert.length,-1),changes:{from:head,to:to,insert:insert}}}}return{range:range}}));return!closeTags.changes.empty&&(view.dispatch([base,state.update(closeTags,{userEvent:"input.complete",scrollIntoView:!0})]),!0)})),cm6proDark=[EditorView.theme({"&":{color:"#cccccc",backgroundColor:"#1f1f1f"},".cm-content":{caretColor:"#4d4d4d"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"#4d4d4d"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"#3d3d3d"},".cm-panels":{backgroundColor:"#1f1f1f",color:"#4d4d4d"},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#2e2e2e"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:"1px solid ".concat("#eee8d5")},".cm-gutters":{backgroundColor:"#1f1f1f",color:"#808080",border:"none"},".cm-activeLineGutter":{backgroundColor:"#2e2e2e"},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:"#1a1a1a"},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:"#1a1a1a",borderBottomColor:"#1a1a1a"},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:"#2e2e2e",color:"#4d4d4d"}}},{dark:!0}),syntaxHighlighting(HighlightStyle.define([{tag:tags$1.keyword,color:"#a7bf06"},{tag:[tags$1.name,tags$1.deleted,tags$1.character,tags$1.propertyName,tags$1.macroName],color:"#569cd6"},{tag:[tags$1.variableName],color:"#cccccc"},{tag:[tags$1.function(tags$1.variableName)],color:"#268bd2"},{tag:[tags$1.labelName],color:"#d33682"},{tag:[tags$1.color,tags$1.constant(tags$1.name),tags$1.standard(tags$1.name)],color:"#d1a008"},{tag:[tags$1.definition(tags$1.name),tags$1.separator],color:"#569cd6"},{tag:[tags$1.brace],color:"#d33682"},{tag:[tags$1.annotation],color:"#d30102"},{tag:[tags$1.number,tags$1.changed,tags$1.annotation,tags$1.modifier,tags$1.self,tags$1.namespace],color:"#d33682"},{tag:[tags$1.typeName,tags$1.className],color:"#cb4b16"},{tag:[tags$1.operator,tags$1.operatorKeyword],color:"#7e83e6"},{tag:[tags$1.tagName],color:"#268bd2"},{tag:[tags$1.squareBracket],color:"#dc322f"},{tag:[tags$1.angleBracket],color:"#808080"},{tag:[tags$1.attributeName],color:"#569cd6"},{tag:[tags$1.regexp],color:"#d30102"},{tag:[tags$1.quote],color:"#a7bf06"},{tag:[tags$1.string],color:"#d1a008"},{tag:tags$1.link,color:"#569cd6",textDecoration:"underline",textUnderlinePosition:"under"},{tag:[tags$1.url,tags$1.escape,tags$1.special(tags$1.string)],color:"#d1a008"},{tag:[tags$1.meta],color:"#dc322f"},{tag:[tags$1.comment],color:"#638e50",fontStyle:"italic"},{tag:tags$1.strong,fontWeight:"bold",color:"#eee8d5"},{tag:tags$1.emphasis,fontStyle:"italic",color:"#a7bf06"},{tag:tags$1.strikethrough,textDecoration:"line-through"},{tag:tags$1.heading,fontWeight:"bold",color:"#d1a008"},{tag:tags$1.heading1,fontWeight:"bold",color:"#fdf6e3"},{tag:[tags$1.heading2,tags$1.heading3,tags$1.heading4],fontWeight:"bold",color:"#eee8d5"},{tag:[tags$1.heading5,tags$1.heading6],color:"#eee8d5"},{tag:[tags$1.atom,tags$1.bool,tags$1.special(tags$1.variableName)],color:"#d33682"},{tag:[tags$1.processingInstruction,tags$1.inserted,tags$1.contentSeparator],color:"#dc322f"},{tag:[tags$1.contentSeparator],color:"#d1a008"},{tag:tags$1.invalid,color:"#dc322f",borderBottom:"1px dotted ".concat("#dc322f")}]))],CONFIG={strict:!1,tab_size:2},hasHtml=content=>/<(?[A-Za-z]+\b)[^>]*(?:.|\n)*?<\/{1}\k>/.test(content),mergeObjects=(current,updates)=>{if(!current||!updates)throw new Error("Both 'current' and 'updates' must be passed-in to merge()");if("object"!=typeof current||"object"!=typeof updates||Array.isArray(current)||Array.isArray(updates))throw new Error("Both 'current' and 'updates' must be passed-in as objects to merge()");let merged={...current};for(let key of Object.keys(updates))"object"!=typeof updates[key]?merged[key]=updates[key]:merged[key]=mergeObjects(merged[key]||{},updates[key]);return merged},validateConfig=config=>{if("object"!=typeof config)throw"Config must be an object.";if(!(Object.hasOwn(config,"tab_size")||Object.hasOwn(config,"strict")))return CONFIG;let tab_size=config.tab_size;if(tab_size){if("number"!=typeof tab_size)throw"Tab size must be a number.";if(!Number.isSafeInteger(tab_size))throw"Tab size ".concat(tab_size," is not safe. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger for more info.");if(tab_size=Math.floor(tab_size),tab_size<1||tab_size>16)throw"Tab size out of range. Expecting 1 to 16.";config.tab_size=tab_size}if(Object.hasOwn(config,"strict")&&"boolean"!=typeof config.strict)throw"Strict config must be a boolean.";return((dconfig,config)=>mergeObjects(structuredClone(dconfig),config))(CONFIG,config)},void_elements=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],entify=function(html){let minify=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return html=(html=(html=html.replace(/(]*>)\n+/g,"$1").replace(/(]*>)\n\s+/g,"$1").replace(/(]*>)\s+\n/g,"$1")).replace(/\s+<\/textarea>/g,"")).replace(/]*>((.|\n)*?)<\/textarea>/g,((match,capture)=>match.replace(capture,(match=>match.replace(//g,">").replace(/\//g,"/").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/%/g,"%").replace(/\{/g,"{").replace(/\}/g,"}"))))),minify&&(html=html.replace(/]*>((.|\n)*?)<\/textarea>/g,((match,capture)=>match=(match=match.replace(capture,(match=>match.replace(/\n|\t/g,"").replace(/[a-z]+="\s*"/gi,"").replace(/>\s+<").replace(/\s+/g," ")))).replace(/\s+/g," ").replace(/\s>/g,">").replace(/>\s/g,">").replace(/\smatch.replace(/\s/g,""))).replace(/(class=.*)\s(["'])/g,"$1$2")))),html};let strict;const convert={line:[]},preprocess=html=>(html=function(html){return arguments.length>1&&void 0!==arguments[1]&&!arguments[1]||hasHtml(html)?html.replace(/<([a-zA-Z\-0-9]+)[^>]*>/g,((match,name)=>void_elements.indexOf(name)>-1?"".concat(match.substring(0,match.length-1)," />").replace(/\/\s\//g,"/"):match.replace(/[\s]?\/>/g,">")))):html}(html,!1),html=function(html){return arguments.length>1&&void 0!==arguments[1]&&!arguments[1]||hasHtml(html)?(html=entify(html)).replace(/\n|\t/g,"").replace(/[a-z]+="\s*"/gi,"").replace(/>\s+<").replace(/\s+/g," ").replace(/\s>/g,">").replace(/<\s\//g,"\s/g,">").replace(/\smatch.replace(/\s/g,""))).replace(/(class=.*)\s(["'])/g,"$1$2"):html}(html,!1),html=(html=>{convert.line=[];let i=-1;return html.replace(/<[^>]*>/g,(match=>(convert.line.push(match),i++,"\n[#-# : ".concat(i," : ").concat(match," : #-#]\n"))))})(html),html),prettify=(html,config)=>{const validated_config=config?validateConfig(config):CONFIG;return strict=validated_config.strict,hasHtml(html)?html=((html,step)=>{let indents="";convert.line.forEach(((source,index)=>{html=html.replace(/\n+/g,"\n").replace("[#-# : ".concat(index," : ").concat(source," : #-#]"),(match=>{let subtrahend=0;const prevLine="[#-# : ".concat(index-1," : ").concat(convert.line[index-1]," : #-#]");indents+="0",0===index&&subtrahend++,match.indexOf("#-# : ".concat(index," : -1&&subtrahend++,prevLine.indexOf("-1&&subtrahend++,prevLine.indexOf("\x3c!--")>-1&&subtrahend++,prevLine.indexOf("/> : #-#")>-1&&subtrahend++,prevLine.indexOf("#-# : ".concat(index-1," : -1&&subtrahend++;const offset=indents.length-subtrahend;if(indents=indents.substring(0,offset),strict&&match.indexOf("\x3c!--")>-1)return"";const result=match.replace("[#-# : ".concat(index," : "),"").replace(" : #-#]","");return result.padStart(result.length+step*offset)}))})),html=html.replace(/>[^<]*?[^><\/\s][^<]*?<\/|>\s+[^><\s]|]*>\s+<\/script>|<(\w+)>\s+<\/(\w+)|<([\w\-]+)[^>]*[^\/]>\s+<\/([\w\-]+)>/g,(match=>match.replace(/\n|\t|\s{2,}/g,""))),strict&&(html=html.replace(/\s\/>/g,">"));const lead_newline_check=html.substring(0,1),tail_newline_check=html.substring(html.length-1);return"\n"===lead_newline_check&&(html=html.substring(1,html.length)),"\n"===tail_newline_check&&(html=html.substring(0,html.length-1)),html})(html=preprocess(html),validated_config.tab_size):html},themes={light:EditorView.baseTheme(),dark:cm6proDark};return _exports.default=class{static getThemes(){return["light","dark"]}constructor(textarea){_defineProperty(this,"_parentElement",void 0),_defineProperty(this,"_source",void 0),_defineProperty(this,"_editorView",void 0),this._parentElement=textarea.parentElement,this.themeConfig=new Compartment,this.linewrapConfig=new Compartment;let updateListenerExtension=EditorView.updateListener.of((update=>{console.log(update),console.log(textarea),textarea.value=update.state.doc.toString()})),extensions=[basicSetup,this.linewrapConfig.of([EditorView.lineWrapping]),this.themeConfig.of([themes.light]),updateListenerExtension],name=textarea.name.split("[",1)[0],formatElement=textarea.form.querySelector('[name="'+name+'[format]"]');if(formatElement)switch(parseInt(formatElement.value)){case 90:extensions.push(css());break;case 91:extensions.push(javascript());break;default:extensions.push(function(){let wrap,config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},dialect="";!1===config.matchClosingTags&&(dialect="noMatch"),!0===config.selfClosingTags&&(dialect=(dialect?dialect+" ":"")+"selfClosing"),(config.nestedLanguages&&config.nestedLanguages.length||config.nestedAttributes&&config.nestedAttributes.length)&&(wrap=configureNesting((config.nestedLanguages||[]).concat(defaultNesting),(config.nestedAttributes||[]).concat(defaultAttrs)));let lang=wrap?htmlPlain.configure({wrap:wrap,dialect:dialect}):dialect?htmlLanguage.configure({dialect:dialect}):htmlLanguage;return new LanguageSupport(lang,[htmlLanguage.data.of({autocomplete:htmlCompletionSourceWith(config)}),!1!==config.autoCloseTags?autoCloseTags:[],javascript().support,css().support])}())}this._editorView=new EditorView({extensions:extensions,parent:this._parentElement,doc:textarea.value}),textarea.parentNode.insertBefore(this._editorView.dom,textarea),textarea.style.display="none",textarea.parentNode.nextElementSibling.style.display="none"}setValue(source){this._source=source;const view=this._editorView;view.dispatch({changes:{from:0,to:view.state.doc.length,insert:source||""}})}getValue(){return this._editorView.state.doc.toString()}setTheme(themeName){themes[themeName]?this._editorView.dispatch({effects:this.themeConfig.reconfigure([themes[themeName]])}):console.error("Unknown theme",themeName)}setLineWrapping(bool){this._editorView.dispatch({effects:this.linewrapConfig.reconfigure(bool?[EditorView.lineWrapping]:[])})}prettify(){const source=this.getValue(),beautified=prettify(source);this.setValue(beautified)}focus(){this._editorView.hasFocus||this._editorView.focus()}},_exports.default})); +define("editor_codemirror/cm6pro-lazy",["exports"],(function(_exports){function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0;class Text{lineAt(pos){if(pos<0||pos>this.length)throw new RangeError("Invalid position ".concat(pos," in document of length ").concat(this.length));return this.lineInner(pos,!1,1,0)}line(n){if(n<1||n>this.lines)throw new RangeError("Invalid line number ".concat(n," in ").concat(this.lines,"-line document"));return this.lineInner(n,!0,1,0)}replace(from,to,text){[from,to]=clip(this,from,to);let parts=[];return this.decompose(0,from,parts,2),text.length&&text.decompose(0,text.length,parts,3),this.decompose(to,this.length,parts,1),TextNode.from(parts,this.length-(to-from)+text.length)}append(other){return this.replace(this.length,this.length,other)}slice(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length;[from,to]=clip(this,from,to);let parts=[];return this.decompose(from,to,parts,0),TextNode.from(parts,to-from)}eq(other){if(other==this)return!0;if(other.length!=this.length||other.lines!=this.lines)return!1;let start=this.scanIdentical(other,1),end=this.length-this.scanIdentical(other,-1),a=new RawTextCursor(this),b=new RawTextCursor(other);for(let skip=start,pos=start;;){if(a.next(skip),b.next(skip),skip=0,a.lineBreak!=b.lineBreak||a.done!=b.done||a.value!=b.value)return!1;if(pos+=a.value.length,a.done||pos>=end)return!0}}iter(){return new RawTextCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:1)}iterRange(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length;return new PartialTextCursor(this,from,to)}iterLines(from,to){let inner;if(null==from)inner=this.iter();else{null==to&&(to=this.lines+1);let start=this.line(from).from;inner=this.iterRange(start,Math.max(start,to==this.lines+1?this.length:to<=1?0:this.line(to-1).to))}return new LineCursor(inner)}toString(){return this.sliceString(0)}toJSON(){let lines=[];return this.flatten(lines),lines}constructor(){}static of(text){if(0==text.length)throw new RangeError("A document must have at least one line");return 1!=text.length||text[0]?text.length<=32?new TextLeaf(text):TextNode.from(TextLeaf.split(text,[])):Text.empty}}class TextLeaf extends Text{constructor(text){let length=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(text){let length=-1;for(let line of text)length+=line.length+1;return length}(text);super(),this.text=text,this.length=length}get lines(){return this.text.length}get children(){return null}lineInner(target,isLine,line,offset){for(let i=0;;i++){let string=this.text[i],end=offset+string.length;if((isLine?line:end)>=target)return new Line(offset,end,line,string);offset=end+1,line++}}decompose(from,to,target,open){let text=from<=0&&to>=this.length?this:new TextLeaf(sliceText(this.text,from,to),Math.min(to,this.length)-Math.max(0,from));if(1&open){let prev=target.pop(),joined=appendText(text.text,prev.text.slice(),0,text.length);if(joined.length<=32)target.push(new TextLeaf(joined,prev.length+text.length));else{let mid=joined.length>>1;target.push(new TextLeaf(joined.slice(0,mid)),new TextLeaf(joined.slice(mid)))}}else target.push(text)}replace(from,to,text){if(!(text instanceof TextLeaf))return super.replace(from,to,text);[from,to]=clip(this,from,to);let lines=appendText(this.text,appendText(text.text,sliceText(this.text,0,from)),to),newLen=this.length+text.length-(to-from);return lines.length<=32?new TextLeaf(lines,newLen):TextNode.from(TextLeaf.split(lines,[]),newLen)}sliceString(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length,lineSep=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"\n";[from,to]=clip(this,from,to);let result="";for(let pos=0,i=0;pos<=to&&ifrom&&i&&(result+=lineSep),frompos&&(result+=line.slice(Math.max(0,from-pos),to-pos)),pos=end+1}return result}flatten(target){for(let line of this.text)target.push(line)}scanIdentical(){return 0}static split(text,target){let part=[],len=-1;for(let line of text)part.push(line),len+=line.length+1,32==part.length&&(target.push(new TextLeaf(part,len)),part=[],len=-1);return len>-1&&target.push(new TextLeaf(part,len)),target}}class TextNode extends Text{constructor(children,length){super(),this.children=children,this.length=length,this.lines=0;for(let child of children)this.lines+=child.lines}lineInner(target,isLine,line,offset){for(let i=0;;i++){let child=this.children[i],end=offset+child.length,endLine=line+child.lines-1;if((isLine?endLine:end)>=target)return child.lineInner(target,isLine,line,offset);offset=end+1,line=endLine+1}}decompose(from,to,target,open){for(let i=0,pos=0;pos<=to&&i=pos){let childOpen=open&((pos<=from?1:0)|(end>=to?2:0));pos>=from&&end<=to&&!childOpen?target.push(child):child.decompose(from-pos,to-pos,target,childOpen)}pos=end+1}}replace(from,to,text){if([from,to]=clip(this,from,to),text.lines=pos&&to<=end){let updated=child.replace(from-pos,to-pos,text),totalLines=this.lines-child.lines+updated.lines;if(updated.lines>4&&updated.lines>totalLines>>6){let copy=this.children.slice();return copy[i]=updated,new TextNode(copy,this.length-(to-from)+text.length)}return super.replace(pos,end,updated)}pos=end+1}return super.replace(from,to,text)}sliceString(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.length,lineSep=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"\n";[from,to]=clip(this,from,to);let result="";for(let i=0,pos=0;ifrom&&i&&(result+=lineSep),frompos&&(result+=child.sliceString(from-pos,to-pos,lineSep)),pos=end+1}return result}flatten(target){for(let child of this.children)child.flatten(target)}scanIdentical(other,dir){if(!(other instanceof TextNode))return 0;let length=0,[iA,iB,eA,eB]=dir>0?[0,0,this.children.length,other.children.length]:[this.children.length-1,other.children.length-1,-1,-1];for(;;iA+=dir,iB+=dir){if(iA==eA||iB==eB)return length;let chA=this.children[iA],chB=other.children[iB];if(chA!=chB)return length+chA.scanIdentical(chB,dir);length+=chA.length+1}}static from(children){let length=arguments.length>1&&void 0!==arguments[1]?arguments[1]:children.reduce(((l,ch)=>l+ch.length+1),-1),lines=0;for(let ch of children)lines+=ch.lines;if(lines<32){let flat=[];for(let ch of children)ch.flatten(flat);return new TextLeaf(flat,length)}let chunk=Math.max(32,lines>>5),maxChunk=chunk<<1,minChunk=chunk>>1,chunked=[],currentLines=0,currentLen=-1,currentChunk=[];function add(child){let last;if(child.lines>maxChunk&&child instanceof TextNode)for(let node of child.children)add(node);else child.lines>minChunk&&(currentLines>minChunk||!currentLines)?(flush(),chunked.push(child)):child instanceof TextLeaf&¤tLines&&(last=currentChunk[currentChunk.length-1])instanceof TextLeaf&&child.lines+last.lines<=32?(currentLines+=child.lines,currentLen+=child.length+1,currentChunk[currentChunk.length-1]=new TextLeaf(last.text.concat(child.text),last.length+1+child.length)):(currentLines+child.lines>chunk&&flush(),currentLines+=child.lines,currentLen+=child.length+1,currentChunk.push(child))}function flush(){0!=currentLines&&(chunked.push(1==currentChunk.length?currentChunk[0]:TextNode.from(currentChunk,currentLen)),currentLen=-1,currentLines=currentChunk.length=0)}for(let child of children)add(child);return flush(),1==chunked.length?chunked[0]:new TextNode(chunked,length)}}function appendText(text,target){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e9;for(let pos=0,i=0,first=!0;i=from&&(end>to&&(line=line.slice(0,to-pos)),pos1&&void 0!==arguments[1]?arguments[1]:1;this.dir=dir,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[text],this.offsets=[dir>0?1:(text instanceof TextLeaf?text.text.length:text.children.length)<<1]}nextInner(skip,dir){for(this.done=this.lineBreak=!1;;){let last=this.nodes.length-1,top=this.nodes[last],offsetValue=this.offsets[last],offset=offsetValue>>1,size=top instanceof TextLeaf?top.text.length:top.children.length;if(offset==(dir>0?size:0)){if(0==last)return this.done=!0,this.value="",this;dir>0&&this.offsets[last-1]++,this.nodes.pop(),this.offsets.pop()}else if((1&offsetValue)==(dir>0?0:1)){if(this.offsets[last]+=dir,0==skip)return this.lineBreak=!0,this.value="\n",this;skip--}else if(top instanceof TextLeaf){let next=top.text[offset+(dir<0?-1:0)];if(this.offsets[last]+=dir,next.length>Math.max(0,skip))return this.value=0==skip?next:dir>0?next.slice(skip):next.slice(0,next.length-skip),this;skip-=next.length}else{let next=top.children[offset+(dir<0?-1:0)];skip>next.length?(skip-=next.length,this.offsets[last]+=dir):(dir<0&&this.offsets[last]--,this.nodes.push(next),this.offsets.push(dir>0?1:(next instanceof TextLeaf?next.text.length:next.children.length)<<1))}}}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return skip<0&&(this.nextInner(-skip,-this.dir),skip=this.value.length),this.nextInner(skip,this.dir)}}class PartialTextCursor{constructor(text,start,end){this.value="",this.done=!1,this.cursor=new RawTextCursor(text,start>end?-1:1),this.pos=start>end?text.length:0,this.from=Math.min(start,end),this.to=Math.max(start,end)}nextInner(skip,dir){if(dir<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;skip+=Math.max(0,dir<0?this.pos-this.to:this.from-this.pos);let limit=dir<0?this.pos-this.from:this.to-this.pos;skip>limit&&(skip=limit),limit-=skip;let{value:value}=this.cursor.next(skip);return this.pos+=(value.length+skip)*dir,this.value=value.length<=limit?value:dir<0?value.slice(value.length-limit):value.slice(0,limit),this.done=!this.value,this}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return skip<0?skip=Math.max(skip,this.from-this.pos):skip>0&&(skip=Math.min(skip,this.to-this.pos)),this.nextInner(skip,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&""!=this.value}}class LineCursor{constructor(inner){this.inner=inner,this.afterBreak=!0,this.value="",this.done=!1}next(){let skip=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,{done:done,lineBreak:lineBreak,value:value}=this.inner.next(skip);return done&&this.afterBreak?(this.value="",this.afterBreak=!1):done?(this.done=!0,this.value=""):lineBreak?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=value,this.afterBreak=!1),this}get lineBreak(){return!1}}"undefined"!=typeof Symbol&&(Text.prototype[Symbol.iterator]=function(){return this.iter()},RawTextCursor.prototype[Symbol.iterator]=PartialTextCursor.prototype[Symbol.iterator]=LineCursor.prototype[Symbol.iterator]=function(){return this});class Line{constructor(from,to,number,text){this.from=from,this.to=to,this.number=number,this.text=text}get length(){return this.to-this.from}}function clip(text,from,to){return[from=Math.max(0,Math.min(text.length,from)),Math.max(from,Math.min(text.length,to))]}let extend="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,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,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((s=>s?parseInt(s,36):1));for(let i=1;icode)return extend[i-1]<=code;return!1}function isRegionalIndicator(code){return code>=127462&&code<=127487}function findClusterBreak(str,pos){let forward=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],includeExtending=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return(forward?nextClusterBreak:prevClusterBreak)(str,pos,includeExtending)}function nextClusterBreak(str,pos,includeExtending){if(pos==str.length)return pos;pos&&surrogateLow(str.charCodeAt(pos))&&surrogateHigh(str.charCodeAt(pos-1))&&pos--;let prev=codePointAt(str,pos);for(pos+=codePointSize(prev);pos=0&&isRegionalIndicator(codePointAt(str,i));)countBefore++,i-=2;if(countBefore%2==0)break;pos+=2}}}return pos}function prevClusterBreak(str,pos,includeExtending){for(;pos>0;){let found=nextClusterBreak(str,pos-2,includeExtending);if(found=56320&&ch<57344}function surrogateHigh(ch){return ch>=55296&&ch<56320}function codePointAt(str,pos){let code0=str.charCodeAt(pos);if(!surrogateHigh(code0)||pos+1==str.length)return code0;let code1=str.charCodeAt(pos+1);return surrogateLow(code1)?code1-56320+(code0-55296<<10)+65536:code0}function fromCodePoint(code){return code<=65535?String.fromCharCode(code):(code-=65536,String.fromCharCode(55296+(code>>10),56320+(1023&code)))}function codePointSize(code){return code<65536?1:2}const DefaultSplit=/\r\n?|\n/;var MapMode=function(MapMode){return MapMode[MapMode.Simple=0]="Simple",MapMode[MapMode.TrackDel=1]="TrackDel",MapMode[MapMode.TrackBefore=2]="TrackBefore",MapMode[MapMode.TrackAfter=3]="TrackAfter",MapMode}(MapMode||(MapMode={}));class ChangeDesc{constructor(sections){this.sections=sections}get length(){let result=0;for(let i=0;i1&&void 0!==arguments[1]&&arguments[1])}get invertedDesc(){let sections=[];for(let i=0;i1&&void 0!==arguments[1]&&arguments[1];return other.empty?this:mapSet(this,other,before)}mapPos(pos){let assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1,mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:MapMode.Simple,posA=0,posB=0;for(let i=0;ipos)return posB+(pos-posA);posB+=len}else{if(mode!=MapMode.Simple&&endA>=pos&&(mode==MapMode.TrackDel&&posApos||mode==MapMode.TrackBefore&&posApos))return null;if(endA>pos||endA==pos&&assoc<0&&!len)return pos==posA||assoc<0?posB:posB+ins;posB+=ins}posA=endA}if(pos>posA)throw new RangeError("Position ".concat(pos," is out of range for changeset of length ").concat(posA));return posB}touchesRange(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;for(let i=0,pos=0;i=0&&pos<=to&&end>=from)return!(posto)||"cover";pos=end}return!1}toString(){let result="";for(let i=0;i=0?":"+ins:"")}return result}toJSON(){return this.sections}static fromJSON(json){if(!Array.isArray(json)||json.length%2||json.some((a=>"number"!=typeof a)))throw new RangeError("Invalid JSON representation of ChangeDesc");return new ChangeDesc(json)}static create(sections){return new ChangeDesc(sections)}}class ChangeSet extends ChangeDesc{constructor(sections,inserted){super(sections),this.inserted=inserted}apply(doc){if(this.length!=doc.length)throw new RangeError("Applying change set to a document with the wrong length");return iterChanges(this,((fromA,toA,fromB,_toB,text)=>doc=doc.replace(fromB,fromB+(toA-fromA),text)),!1),doc}mapDesc(other){return mapSet(this,other,arguments.length>1&&void 0!==arguments[1]&&arguments[1],!0)}invert(doc){let sections=this.sections.slice(),inserted=[];for(let i=0,pos=0;i=0){sections[i]=ins,sections[i+1]=len;let index=i>>1;for(;inserted.length1&&void 0!==arguments[1]&&arguments[1];return other.empty?this:mapSet(this,other,before,!0)}iterChanges(f){iterChanges(this,f,arguments.length>1&&void 0!==arguments[1]&&arguments[1])}get desc(){return ChangeDesc.create(this.sections)}filter(ranges){let resultSections=[],resultInserted=[],filteredSections=[],iter=new SectionIter(this);done:for(let i=0,pos=0;;){let next=i==ranges.length?1e9:ranges[i++];for(;pos0&&addInsert(resultInserted,resultSections,iter.text),iter.forward(len),pos+=len}let end=ranges[i++];for(;pos>1].toJSON()))}return parts}static of(changes,length,lineSep){let sections=[],inserted=[],pos=0,total=null;function flush(){let force=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!force&&!sections.length)return;posto||from<0||to>length)throw new RangeError("Invalid change range ".concat(from," to ").concat(to," (in doc of length ").concat(length,")"));let insText=insert?"string"==typeof insert?Text.of(insert.split(lineSep||DefaultSplit)):insert:Text.empty,insLen=insText.length;if(from==to&&0==insLen)return;frompos&&addSection(sections,from-pos,-1),addSection(sections,to-from,insLen),addInsert(inserted,sections,insText),pos=to}}(changes),flush(!total),total}static empty(length){return new ChangeSet(length?[length,-1]:[],[])}static fromJSON(json){if(!Array.isArray(json))throw new RangeError("Invalid JSON representation of ChangeSet");let sections=[],inserted=[];for(let i=0;ii&&"string"!=typeof e)))throw new RangeError("Invalid JSON representation of ChangeSet");if(1==part.length)sections.push(part[0],0);else{for(;inserted.length3&&void 0!==arguments[3]&&arguments[3];if(0==len&&ins<=0)return;let last=sections.length-2;last>=0&&ins<=0&&ins==sections[last+1]?sections[last]+=len:0==len&&0==sections[last]?sections[last+1]+=ins:forceJoin?(sections[last]+=len,sections[last+1]+=ins):sections.push(len,ins)}function addInsert(values,sections,value){if(0==value.length)return;let index=sections.length-2>>1;if(index>1])),!(individual||i==desc.sections.length||desc.sections[i+1]<0);)len=desc.sections[i++],ins=desc.sections[i++];f(posA,endA,posB,endB,text),posA=endA,posB=endB}}}function mapSet(setA,setB,before){let mkSet=arguments.length>3&&void 0!==arguments[3]&&arguments[3],sections=[],insert=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let inserted=-1;;)if(-1==a.ins&&-1==b.ins){let len=Math.min(a.len,b.len);addSection(sections,len,-1),a.forward(len),b.forward(len)}else if(b.ins>=0&&(a.ins<0||inserted==a.i||0==a.off&&(b.len=0&&inserted=0)){if(a.done&&b.done)return insert?ChangeSet.createSet(sections,insert):ChangeDesc.create(sections);throw new Error("Mismatched change set lengths")}{let len=0,left=a.len;for(;left;)if(-1==b.ins){let piece=Math.min(left,b.len);len+=piece,left-=piece,b.forward(piece)}else{if(!(0==b.ins&&b.len2&&void 0!==arguments[2]&&arguments[2],sections=[],insert=mkSet?[]:null,a=new SectionIter(setA),b=new SectionIter(setB);for(let open=!1;;){if(a.done&&b.done)return insert?ChangeSet.createSet(sections,insert):ChangeDesc.create(sections);if(0==a.ins)addSection(sections,a.len,0,open),a.next();else if(0!=b.len||b.done){if(a.done||b.done)throw new Error("Mismatched change set lengths");{let len=Math.min(a.len2,b.len),sectionLen=sections.length;if(-1==a.ins){let insB=-1==b.ins?-1:b.off?0:b.ins;addSection(sections,len,insB,open),insert&&insB&&addInsert(insert,sections,b.text)}else-1==b.ins?(addSection(sections,a.off?0:a.len,len,open),insert&&addInsert(insert,sections,a.textBit(len))):(addSection(sections,a.off?0:a.len,b.off?0:b.ins,open),insert&&!b.off&&addInsert(insert,sections,b.text));open=(a.ins>len||b.ins>=0&&b.len>len)&&(open||sections.length>sectionLen),a.forward2(len),b.forward(len)}}else addSection(sections,0,b.ins,open),insert&&addInsert(insert,sections,b.text),b.next()}}class SectionIter{constructor(set){this.set=set,this.i=0,this.next()}next(){let{sections:sections}=this.set;this.i>1;return index>=inserted.length?Text.empty:inserted[index]}textBit(len){let{inserted:inserted}=this.set,index=this.i-2>>1;return index>=inserted.length&&!len?Text.empty:inserted[index].slice(this.off,null==len?void 0:this.off+len)}forward(len){len==this.len?this.next():(this.len-=len,this.off+=len)}forward2(len){-1==this.ins?this.forward(len):len==this.ins?this.next():(this.ins-=len,this.off+=len)}}class SelectionRange{constructor(from,to,flags){this.from=from,this.to=to,this.flags=flags}get anchor(){return 32&this.flags?this.to:this.from}get head(){return 32&this.flags?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return 8&this.flags?-1:16&this.flags?1:0}get bidiLevel(){let level=7&this.flags;return 7==level?null:level}get goalColumn(){let value=this.flags>>6;return 16777215==value?void 0:value}map(change){let from,to,assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return this.empty?from=to=change.mapPos(this.from,assoc):(from=change.mapPos(this.from,1),to=change.mapPos(this.to,-1)),from==this.from&&to==this.to?this:new SelectionRange(from,to,this.flags)}extend(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(from<=this.anchor&&to>=this.anchor)return EditorSelection.range(from,to);let head=Math.abs(from-this.anchor)>Math.abs(to-this.anchor)?from:to;return EditorSelection.range(this.anchor,head)}eq(other){let includeAssoc=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return!(this.anchor!=other.anchor||this.head!=other.head||includeAssoc&&this.empty&&this.assoc!=other.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(json){if(!json||"number"!=typeof json.anchor||"number"!=typeof json.head)throw new RangeError("Invalid JSON representation for SelectionRange");return EditorSelection.range(json.anchor,json.head)}static create(from,to,flags){return new SelectionRange(from,to,flags)}}class EditorSelection{constructor(ranges,mainIndex){this.ranges=ranges,this.mainIndex=mainIndex}map(change){let assoc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;return change.empty?this:EditorSelection.create(this.ranges.map((r=>r.map(change,assoc))),this.mainIndex)}eq(other){let includeAssoc=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(this.ranges.length!=other.ranges.length||this.mainIndex!=other.mainIndex)return!1;for(let i=0;i1&&void 0!==arguments[1])||arguments[1];return EditorSelection.create([range].concat(this.ranges),main?0:this.mainIndex+1)}replaceRange(range){let which=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.mainIndex,ranges=this.ranges.slice();return ranges[which]=range,EditorSelection.create(ranges,this.mainIndex)}toJSON(){return{ranges:this.ranges.map((r=>r.toJSON())),main:this.mainIndex}}static fromJSON(json){if(!json||!Array.isArray(json.ranges)||"number"!=typeof json.main||json.main>=json.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new EditorSelection(json.ranges.map((r=>SelectionRange.fromJSON(r))),json.main)}static single(anchor){let head=arguments.length>1&&void 0!==arguments[1]?arguments[1]:anchor;return new EditorSelection([EditorSelection.range(anchor,head)],0)}static create(ranges){let mainIndex=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(0==ranges.length)throw new RangeError("A selection needs at least one range");for(let pos=0,i=0;i1&&void 0!==arguments[1]?arguments[1]:0,bidiLevel=arguments.length>2?arguments[2]:void 0,goalColumn=arguments.length>3?arguments[3]:void 0;return SelectionRange.create(pos,pos,(0==assoc?0:assoc<0?8:16)|(null==bidiLevel?7:Math.min(6,bidiLevel))|(null!=goalColumn?goalColumn:16777215)<<6)}static range(anchor,head,goalColumn,bidiLevel){let flags=(null!=goalColumn?goalColumn:16777215)<<6|(null==bidiLevel?7:Math.min(6,bidiLevel));return headanchor?8:0)|flags)}static normalized(ranges){let mainIndex=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,main=ranges[mainIndex];ranges.sort(((a,b)=>a.from-b.from)),mainIndex=ranges.indexOf(main);for(let i=1;irange.head?EditorSelection.range(to,from):EditorSelection.range(from,to))}}return new EditorSelection(ranges,mainIndex)}}function checkSelection(selection,docLength){for(let range of selection.ranges)if(range.to>docLength)throw new RangeError("Selection points outside of document")}let nextID=0;class Facet{constructor(combine,compareInput,compare,isStatic,enables){this.combine=combine,this.compareInput=compareInput,this.compare=compare,this.isStatic=isStatic,this.id=nextID++,this.default=combine([]),this.extensions="function"==typeof enables?enables(this):enables}get reader(){return this}static define(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new Facet(config.combine||(a=>a),config.compareInput||((a,b)=>a===b),config.compare||(config.combine?(a,b)=>a===b:sameArray$1),!!config.static,config.enables)}of(value){return new FacetProvider([],this,0,value)}compute(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,1,get)}computeN(deps,get){if(this.isStatic)throw new Error("Can't compute a static facet");return new FacetProvider(deps,this,2,get)}from(field,get){return get||(get=x=>x),this.compute([field],(state=>get(state.field(field))))}}function sameArray$1(a,b){return a==b||a.length==b.length&&a.every(((e,i)=>e===b[i]))}class FacetProvider{constructor(dependencies,facet,type,value){this.dependencies=dependencies,this.facet=facet,this.type=type,this.value=value,this.id=nextID++}dynamicSlot(addresses){var _a;let getter=this.value,compare=this.facet.compareInput,id=this.id,idx=addresses[id]>>1,multi=2==this.type,depDoc=!1,depSel=!1,depAddrs=[];for(let dep of this.dependencies)"doc"==dep?depDoc=!0:"selection"==dep?depSel=!0:0==(1&(null!==(_a=addresses[dep.id])&&void 0!==_a?_a:1))&&depAddrs.push(addresses[dep.id]);return{create:state=>(state.values[idx]=getter(state),1),update(state,tr){if(depDoc&&tr.docChanged||depSel&&(tr.docChanged||tr.selection)||ensureAll(state,depAddrs)){let newVal=getter(state);if(multi?!compareArray(newVal,state.values[idx],compare):!compare(newVal,state.values[idx]))return state.values[idx]=newVal,1}return 0},reconfigure:(state,oldState)=>{let newVal,oldAddr=oldState.config.address[id];if(null!=oldAddr){let oldVal=getAddr(oldState,oldAddr);if(this.dependencies.every((dep=>dep instanceof Facet?oldState.facet(dep)===state.facet(dep):!(dep instanceof StateField)||oldState.field(dep,!1)==state.field(dep,!1)))||(multi?compareArray(newVal=getter(state),oldVal,compare):compare(newVal=getter(state),oldVal)))return state.values[idx]=oldVal,0}else newVal=getter(state);return state.values[idx]=newVal,1}}}}function compareArray(a,b,compare){if(a.length!=b.length)return!1;for(let i=0;iaddresses[p.id])),providerTypes=providers.map((p=>p.type)),dynamic=providerAddrs.filter((p=>!(1&p))),idx=addresses[facet.id]>>1;function get(state){let values=[];for(let i=0;ia===b),config);return config.provide&&(field.provides=config.provide(field)),field}create(state){let init=state.facet(initField).find((i=>i.field==this));return((null==init?void 0:init.create)||this.createF)(state)}slot(addresses){let idx=addresses[this.id]>>1;return{create:state=>(state.values[idx]=this.create(state),1),update:(state,tr)=>{let oldVal=state.values[idx],value=this.updateF(oldVal,tr);return this.compareF(oldVal,value)?0:(state.values[idx]=value,1)},reconfigure:(state,oldState)=>null!=oldState.config.address[this.id]?(state.values[idx]=oldState.field(this),0):(state.values[idx]=this.create(state),1)}}init(create){return[this,initField.of({field:this,create:create})]}get extension(){return this}}const Prec__lowest=4,Prec__low=3,Prec__default=2,Prec__high=1;function prec(value){return ext=>new PrecExtension(ext,value)}const Prec={highest:prec(0),high:prec(Prec__high),default:prec(Prec__default),low:prec(Prec__low),lowest:prec(Prec__lowest)};class PrecExtension{constructor(inner,prec){this.inner=inner,this.prec=prec}}class Compartment{of(ext){return new CompartmentInstance(this,ext)}reconfigure(content){return Compartment.reconfigure.of({compartment:this,extension:content})}get(state){return state.config.compartments.get(this)}}class CompartmentInstance{constructor(compartment,inner){this.compartment=compartment,this.inner=inner}}class Configuration{constructor(base,compartments,dynamicSlots,address,staticValues,facets){for(this.base=base,this.compartments=compartments,this.dynamicSlots=dynamicSlots,this.address=address,this.staticValues=staticValues,this.facets=facets,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(base,compartments,oldState){let fields=[],facets=Object.create(null),newCompartments=new Map;for(let ext of function(extension,compartments,newCompartments){let result=[[],[],[],[],[]],seen=new Map;function inner(ext,prec){let known=seen.get(ext);if(null!=known){if(known<=prec)return;let found=result[known].indexOf(ext);found>-1&&result[known].splice(found,1),ext instanceof CompartmentInstance&&newCompartments.delete(ext.compartment)}if(seen.set(ext,prec),Array.isArray(ext))for(let e of ext)inner(e,prec);else if(ext instanceof CompartmentInstance){if(newCompartments.has(ext.compartment))throw new RangeError("Duplicate use of compartment in extensions");let content=compartments.get(ext.compartment)||ext.inner;newCompartments.set(ext.compartment,content),inner(content,prec)}else if(ext instanceof PrecExtension)inner(ext.inner,ext.prec);else if(ext instanceof StateField)result[prec].push(ext),ext.provides&&inner(ext.provides,prec);else if(ext instanceof FacetProvider)result[prec].push(ext),ext.facet.extensions&&inner(ext.facet.extensions,Prec__default);else{let content=ext.extension;if(!content)throw new Error("Unrecognized extension value in extension set (".concat(ext,"). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks."));inner(content,prec)}}return inner(extension,Prec__default),result.reduce(((a,b)=>a.concat(b)))}(base,compartments,newCompartments))ext instanceof StateField?fields.push(ext):(facets[ext.facet.id]||(facets[ext.facet.id]=[])).push(ext);let address=Object.create(null),staticValues=[],dynamicSlots=[];for(let field of fields)address[field.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>field.slot(a)));let oldFacets=null==oldState?void 0:oldState.config.facets;for(let id in facets){let providers=facets[id],facet=providers[0].facet,oldProviders=oldFacets&&oldFacets[id]||[];if(providers.every((p=>0==p.type)))if(address[facet.id]=staticValues.length<<1|1,sameArray$1(oldProviders,providers))staticValues.push(oldState.facet(facet));else{let value=facet.combine(providers.map((p=>p.value)));staticValues.push(oldState&&facet.compare(value,oldState.facet(facet))?oldState.facet(facet):value)}else{for(let p of providers)0==p.type?(address[p.id]=staticValues.length<<1|1,staticValues.push(p.value)):(address[p.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>p.dynamicSlot(a))));address[facet.id]=dynamicSlots.length<<1,dynamicSlots.push((a=>dynamicFacetSlot(a,facet,providers)))}}let dynamic=dynamicSlots.map((f=>f(address)));return new Configuration(base,newCompartments,dynamic,address,staticValues,facets)}}function ensureAddr(state,addr){if(1&addr)return 2;let idx=addr>>1,status=state.status[idx];if(4==status)throw new Error("Cyclic dependency between fields and/or facets");if(2&status)return status;state.status[idx]=4;let changed=state.computeSlot(state,state.config.dynamicSlots[idx]);return state.status[idx]=2|changed}function getAddr(state,addr){return 1&addr?state.config.staticValues[addr>>1]:state.values[addr>>1]}const languageData=Facet.define(),allowMultipleSelections=Facet.define({combine:values=>values.some((v=>v)),static:!0}),lineSeparator=Facet.define({combine:values=>values.length?values[0]:void 0,static:!0}),changeFilter=Facet.define(),transactionFilter=Facet.define(),transactionExtender=Facet.define(),readOnly=Facet.define({combine:values=>!!values.length&&values[0]});class Annotation{constructor(type,value){this.type=type,this.value=value}static define(){return new AnnotationType}}class AnnotationType{of(value){return new Annotation(this,value)}}class StateEffectType{constructor(map){this.map=map}of(value){return new StateEffect(this,value)}}class StateEffect{constructor(type,value){this.type=type,this.value=value}map(mapping){let mapped=this.type.map(this.value,mapping);return void 0===mapped?void 0:mapped==this.value?this:new StateEffect(this.type,mapped)}is(type){return this.type==type}static define(){return new StateEffectType((arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).map||(v=>v))}static mapEffects(effects,mapping){if(!effects.length)return effects;let result=[];for(let effect of effects){let mapped=effect.map(mapping);mapped&&result.push(mapped)}return result}}StateEffect.reconfigure=StateEffect.define(),StateEffect.appendConfig=StateEffect.define();class Transaction{constructor(startState,changes,selection,effects,annotations,scrollIntoView){this.startState=startState,this.changes=changes,this.selection=selection,this.effects=effects,this.annotations=annotations,this.scrollIntoView=scrollIntoView,this._doc=null,this._state=null,selection&&checkSelection(selection,changes.newLength),annotations.some((a=>a.type==Transaction.time))||(this.annotations=annotations.concat(Transaction.time.of(Date.now())))}static create(startState,changes,selection,effects,annotations,scrollIntoView){return new Transaction(startState,changes,selection,effects,annotations,scrollIntoView)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(type){for(let ann of this.annotations)if(ann.type==type)return ann.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(event){let e=this.annotation(Transaction.userEvent);return!(!e||!(e==event||e.length>event.length&&e.slice(0,event.length)==event&&"."==e[event.length]))}}function joinRanges(a,b){let result=[];for(let iA=0,iB=0;;){let from,to;if(iA=a[iA]))from=a[iA++],to=a[iA++];else{if(!(iB=0;i--){let extension=extenders[i](tr);extension&&Object.keys(extension).length&&(spec=mergeTransaction(spec,resolveTransactionInner(state,extension,tr.changes.newLength),!0))}return spec==tr?tr:Transaction.create(state,tr.changes,tr.selection,spec.effects,spec.annotations,spec.scrollIntoView)}(filter?function(tr){let state=tr.startState,result=!0;for(let filter of state.facet(changeFilter)){let value=filter(tr);if(!1===value){result=!1;break}Array.isArray(value)&&(result=!0===result?value:joinRanges(result,value))}if(!0!==result){let changes,back;if(!1===result)back=tr.changes.invertedDesc,changes=ChangeSet.empty(state.doc.length);else{let filtered=tr.changes.filter(result);changes=filtered.changes,back=filtered.filtered.mapDesc(filtered.changes).invertedDesc}tr=Transaction.create(state,changes,tr.selection&&tr.selection.map(back),StateEffect.mapEffects(tr.effects,back),tr.annotations,tr.scrollIntoView)}let filters=state.facet(transactionFilter);for(let i=filters.length-1;i>=0;i--){let filtered=filters[i](tr);tr=filtered instanceof Transaction?filtered:Array.isArray(filtered)&&1==filtered.length&&filtered[0]instanceof Transaction?filtered[0]:resolveTransaction(state,asArray$1(filtered),!1)}return tr}(tr):tr)}Transaction.time=Annotation.define(),Transaction.userEvent=Annotation.define(),Transaction.addToHistory=Annotation.define(),Transaction.remote=Annotation.define();const none$2=[];function asArray$1(value){return null==value?none$2:Array.isArray(value)?value:[value]}var CharCategory=function(CharCategory){return CharCategory[CharCategory.Word=0]="Word",CharCategory[CharCategory.Space=1]="Space",CharCategory[CharCategory.Other=2]="Other",CharCategory}(CharCategory||(CharCategory={}));const nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wordChar;try{wordChar=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch(_){}function makeCategorizer(wordChars){return char=>{if(!/\S/.test(char))return CharCategory.Space;if(function(str){if(wordChar)return wordChar.test(str);for(let i=0;i"€"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch)))return!0}return!1}(char))return CharCategory.Word;for(let i=0;i-1)return CharCategory.Word;return CharCategory.Other}}class EditorState{constructor(config,doc,selection,values,computeSlot,tr){this.config=config,this.doc=doc,this.selection=selection,this.values=values,this.status=config.statusTemplate.slice(),this.computeSlot=computeSlot,tr&&(tr._state=this);for(let i=0;i1&&void 0!==arguments[1])||arguments[1],addr=this.config.address[field.id];if(null!=addr)return ensureAddr(this,addr),getAddr(this,addr);if(require)throw new RangeError("Field is not present in this state")}update(){for(var _len=arguments.length,specs=new Array(_len),_key=0;_key<_len;_key++)specs[_key]=arguments[_key];return resolveTransaction(this,specs,!0)}applyTransaction(tr){let startValues,conf=this.config,{base:base,compartments:compartments}=conf;for(let effect of tr.effects)effect.is(Compartment.reconfigure)?(conf&&(compartments=new Map,conf.compartments.forEach(((val,key)=>compartments.set(key,val))),conf=null),compartments.set(effect.value.compartment,effect.value.extension)):effect.is(StateEffect.reconfigure)?(conf=null,base=effect.value):effect.is(StateEffect.appendConfig)&&(conf=null,base=asArray$1(base).concat(effect.value));if(conf)startValues=tr.startState.values.slice();else{conf=Configuration.resolve(base,compartments,this),startValues=new EditorState(conf,this.doc,this.selection,conf.dynamicSlots.map((()=>null)),((state,slot)=>slot.reconfigure(state,this)),null).values}let selection=tr.startState.facet(allowMultipleSelections)?tr.newSelection:tr.newSelection.asSingle();new EditorState(conf,tr.newDoc,selection,startValues,((state,slot)=>slot.update(state,tr)),tr)}replaceSelection(text){return"string"==typeof text&&(text=this.toText(text)),this.changeByRange((range=>({changes:{from:range.from,to:range.to,insert:text},range:EditorSelection.cursor(range.from+text.length)})))}changeByRange(f){let sel=this.selection,result1=f(sel.ranges[0]),changes=this.changes(result1.changes),ranges=[result1.range],effects=asArray$1(result1.effects);for(let i=1;i0&&void 0!==arguments[0]?arguments[0]:[];return spec instanceof ChangeSet?spec:ChangeSet.of(spec,this.doc.length,this.facet(EditorState.lineSeparator))}toText(string){return Text.of(string.split(this.facet(EditorState.lineSeparator)||DefaultSplit))}sliceDoc(){let from=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.doc.length;return this.doc.sliceString(from,to,this.lineBreak)}facet(facet){let addr=this.config.address[facet.id];return null==addr?facet.default:(ensureAddr(this,addr),getAddr(this,addr))}toJSON(fields){let result={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(fields)for(let prop in fields){let value=fields[prop];value instanceof StateField&&null!=this.config.address[value.id]&&(result[prop]=value.spec.toJSON(this.field(fields[prop]),this))}return result}static fromJSON(json){let config=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},fields=arguments.length>2?arguments[2]:void 0;if(!json||"string"!=typeof json.doc)throw new RangeError("Invalid JSON representation for EditorState");let fieldInit=[];if(fields)for(let prop in fields)if(Object.prototype.hasOwnProperty.call(json,prop)){let field=fields[prop],value=json[prop];fieldInit.push(field.init((state=>field.spec.fromJSON(value,state))))}return EditorState.create({doc:json.doc,selection:EditorSelection.fromJSON(json.selection),extensions:config.extensions?fieldInit.concat([config.extensions]):fieldInit})}static create(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},configuration=Configuration.resolve(config.extensions||[],new Map),doc=config.doc instanceof Text?config.doc:Text.of((config.doc||"").split(configuration.staticFacet(EditorState.lineSeparator)||DefaultSplit)),selection=config.selection?config.selection instanceof EditorSelection?config.selection:EditorSelection.single(config.selection.anchor,config.selection.head):EditorSelection.single(0);return checkSelection(selection,doc.length),configuration.staticFacet(allowMultipleSelections)||(selection=selection.asSingle()),new EditorState(configuration,doc,selection,configuration.dynamicSlots.map((()=>null)),((state,slot)=>slot.create(state)),null)}get tabSize(){return this.facet(EditorState.tabSize)}get lineBreak(){return this.facet(EditorState.lineSeparator)||"\n"}get readOnly(){return this.facet(readOnly)}phrase(phrase){for(var _len2=arguments.length,insert=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)insert[_key2-1]=arguments[_key2];for(let map of this.facet(EditorState.phrases))if(Object.prototype.hasOwnProperty.call(map,phrase)){phrase=map[phrase];break}return insert.length&&(phrase=phrase.replace(/\$(\$|\d*)/g,((m,i)=>{if("$"==i)return"$";let n=+(i||1);return!n||n>insert.length?m:insert[n-1]}))),phrase}languageDataAt(name,pos){let side=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,values=[];for(let provider of this.facet(languageData))for(let result of provider(this,pos,side))Object.prototype.hasOwnProperty.call(result,name)&&values.push(result[name]);return values}charCategorizer(at){return makeCategorizer(this.languageDataAt("wordChars",at).join(""))}wordAt(pos){let{text:text,from:from,length:length}=this.doc.lineAt(pos),cat=this.charCategorizer(pos),start=pos-from,end=pos-from;for(;start>0;){let prev=findClusterBreak(text,start,!1);if(cat(text.slice(prev,start))!=CharCategory.Word)break;start=prev}for(;end2&&void 0!==arguments[2]?arguments[2]:{},result={};for(let config of configs)for(let key of Object.keys(config)){let value=config[key],current=result[key];if(void 0===current)result[key]=value;else if(current===value||void 0===value);else{if(!Object.hasOwnProperty.call(combine,key))throw new Error("Config merge conflict for field "+key);result[key]=combine[key](current,value)}}for(let key in defaults)void 0===result[key]&&(result[key]=defaults[key]);return result}EditorState.allowMultipleSelections=allowMultipleSelections,EditorState.tabSize=Facet.define({combine:values=>values.length?values[0]:4}),EditorState.lineSeparator=lineSeparator,EditorState.readOnly=readOnly,EditorState.phrases=Facet.define({compare(a,b){let kA=Object.keys(a),kB=Object.keys(b);return kA.length==kB.length&&kA.every((k=>a[k]==b[k]))}}),EditorState.languageData=languageData,EditorState.changeFilter=changeFilter,EditorState.transactionFilter=transactionFilter,EditorState.transactionExtender=transactionExtender,Compartment.reconfigure=StateEffect.define();class RangeValue{eq(other){return this==other}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;return Range$1.create(from,to,this)}}RangeValue.prototype.startSide=RangeValue.prototype.endSide=0,RangeValue.prototype.point=!1,RangeValue.prototype.mapMode=MapMode.TrackDel;let Range$1=class Range{constructor(from,to,value){this.from=from,this.to=to,this.value=value}static create(from,to,value){return new Range(from,to,value)}};function cmpRange(a,b){return a.from-b.from||a.value.startSide-b.value.startSide}class Chunk{constructor(from,to,value,maxPoint){this.from=from,this.to=to,this.value=value,this.maxPoint=maxPoint}get length(){return this.to[this.to.length-1]}findIndex(pos,side,end){let startAt=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,arr=end?this.to:this.from;for(let lo=startAt,hi=arr.length;;){if(lo==hi)return lo;let mid=lo+hi>>1,diff=arr[mid]-pos||(end?this.value[mid].endSide:this.value[mid].startSide)-side;if(mid==lo)return diff>=0?lo:hi;diff>=0?hi=mid:lo=mid+1}}between(offset,from,to,f){for(let i=this.findIndex(from,-1e9,!0),e=this.findIndex(to,1e9,!1,i);inewTo||newFrom==newTo&&val.startSide>0&&val.endSide<=0)continue;(newTo-newFrom||val.endSide-val.startSide)<0||(newPos<0&&(newPos=newFrom),val.point&&(maxPoint=Math.max(maxPoint,newTo-newFrom)),value.push(val),from.push(newFrom-newPos),to.push(newTo-newPos))}return{mapped:value.length?new Chunk(from,to,value,maxPoint):null,pos:newPos}}}class RangeSet{constructor(chunkPos,chunk,nextLayer,maxPoint){this.chunkPos=chunkPos,this.chunk=chunk,this.nextLayer=nextLayer,this.maxPoint=maxPoint}static create(chunkPos,chunk,nextLayer,maxPoint){return new RangeSet(chunkPos,chunk,nextLayer,maxPoint)}get length(){let last=this.chunk.length-1;return last<0?0:Math.max(this.chunkEnd(last),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let size=this.nextLayer.size;for(let chunk of this.chunk)size+=chunk.value.length;return size}chunkEnd(index){return this.chunkPos[index]+this.chunk[index].length}update(updateSpec){let{add:add=[],sort:sort=!1,filterFrom:filterFrom=0,filterTo:filterTo=this.length}=updateSpec,filter=updateSpec.filter;if(0==add.length&&!filter)return this;if(sort&&(add=add.slice().sort(cmpRange)),this.isEmpty)return add.length?RangeSet.of(add):this;let cur=new LayerCursor(this,null,-1).goto(0),i=0,spill=[],builder=new RangeSetBuilder;for(;cur.value||i=0){let range=add[i++];builder.addInner(range.from,range.to,range.value)||spill.push(range)}else 1==cur.rangeIndex&&cur.chunkIndexthis.chunkEnd(cur.chunkIndex)||filterTocur.to||filterTo=start&&from<=start+chunk.length&&!1===chunk.between(start,from-start,to-start,f))return}this.nextLayer.between(from,to,f)}}iter(){let from=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return HeapCursor.from([this]).goto(from)}get isEmpty(){return this.nextLayer==this}static iter(sets){let from=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return HeapCursor.from(sets).goto(from)}static compare(oldSets,newSets,textDiff,comparator){let minPointSize=arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1,a=oldSets.filter((set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize)),b=newSets.filter((set=>set.maxPoint>0||!set.isEmpty&&set.maxPoint>=minPointSize)),sharedChunks=findSharedChunks(a,b,textDiff),sideA=new SpanCursor(a,sharedChunks,minPointSize),sideB=new SpanCursor(b,sharedChunks,minPointSize);textDiff.iterGaps(((fromA,fromB,length)=>compare(sideA,fromA,sideB,fromB,length,comparator))),textDiff.empty&&0==textDiff.length&&compare(sideA,0,sideB,0,0,comparator)}static eq(oldSets,newSets){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3?arguments[3]:void 0;null==to&&(to=999999999);let a=oldSets.filter((set=>!set.isEmpty&&newSets.indexOf(set)<0)),b=newSets.filter((set=>!set.isEmpty&&oldSets.indexOf(set)<0));if(a.length!=b.length)return!1;if(!a.length)return!0;let sharedChunks=findSharedChunks(a,b),sideA=new SpanCursor(a,sharedChunks,0).goto(from),sideB=new SpanCursor(b,sharedChunks,0).goto(from);for(;;){if(sideA.to!=sideB.to||!sameValues(sideA.active,sideB.active)||sideA.point&&(!sideB.point||!sideA.point.eq(sideB.point)))return!1;if(sideA.to>to)return!0;sideA.next(),sideB.next()}}static spans(sets,from,to,iterator){let cursor=new SpanCursor(sets,null,arguments.length>4&&void 0!==arguments[4]?arguments[4]:-1).goto(from),pos=from,openRanges=cursor.openStart;for(;;){let curTo=Math.min(cursor.to,to);if(cursor.point){let active=cursor.activeForPoint(cursor.to),openCount=cursor.pointFrompos&&(iterator.span(pos,curTo,cursor.active,openRanges),openRanges=cursor.openEnd(curTo));if(cursor.to>to)return openRanges+(cursor.point&&cursor.to>to?1:0);pos=cursor.to,cursor.next()}}static of(ranges){let sort=arguments.length>1&&void 0!==arguments[1]&&arguments[1],build=new RangeSetBuilder;for(let range of ranges instanceof Range$1?[ranges]:sort?function(ranges){if(ranges.length>1)for(let prev=ranges[0],i=1;i0)return ranges.slice().sort(cmpRange);prev=cur}return ranges}(ranges):ranges)build.add(range.from,range.to,range.value);return build.finish()}static join(sets){if(!sets.length)return RangeSet.empty;let result=sets[sets.length-1];for(let i=sets.length-2;i>=0;i--)for(let layer=sets[i];layer!=RangeSet.empty;layer=layer.nextLayer)result=new RangeSet(layer.chunkPos,layer.chunk,result,Math.max(layer.maxPoint,result.maxPoint));return result}}RangeSet.empty=new RangeSet([],[],null,-1),RangeSet.empty.nextLayer=RangeSet.empty;class RangeSetBuilder{finishChunk(newArrays){this.chunks.push(new Chunk(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,newArrays&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(from,to,value){this.addInner(from,to,value)||(this.nextLayer||(this.nextLayer=new RangeSetBuilder)).add(from,to,value)}addInner(from,to,value){let diff=from-this.lastTo||value.startSide-this.last.endSide;if(diff<=0&&(from-this.lastFrom||value.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return!(diff<0)&&(250==this.from.length&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=from),this.from.push(from-this.chunkStart),this.to.push(to-this.chunkStart),this.last=value,this.lastFrom=from,this.lastTo=to,this.value.push(value),value.point&&(this.maxPoint=Math.max(this.maxPoint,to-from)),!0)}addChunk(from,chunk){if((from-this.lastTo||chunk.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,chunk.maxPoint),this.chunks.push(chunk),this.chunkPos.push(from);let last=chunk.value.length-1;return this.last=chunk.value[last],this.lastFrom=chunk.from[last]+from,this.lastTo=chunk.to[last]+from,!0}finish(){return this.finishInner(RangeSet.empty)}finishInner(next){if(this.from.length&&this.finishChunk(!1),0==this.chunks.length)return next;let result=RangeSet.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(next):next,this.setMaxPoint);return this.from=null,result}}function findSharedChunks(a,b,textDiff){let inA=new Map;for(let set of a)for(let i=0;i3&&void 0!==arguments[3]?arguments[3]:0;this.layer=layer,this.skip=skip,this.minPoint=minPoint,this.rank=rank}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;return this.chunkIndex=this.rangeIndex=0,this.gotoInner(pos,side,!1),this}gotoInner(pos,side,forward){for(;this.chunkIndex=this.minPoint)break}}}setRangeIndex(index){if(index==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex1&&void 0!==arguments[1]?arguments[1]:null,minPoint=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,heap=[];for(let i=0;i=minPoint&&heap.push(new LayerCursor(cur,skip,minPoint,i));return 1==heap.length?heap[0]:new HeapCursor(heap)}get startSide(){return this.value?this.value.startSide:0}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;for(let cur of this.heap)cur.goto(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);return this.next(),this}forward(pos,side){for(let cur of this.heap)cur.forward(pos,side);for(let i=this.heap.length>>1;i>=0;i--)heapBubble(this.heap,i);(this.to-pos||this.value.endSide-side)<0&&this.next()}next(){if(0==this.heap.length)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let top=this.heap[0];this.from=top.from,this.to=top.to,this.value=top.value,this.rank=top.rank,top.value&&top.next(),heapBubble(this.heap,0)}}}function heapBubble(heap,index){for(let cur=heap[index];;){let childIndex=1+(index<<1);if(childIndex>=heap.length)break;let child=heap[childIndex];if(childIndex+1=0&&(child=heap[childIndex+1],childIndex++),cur.compare(child)<0)break;heap[childIndex]=cur,heap[index]=child,index=childIndex}}class SpanCursor{constructor(sets,skip,minPoint){this.minPoint=minPoint,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=HeapCursor.from(sets,skip,minPoint)}goto(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1e9;return this.cursor.goto(pos,side),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=pos,this.endSide=side,this.openStart=-1,this.next(),this}forward(pos,side){for(;this.minActive>-1&&(this.activeTo[this.minActive]-pos||this.active[this.minActive].endSide-side)<0;)this.removeActive(this.minActive);this.cursor.forward(pos,side)}removeActive(index){remove(this.active,index),remove(this.activeTo,index),remove(this.activeRank,index),this.minActive=findMinIndex(this.active,this.activeTo)}addActive(trackOpen){let i=0,{value:value,to:to,rank:rank}=this.cursor;for(;i0;)i++;insert(this.active,i,value),insert(this.activeTo,i,to),insert(this.activeRank,i,rank),trackOpen&&insert(trackOpen,i,this.cursor.from),this.minActive=findMinIndex(this.active,this.activeTo)}next(){let from=this.to,wasPoint=this.point;this.point=null;let trackOpen=this.openStart<0?[]:null;for(;;){let a=this.minActive;if(a>-1&&(this.activeTo[a]-this.cursor.from||this.active[a].endSide-this.cursor.startSide)<0){if(this.activeTo[a]>from){this.to=this.activeTo[a],this.endSide=this.active[a].endSide;break}this.removeActive(a),trackOpen&&remove(trackOpen,a)}else{if(!this.cursor.value){this.to=this.endSide=1e9;break}if(this.cursor.from>from){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}{let nextVal=this.cursor.value;if(nextVal.point){if(!(wasPoint&&this.cursor.to==this.to&&this.cursor.from=0&&trackOpen[i]=0&&!(this.activeRank[i]to||this.activeTo[i]==to&&this.active[i].endSide>=this.point.endSide)&&active.push(this.active[i]);return active.reverse()}openEnd(to){let open=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>to;i--)open++;return open}}function compare(a,startA,b,startB,length,comparator){a.goto(startA),b.goto(startB);let endB=startB+length,pos=startB,dPos=startB-startA;for(;;){let diff=a.to+dPos-b.to||a.endSide-b.endSide,end=diff<0?a.to+dPos:b.to,clipEnd=Math.min(end,endB);if(a.point||b.point?a.point&&b.point&&(a.point==b.point||a.point.eq(b.point))&&sameValues(a.activeForPoint(a.to),b.activeForPoint(b.to))||comparator.comparePoint(pos,clipEnd,a.point,b.point):clipEnd>pos&&!sameValues(a.active,b.active)&&comparator.compareRange(pos,clipEnd,a.active,b.active),end>endB)break;pos=end,diff<=0&&a.next(),diff>=0&&b.next()}}function sameValues(a,b){if(a.length!=b.length)return!1;for(let i=0;i=index;i--)array[i+1]=array[i];array[index]=value}function findMinIndex(value,array){let found=-1,foundPos=1e9;for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:string.length,n=0;for(let i=0;i=col)return i;if(i==string.length)break;n+=9==string.charCodeAt(i)?tabSize-n%tabSize:1,i=findClusterBreak(string,i)}return!0===strict?-1:string.length}const COUNT="undefined"==typeof Symbol?"__ͼ":Symbol.for("ͼ"),SET="undefined"==typeof Symbol?"__styleSet"+Math.floor(1e8*Math.random()):Symbol("styleSet"),top="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};class StyleModule{constructor(spec,options){this.rules=[];let{finish:finish}=options||{};function splitSelector(selector){return/^@/.test(selector)?[selector]:selector.split(/,\s*/)}function render(selectors,spec,target,isKeyframes){let local=[],isAt=/^@(\w+)\b/.exec(selectors[0]),keyframes=isAt&&"keyframes"==isAt[1];if(isAt&&null==spec)return target.push(selectors[0]+";");for(let prop in spec){let value=spec[prop];if(/&/.test(prop))render(prop.split(/,\s*/).map((part=>selectors.map((sel=>part.replace(/&/,sel))))).reduce(((a,b)=>a.concat(b))),value,target);else if(value&&"object"==typeof value){if(!isAt)throw new RangeError("The value of a property ("+prop+") should be a primitive value.");render(splitSelector(prop),value,local,keyframes)}else null!=value&&local.push(prop.replace(/_.*/,"").replace(/[A-Z]/g,(l=>"-"+l.toLowerCase()))+": "+value+";")}(local.length||keyframes)&&target.push((!finish||isAt||isKeyframes?selectors:selectors.map(finish)).join(", ")+" {"+local.join(" ")+"}")}for(let prop in spec)render(splitSelector(prop),spec[prop],this.rules)}getRules(){return this.rules.join("\n")}static newName(){let id=top[COUNT]||1;return top[COUNT]=id+1,"ͼ"+id.toString(36)}static mount(root,modules,options){let set=root[SET],nonce=options&&options.nonce;set?nonce&&set.setNonce(nonce):set=new StyleSet(root,nonce),set.mount(Array.isArray(modules)?modules:[modules],root)}}let adoptedSet=new Map;class StyleSet{constructor(root,nonce){let doc=root.ownerDocument||root,win=doc.defaultView;if(!root.head&&root.adoptedStyleSheets&&win.CSSStyleSheet){let adopted=adoptedSet.get(doc);if(adopted)return root[SET]=adopted;this.sheet=new win.CSSStyleSheet,adoptedSet.set(doc,this)}else this.styleTag=doc.createElement("style"),nonce&&this.styleTag.setAttribute("nonce",nonce);this.modules=[],root[SET]=this}mount(modules,root){let sheet=this.sheet,pos=0,j=0;for(let i=0;i-1&&(this.modules.splice(index,1),j--,index=-1),-1==index){if(this.modules.splice(j++,0,mod),sheet)for(let k=0;k",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},mac="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),ie$1="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(i=1;i<=24;i++)base[i+111]="F"+i;for(i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift[i]=String.fromCharCode(i);for(var code in base)shift.hasOwnProperty(code)||(shift[code]=base[code]);function getSelection(root){let target;return target=11==root.nodeType?root.getSelection?root:root.ownerDocument:root,target.getSelection()}function contains(dom,node){return!!node&&(dom==node||dom.contains(1!=node.nodeType?node.parentNode:node))}function hasSelection(dom,selection){if(!selection.anchorNode)return!1;try{return contains(dom,selection.anchorNode)}catch(_){return!1}}function clientRectsFor(dom){return 3==dom.nodeType?textRange(dom,0,dom.nodeValue.length).getClientRects():1==dom.nodeType?dom.getClientRects():[]}function isEquivalentPosition(node,off,targetNode,targetOff){return!!targetNode&&(scanFor(node,off,targetNode,targetOff,-1)||scanFor(node,off,targetNode,targetOff,1))}function domIndex(node){for(var index=0;;index++)if(!(node=node.previousSibling))return index}function isBlockElement(node){return 1==node.nodeType&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName)}function scanFor(node,off,targetNode,targetOff,dir){for(;;){if(node==targetNode&&off==targetOff)return!0;if(off==(dir<0?0:maxOffset(node))){if("DIV"==node.nodeName)return!1;let parent=node.parentNode;if(!parent||1!=parent.nodeType)return!1;off=domIndex(node)+(dir<0?0:1),node=parent}else{if(1!=node.nodeType)return!1;if(1==(node=node.childNodes[off+(dir<0?-1:0)]).nodeType&&"false"==node.contentEditable)return!1;off=dir<0?maxOffset(node):0}}}function maxOffset(node){return 3==node.nodeType?node.nodeValue.length:node.childNodes.length}function flattenRect(rect,left){let x=left?rect.left:rect.right;return{left:x,right:x,top:rect.top,bottom:rect.bottom}}function windowRect(win){let vp=win.visualViewport;return vp?{left:0,right:vp.width,top:0,bottom:vp.height}:{left:0,right:win.innerWidth,top:0,bottom:win.innerHeight}}function getScale(elt,rect){let scaleX=rect.width/elt.offsetWidth,scaleY=rect.height/elt.offsetHeight;return(scaleX>.995&&scaleX<1.005||!isFinite(scaleX)||Math.abs(rect.width-elt.offsetWidth)<1)&&(scaleX=1),(scaleY>.995&&scaleY<1.005||!isFinite(scaleY)||Math.abs(rect.height-elt.offsetHeight)<1)&&(scaleY=1),{scaleX:scaleX,scaleY:scaleY}}class DOMSelectionState{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(domSel){return this.anchorNode==domSel.anchorNode&&this.anchorOffset==domSel.anchorOffset&&this.focusNode==domSel.focusNode&&this.focusOffset==domSel.focusOffset}setRange(range){let{anchorNode:anchorNode,focusNode:focusNode}=range;this.set(anchorNode,Math.min(range.anchorOffset,anchorNode?maxOffset(anchorNode):0),focusNode,Math.min(range.focusOffset,focusNode?maxOffset(focusNode):0))}set(anchorNode,anchorOffset,focusNode,focusOffset){this.anchorNode=anchorNode,this.anchorOffset=anchorOffset,this.focusNode=focusNode,this.focusOffset=focusOffset}}let scratchRange,preventScrollSupported=null;function focusPreventScroll(dom){if(dom.setActive)return dom.setActive();if(preventScrollSupported)return dom.focus(preventScrollSupported);let stack=[];for(let cur=dom;cur&&(stack.push(cur,cur.scrollTop,cur.scrollLeft),cur!=cur.ownerDocument);cur=cur.parentNode);if(dom.focus(null==preventScrollSupported?{get preventScroll(){return preventScrollSupported={preventScroll:!0},!0}}:void 0),!preventScrollSupported){preventScrollSupported=!1;for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:from,range=scratchRange||(scratchRange=document.createRange());return range.setEnd(node,to),range.setStart(node,from),range}function dispatchKey(elt,name,code,mods){let options={key:name,code:name,keyCode:code,which:code,cancelable:!0};mods&&({altKey:options.altKey,ctrlKey:options.ctrlKey,shiftKey:options.shiftKey,metaKey:options.metaKey}=mods);let down=new KeyboardEvent("keydown",options);down.synthetic=!0,elt.dispatchEvent(down);let up=new KeyboardEvent("keyup",options);return up.synthetic=!0,elt.dispatchEvent(up),down.defaultPrevented||up.defaultPrevented}function clearAttributes(node){for(;node.attributes.length;)node.removeAttributeNode(node.attributes[0])}function isScrolledToBottom(elt){return elt.scrollTop>Math.max(1,elt.scrollHeight-elt.clientHeight-4)}function textNodeBefore(startNode,startOffset){for(let node=startNode,offset=startOffset;;){if(3==node.nodeType&&offset>0)return{node:node,offset:offset};if(1==node.nodeType&&offset>0){if("false"==node.contentEditable)return null;node=node.childNodes[offset-1],offset=maxOffset(node)}else{if(!node.parentNode||isBlockElement(node))return null;offset=domIndex(node),node=node.parentNode}}}function textNodeAfter(startNode,startOffset){for(let node=startNode,offset=startOffset;;){if(3==node.nodeType&&offset2&&void 0!==arguments[2])||arguments[2];this.node=node,this.offset=offset,this.precise=precise}static before(dom,precise){return new DOMPos(dom.parentNode,domIndex(dom),precise)}static after(dom,precise){return new DOMPos(dom.parentNode,domIndex(dom)+1,precise)}}const noChildren=[];class ContentView{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(view){let pos=this.posAtStart;for(let child of this.children){if(child==view)return pos;pos+=child.length+child.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(view){return this.posBefore(view)+view.length}sync(view,track){if(2&this.flags){let next,parent=this.dom,prev=null;for(let child of this.children){if(7&child.flags){if(!child.dom&&(next=prev?prev.nextSibling:parent.firstChild)){let contentView=ContentView.get(next);(!contentView||!contentView.parent&&contentView.canReuseDOM(child))&&child.reuseDOM(next)}child.sync(view,track),child.flags&=-8}if(next=prev?prev.nextSibling:parent.firstChild,track&&!track.written&&track.node==parent&&next!=child.dom&&(track.written=!0),child.dom.parentNode==parent)for(;next&&next!=child.dom;)next=rm$1(next);else parent.insertBefore(child.dom,next);prev=child.dom}for(next=prev?prev.nextSibling:parent.firstChild,next&&track&&track.node==parent&&(track.written=!0);next;)next=rm$1(next)}else if(1&this.flags)for(let child of this.children)7&child.flags&&(child.sync(view,track),child.flags&=-8)}reuseDOM(_dom){}localPosFromDOM(node,offset){let after;if(node==this.dom)after=this.dom.childNodes[offset];else{let bias=0==maxOffset(node)?0:0==offset?-1:1;for(;;){let parent=node.parentNode;if(parent==this.dom)break;0==bias&&parent.firstChild!=parent.lastChild&&(bias=node==parent.firstChild?-1:1),node=parent}after=bias<0?node:node.nextSibling}if(after==this.dom.firstChild)return 0;for(;after&&!ContentView.get(after);)after=after.nextSibling;if(!after)return this.length;for(let i=0,pos=0;;i++){let child=this.children[i];if(child.dom==after)return pos;pos+=child.length+child.breakAfter}}domBoundsAround(from,to){let offset=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,fromI=-1,fromStart=-1,toI=-1,toEnd=-1;for(let i=0,pos=offset,prevEnd=offset;ito)return child.domBoundsAround(from,to,pos);if(end>=from&&-1==fromI&&(fromI=i,fromStart=pos),pos>to&&child.dom.parentNode==this.dom){toI=i,toEnd=prevEnd;break}prevEnd=end,pos=end+child.breakAfter}return{from:fromStart,to:toEnd<0?offset+this.length:toEnd,startDOM:(fromI?this.children[fromI-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:toI=0?this.children[toI].dom:null}}markDirty(){let andParent=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.flags|=2,this.markParentsDirty(andParent)}markParentsDirty(childList){for(let parent=this.parent;parent;parent=parent.parent){if(childList&&(parent.flags|=2),1&parent.flags)return;parent.flags|=1,childList=!1}}setParent(parent){this.parent!=parent&&(this.parent=parent,7&this.flags&&this.markParentsDirty(!0))}setDOM(dom){this.dom!=dom&&(this.dom&&(this.dom.cmView=null),this.dom=dom,dom.cmView=this)}get rootView(){for(let v=this;;){let parent=v.parent;if(!parent)return v;v=parent}}replaceChildren(from,to){let children=arguments.length>2&&void 0!==arguments[2]?arguments[2]:noChildren;this.markDirty();for(let i=from;i0&&void 0!==arguments[0]?arguments[0]:this.length;return new ChildCursor(this.children,pos,this.children.length)}childPos(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.childCursor().findPos(pos,bias)}toString(){let name=this.constructor.name.replace("View","");return name+(this.children.length?"("+this.children.join()+")":this.length?"["+("Text"==name?this.text:this.length)+"]":"")+(this.breakAfter?"#":"")}static get(node){return node.cmView}get isEditable(){return!0}get isWidget(){return!1}get isHidden(){return!1}merge(from,to,source,hasStart,openStart,openEnd){return!1}become(other){return!1}canReuseDOM(other){return other.constructor==this.constructor&&!(8&(this.flags|other.flags))}getSide(){return 0}destroy(){for(let child of this.children)child.parent==this&&child.destroy();this.parent=null}}function rm$1(dom){let next=dom.nextSibling;return dom.parentNode.removeChild(dom),next}ContentView.prototype.breakAfter=0;class ChildCursor{constructor(children,pos,i){this.children=children,this.pos=pos,this.i=i,this.off=0}findPos(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;for(;;){if(pos>this.pos||pos==this.pos&&(bias>0||0==this.i||this.children[this.i-1].breakAfter))return this.off=pos-this.pos,this;let next=this.children[--this.i];this.pos-=next.length+next.breakAfter}}}function replaceRange(parent,fromI,fromOff,toI,toOff,insert,breakAtStart,openStart,openEnd){let{children:children}=parent,before=children.length?children[fromI]:null,last=insert.length?insert[insert.length-1]:null,breakAtEnd=last?last.breakAfter:breakAtStart;if(!(fromI==toI&&before&&!breakAtStart&&!breakAtEnd&&insert.length<2&&before.merge(fromOff,toOff,insert.length?last:null,0==fromOff,openStart,openEnd))){if(toI0&&(!breakAtStart&&insert.length&&before.merge(fromOff,before.length,insert[0],!1,openStart,0)?before.breakAfter=insert.shift().breakAfter:(fromOff2);var browser={mac:ios||/Mac/.test(nav.platform),windows:/Win/.test(nav.platform),linux:/Linux|X11/.test(nav.platform),ie:ie,ie_version:ie_upto10?doc.documentMode||6:ie_11up?+ie_11up[1]:ie_edge?+ie_edge[1]:0,gecko:gecko,gecko_version:gecko?+(/Firefox\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,chrome:!!chrome,chrome_version:chrome?+chrome[1]:0,ios:ios,android:/Android\b/.test(nav.userAgent),webkit:webkit,safari:safari,webkit_version:webkit?+(/\bAppleWebKit\/(\d+)/.exec(nav.userAgent)||[0,0])[1]:0,tabSize:null!=doc.documentElement.style.tabSize?"tab-size":"-moz-tab-size"};class TextView extends ContentView{constructor(text){super(),this.text=text}get length(){return this.text.length}createDOM(textDOM){this.setDOM(textDOM||document.createTextNode(this.text))}sync(view,track){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(track&&track.node==this.dom&&(track.written=!0),this.dom.nodeValue=this.text)}reuseDOM(dom){3==dom.nodeType&&this.createDOM(dom)}merge(from,to,source){return!(8&this.flags||source&&(!(source instanceof TextView)||this.length-(to-from)+source.length>256||8&source.flags))&&(this.text=this.text.slice(0,from)+(source?source.text:"")+this.text.slice(to),this.markDirty(),!0)}split(from){let result=new TextView(this.text.slice(from));return this.text=this.text.slice(0,from),this.markDirty(),result.flags|=8&this.flags,result}localPosFromDOM(node,offset){return node==this.dom?offset:offset?this.text.length:0}domAtPos(pos){return new DOMPos(this.dom,pos)}domBoundsAround(_from,_to,offset){return{from:offset,to:offset+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(pos,side){return function(text,pos,side){let length=text.nodeValue.length;pos>length&&(pos=length);let from=pos,to=pos,flatten=0;0==pos&&side<0||pos==length&&side>=0?browser.chrome||browser.gecko||(pos?(from--,flatten=1):to=0)?0:rects.length-1];browser.safari&&!flatten&&0==rect.width&&(rect=Array.prototype.find.call(rects,(r=>r.width))||rect);return flatten?flattenRect(rect,flatten<0):rect||null}(this.dom,pos,side)}}class MarkView extends ContentView{constructor(mark){let children=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],length=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;super(),this.mark=mark,this.children=children,this.length=length;for(let ch of children)ch.setParent(this)}setAttrs(dom){if(clearAttributes(dom),this.mark.class&&(dom.className=this.mark.class),this.mark.attrs)for(let name in this.mark.attrs)dom.setAttribute(name,this.mark.attrs[name]);return dom}canReuseDOM(other){return super.canReuseDOM(other)&&!(8&(this.flags|other.flags))}reuseDOM(node){node.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(node),this.flags|=6)}sync(view,track){this.dom?4&this.flags&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(view,track)}merge(from,to,source,_hasStart,openStart,openEnd){return(!source||!(!(source instanceof MarkView&&source.mark.eq(this.mark))||from&&openStart<=0||tofrom&&result.push(off=from&&(detachFrom=i),off=end,i++}let length=this.length-from;return this.length=from,detachFrom>-1&&(this.children.length=detachFrom,this.markDirty()),new MarkView(this.mark,result,length)}domAtPos(pos){return inlineDOMAtPos(this,pos)}coordsAt(pos,side){return coordsInChildren(this,pos,side)}}class WidgetView extends ContentView{static create(widget,length,side){return new WidgetView(widget,length,side)}constructor(widget,length,side){super(),this.widget=widget,this.length=length,this.side=side,this.prevWidget=null}split(from){let result=WidgetView.create(this.widget,this.length-from,this.side);return this.length-=from,result}sync(view){this.dom&&this.widget.updateDOM(this.dom,view)||(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(view)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(from,to,source,hasStart,openStart,openEnd){return!(source&&(!(source instanceof WidgetView&&this.widget.compare(source.widget))||from>0&&openStart<=0||to0)?DOMPos.before(this.dom):DOMPos.after(this.dom,pos==this.length)}domBoundsAround(){return null}coordsAt(pos,side){let custom=this.widget.coordsAt(this.dom,pos,side);if(custom)return custom;let rects=this.dom.getClientRects(),rect=null;if(!rects.length)return null;let fromBack=this.side?this.side<0:pos>0;for(let i=fromBack?rects.length-1:0;rect=rects[i],!(pos>0?0==i:i==rects.length-1||rect.top0?DOMPos.before(this.dom):DOMPos.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(pos){return this.dom.getBoundingClientRect()}get overrideDOMText(){return Text.empty}get isHidden(){return!0}}function inlineDOMAtPos(parent,pos){let dom=parent.dom,{children:children}=parent,i=0;for(let off=0;ioff&&pos0;j--){let prev=children[j-1];if(prev.dom.parentNode==dom)return prev.domAtPos(prev.length)}for(let j=i;j0&&view instanceof MarkView&&children.length&&(last=children[children.length-1])instanceof MarkView&&last.mark.eq(view.mark)?joinInlineInto(last,view.children[0],open-1):(children.push(view),view.setParent(parent)),parent.length+=view.length}function coordsInChildren(view,pos,side){let before=null,beforePos=-1,after=null,afterPos=-1;!function scan(view,pos){for(let i=0,off=0;i=pos&&(child.children.length?scan(child,pos-off):(!after||after.isHidden&&side>0)&&(end>pos||off==end&&child.getSide()>0)?(after=child,afterPos=pos-off):(off-1?1:0)!=keysB.length-(ignore&&keysB.indexOf(ignore)>-1?1:0))return!1;for(let key of keysA)if(key!=ignore&&(-1==keysB.indexOf(key)||a[key]!==b[key]))return!1;return!0}function updateAttrs(dom,prev,attrs){let changed=!1;if(prev)for(let name in prev)attrs&&name in attrs||(changed=!0,"style"==name?dom.style.cssText="":dom.removeAttribute(name));if(attrs)for(let name in attrs)prev&&prev[name]==attrs[name]||(changed=!0,"style"==name?dom.style.cssText=attrs[name]:dom.setAttribute(name,attrs[name]));return changed}function getAttrs$1(dom){let attrs=Object.create(null);for(let i=0;i0&&0==this.children[i-1].length;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=at,end}transferDOM(other){this.dom&&(this.markDirty(),other.setDOM(this.dom),other.prevAttrs=void 0===this.prevAttrs?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(attrs){attrsEq(this.attrs,attrs)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=attrs)}append(child,openStart){joinInlineInto(this,child,openStart)}addLineDeco(deco){let attrs=deco.spec.attributes,cls=deco.spec.class;attrs&&(this.attrs=combineAttrs(attrs,this.attrs||{})),cls&&(this.attrs=combineAttrs({class:cls},this.attrs||{}))}domAtPos(pos){return inlineDOMAtPos(this,pos)}reuseDOM(node){"DIV"==node.nodeName&&(this.setDOM(node),this.flags|=6)}sync(view,track){var _a;this.dom?4&this.flags&&(clearAttributes(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),void 0!==this.prevAttrs&&(updateAttrs(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(view,track);let last=this.dom.lastChild;for(;last&&ContentView.get(last)instanceof MarkView;)last=last.lastChild;if(!(last&&this.length&&("BR"==last.nodeName||0!=(null===(_a=ContentView.get(last))||void 0===_a?void 0:_a.isEditable)||browser.ios&&this.children.some((ch=>ch instanceof TextView))))){let hack=document.createElement("BR");hack.cmIgnore=!0,this.dom.appendChild(hack)}}measureTextSize(){if(0==this.children.length||this.length>20)return null;let textHeight,totalWidth=0;for(let child of this.children){if(!(child instanceof TextView)||/[^ -~]/.test(child.text))return null;let rects=clientRectsFor(child.dom);if(1!=rects.length)return null;totalWidth+=rects[0].width,textHeight=rects[0].height}return totalWidth?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:totalWidth/this.length,textHeight:textHeight}:null}coordsAt(pos,side){let rect=coordsInChildren(this,pos,side);if(!this.children.length&&rect&&this.parent){let{heightOracle:heightOracle}=this.parent.view.viewState,height=rect.bottom-rect.top;if(Math.abs(height-heightOracle.lineHeight)<2&&heightOracle.textHeight=pos){if(block instanceof LineView)return block;if(end>pos)break}off=end+block.breakAfter}return null}}class BlockWidgetView extends ContentView{constructor(widget,length,deco){super(),this.widget=widget,this.length=length,this.deco=deco,this.breakAfter=0,this.prevWidget=null}merge(from,to,source,_takeDeco,openStart,openEnd){return!(source&&(!(source instanceof BlockWidgetView&&this.widget.compare(source.widget))||from>0&&openStart<=0||to0)}}class WidgetType{eq(widget){return!1}updateDOM(dom,view){return!1}compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(event){return!0}coordsAt(dom,pos,side){return null}get isHidden(){return!1}get editable(){return!1}destroy(dom){}}var BlockType=function(BlockType){return BlockType[BlockType.Text=0]="Text",BlockType[BlockType.WidgetBefore=1]="WidgetBefore",BlockType[BlockType.WidgetAfter=2]="WidgetAfter",BlockType[BlockType.WidgetRange=3]="WidgetRange",BlockType}(BlockType||(BlockType={}));class Decoration extends RangeValue{constructor(startSide,endSide,widget,spec){super(),this.startSide=startSide,this.endSide=endSide,this.widget=widget,this.spec=spec}get heightRelevant(){return!1}static mark(spec){return new MarkDecoration(spec)}static widget(spec){let side=Math.max(-1e4,Math.min(1e4,spec.side||0)),block=!!spec.block;return side+=block&&!spec.inlineOrder?side>0?3e8:-4e8:side>0?1e8:-1e8,new PointDecoration(spec,side,side,block,spec.widget||null,!1)}static replace(spec){let startSide,endSide,block=!!spec.block;if(spec.isBlockGap)startSide=-5e8,endSide=4e8;else{let{start:start,end:end}=getInclusive(spec,block);startSide=(start?block?-3e8:-1:5e8)-1,endSide=1+(end?block?2e8:1:-6e8)}return new PointDecoration(spec,startSide,endSide,block,spec.widget||null,!0)}static line(spec){return new LineDecoration(spec)}static set(of){let sort=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return RangeSet.of(of,sort)}hasHeight(){return!!this.widget&&this.widget.estimatedHeight>-1}}Decoration.none=RangeSet.empty;class MarkDecoration extends Decoration{constructor(spec){let{start:start,end:end}=getInclusive(spec);super(start?-1:5e8,end?1:-6e8,null,spec),this.tagName=spec.tagName||"span",this.class=spec.class||"",this.attrs=spec.attributes||null}eq(other){var _a,_b;return this==other||other instanceof MarkDecoration&&this.tagName==other.tagName&&(this.class||(null===(_a=this.attrs)||void 0===_a?void 0:_a.class))==(other.class||(null===(_b=other.attrs)||void 0===_b?void 0:_b.class))&&attrsEq(this.attrs,other.attrs,"class")}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(from>=to)throw new RangeError("Mark decorations may not be empty");return super.range(from,to)}}MarkDecoration.prototype.point=!1;class LineDecoration extends Decoration{constructor(spec){super(-2e8,-2e8,null,spec)}eq(other){return other instanceof LineDecoration&&this.spec.class==other.spec.class&&attrsEq(this.spec.attributes,other.spec.attributes)}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(to!=from)throw new RangeError("Line decoration ranges must be zero-length");return super.range(from,to)}}LineDecoration.prototype.mapMode=MapMode.TrackBefore,LineDecoration.prototype.point=!0;class PointDecoration extends Decoration{constructor(spec,startSide,endSide,block,widget,isReplace){super(startSide,endSide,widget,spec),this.block=block,this.isReplace=isReplace,this.mapMode=block?startSide<=0?MapMode.TrackBefore:MapMode.TrackAfter:MapMode.TrackDel}get type(){return this.startSide!=this.endSide?BlockType.WidgetRange:this.startSide<=0?BlockType.WidgetBefore:BlockType.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(other){return other instanceof PointDecoration&&(a=this.widget,b=other.widget,a==b||!!(a&&b&&a.compare(b)))&&this.block==other.block&&this.startSide==other.startSide&&this.endSide==other.endSide;var a,b}range(from){let to=arguments.length>1&&void 0!==arguments[1]?arguments[1]:from;if(this.isReplace&&(from>to||from==to&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&to!=from)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(from,to)}}function getInclusive(spec){let block=arguments.length>1&&void 0!==arguments[1]&&arguments[1],{inclusiveStart:start,inclusiveEnd:end}=spec;return null==start&&(start=spec.inclusive),null==end&&(end=spec.inclusive),{start:null!=start?start:block,end:null!=end?end:block}}function addRange(from,to,ranges){let margin=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,last=ranges.length-1;last>=0&&ranges[last]+margin>=from?ranges[last]=Math.max(ranges[last],to):ranges.push(from,to)}PointDecoration.prototype.point=!0;class ContentBuilder{constructor(doc,pos,end,disallowBlockEffectsFor){this.doc=doc,this.pos=pos,this.end=end,this.disallowBlockEffectsFor=disallowBlockEffectsFor,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=doc.iter(),this.skip=pos}posCovered(){if(0==this.content.length)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let last=this.content[this.content.length-1];return!(last.breakAfter||last instanceof BlockWidgetView&&last.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new LineView),this.atCursorPos=!0),this.curLine}flushBuffer(){let active=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.bufferMarks;this.pendingBuffer&&(this.curLine.append(wrapMarks(new WidgetBufferView(-1),active),active.length),this.pendingBuffer=0)}addBlockWidget(view){this.flushBuffer(),this.curLine=null,this.content.push(view)}finish(openEnd){this.pendingBuffer&&openEnd<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,this.posCovered()||openEnd&&this.content.length&&this.content[this.content.length-1]instanceof BlockWidgetView||this.getLine()}buildText(length,active,openStart){for(;length>0;){if(this.textOff==this.text.length){let{value:value,lineBreak:lineBreak,done:done}=this.cursor.next(this.skip);if(this.skip=0,done)throw new Error("Ran out of text content when drawing inline views");if(lineBreak){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,length--;continue}this.text=value,this.textOff=0}let take=Math.min(this.text.length-this.textOff,length,512);this.flushBuffer(active.slice(active.length-openStart)),this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff,this.textOff+take)),active),openStart),this.atCursorPos=!0,this.textOff+=take,length-=take,openStart=0}}span(from,to,active,openStart){this.buildText(to-from,active,openStart),this.pos=to,this.openStart<0&&(this.openStart=openStart)}point(from,to,deco,active,openStart,index){if(this.disallowBlockEffectsFor[index]&&deco instanceof PointDecoration){if(deco.block)throw new RangeError("Block decorations may not be specified via plugins");if(to>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let len=to-from;if(deco instanceof PointDecoration)if(deco.block)deco.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new BlockWidgetView(deco.widget||NullWidget.block,len,deco));else{let view=WidgetView.create(deco.widget||NullWidget.inline,len,len?0:deco.startSide),cursorBefore=this.atCursorPos&&!view.isEditable&&openStart<=active.length&&(from0),cursorAfter=!view.isEditable&&(fromactive.length||deco.startSide<=0),line=this.getLine();2!=this.pendingBuffer||cursorBefore||view.isEditable||(this.pendingBuffer=0),this.flushBuffer(active),cursorBefore&&(line.append(wrapMarks(new WidgetBufferView(1),active),openStart),openStart=active.length+Math.max(0,openStart-active.length)),line.append(wrapMarks(view,active),openStart),this.atCursorPos=cursorAfter,this.pendingBuffer=cursorAfter?fromactive.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=active.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(deco);len&&(this.textOff+len<=this.text.length?this.textOff+=len:(this.skip+=len-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=to),this.openStart<0&&(this.openStart=openStart)}static build(text,from,to,decorations,dynamicDecorationMap){let builder=new ContentBuilder(text,from,to,dynamicDecorationMap);return builder.openEnd=RangeSet.spans(decorations,from,to,builder),builder.openStart<0&&(builder.openStart=builder.openEnd),builder.finish(builder.openEnd),builder}}function wrapMarks(view,active){for(let mark of active)view=new MarkView(mark,[view],view.length);return view}class NullWidget extends WidgetType{constructor(tag){super(),this.tag=tag}eq(other){return other.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(elt){return elt.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}NullWidget.inline=new NullWidget("span"),NullWidget.block=new NullWidget("div");var Direction=function(Direction){return Direction[Direction.LTR=0]="LTR",Direction[Direction.RTL=1]="RTL",Direction}(Direction||(Direction={}));const LTR=Direction.LTR,RTL=Direction.RTL;function dec(str){let result=[];for(let i=0;i=index){if(span.level==level)return i;(maybe<0||(0!=assoc?assoc<0?span.fromindex:order[maybe].level>span.level))&&(maybe=i)}}if(maybe<0)throw new RangeError("Index out of range");return maybe}}function isolatesEq(a,b){if(a.length!=b.length)return!1;for(let i=0;iiCh&&order.push(new BidiSpan(iCh,iso.from,localLevel)),computeSectionOrder(line,iso.direction==LTR!=!(localLevel%2)?level+1:level,baseLevel,iso.inner,iso.from,iso.to,order),iCh=iso.to}iScan=iso.to}else{if(iScan==to||(sameDir?types[iScan]!=ourType:types[iScan]==ourType))break;iScan++}recurse?emitSpans(line,iCh,iScan,level+1,baseLevel,recurse,order):iChfrom;){let sameDir=!0,isNum=!1;if(!iI||iCh>isolates[iI-1].to){let next=types[iCh-1];next!=ourType&&(sameDir=!1,isNum=16==next)}let recurse=sameDir||1!=ourType?null:[],localLevel=sameDir?level:level+1,iScan=iCh;run:for(;;)if(iI&&iScan==isolates[iI-1].to){if(isNum)break run;let iso=isolates[--iI];if(!sameDir)for(let upto=iso.from,jI=iI;;){if(upto==from)break run;if(!jI||isolates[jI-1].to!=upto){if(types[upto-1]==ourType)break run;break}upto=isolates[--jI].from}if(recurse)recurse.push(iso);else{iso.to=0;sJ-=3)if(BracketStack[sJ+1]==-br){let flags=BracketStack[sJ+2],type=2&flags?outerType:4&flags?1&flags?oppositeType:outerType:0;type&&(types[i]=types[BracketStack[sJ]]=type),sI=sJ;break}}else{if(189==BracketStack.length)break;BracketStack[sI++]=i,BracketStack[sI++]=ch,BracketStack[sI++]=context}else if(2==(type=types[i])||1==type){let embed=type==outerType;context=embed?0:1;for(let sJ=sI-3;sJ>=0;sJ-=3){let cur=BracketStack[sJ+2];if(2&cur)break;if(embed)BracketStack[sJ+2]|=2;else{if(4&cur)break;BracketStack[sJ+2]|=4}}}}}(line,from,to,isolates,outerType),function(rFrom,rTo,isolates,outerType){for(let iI=0,prev=outerType;iI<=isolates.length;iI++){let from=iI?isolates[iI-1].to:rFrom,to=iIi;)j==fromJ&&(j=isolates[--jI].from,fromJ=jI?isolates[jI-1].to:rFrom),types[--j]=replace;i=end}else prev=type,i++}}}(from,to,isolates,outerType),emitSpans(line,from,to,level,baseLevel,isolates,order)}function trivialOrder(length){return[new BidiSpan(0,length,0)]}let movedOver="";function moveVisually(line,order,dir,start,forward){var _a;let startIndex=start.head-line.from,spanI=BidiSpan.find(order,startIndex,null!==(_a=start.bidiLevel)&&void 0!==_a?_a:-1,start.assoc),span=order[spanI],spanEnd=span.side(forward,dir);if(startIndex==spanEnd){let nextI=spanI+=forward?1:-1;if(nextI<0||nextI>=order.length)return null;span=order[spanI=nextI],startIndex=span.side(!forward,dir),spanEnd=span.side(forward,dir)}let nextIndex=findClusterBreak(line.text,startIndex,span.forward(forward,dir));(nextIndexspan.to)&&(nextIndex=spanEnd),movedOver=line.text.slice(Math.min(startIndex,nextIndex),Math.max(startIndex,nextIndex));let nextSpan=spanI==(forward?order.length-1:0)?null:order[spanI+(forward?1:-1)];return nextSpan&&nextIndex==spanEnd&&nextSpan.level+(forward?0:1)values.some((x=>x))}),nativeSelectionHidden=Facet.define({combine:values=>values.some((x=>x))}),scrollHandler=Facet.define();class ScrollTarget{constructor(range){let y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"nearest",x=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"nearest",yMargin=arguments.length>3&&void 0!==arguments[3]?arguments[3]:5,xMargin=arguments.length>4&&void 0!==arguments[4]?arguments[4]:5,isSnapshot=arguments.length>5&&void 0!==arguments[5]&&arguments[5];this.range=range,this.y=y,this.x=x,this.yMargin=yMargin,this.xMargin=xMargin,this.isSnapshot=isSnapshot}map(changes){return changes.empty?this:new ScrollTarget(this.range.map(changes),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(state){return this.range.to<=state.doc.length?this:new ScrollTarget(EditorSelection.cursor(state.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const scrollIntoView$1=StateEffect.define({map:(t,ch)=>t.map(ch)}),setEditContextFormatting=StateEffect.define();function logException(state,exception,context){let handler=state.facet(exceptionSink);handler.length?handler[0](exception):window.onerror?window.onerror(String(exception),context,void 0,void 0,exception):context?console.error(context+":",exception):console.error(exception)}const editable=Facet.define({combine:values=>!values.length||values[0]});let nextPluginID=0;const viewPlugin=Facet.define();class ViewPlugin{constructor(id,create,domEventHandlers,domEventObservers,buildExtensions){this.id=id,this.create=create,this.domEventHandlers=domEventHandlers,this.domEventObservers=domEventObservers,this.extension=buildExtensions(this)}static define(create,spec){const{eventHandlers:eventHandlers,eventObservers:eventObservers,provide:provide,decorations:deco}=spec||{};return new ViewPlugin(nextPluginID++,create,eventHandlers,eventObservers,(plugin=>{let ext=[viewPlugin.of(plugin)];return deco&&ext.push(decorations.of((view=>{let pluginInst=view.plugin(plugin);return pluginInst?deco(pluginInst):Decoration.none}))),provide&&ext.push(provide(plugin)),ext}))}static fromClass(cls,spec){return ViewPlugin.define((view=>new cls(view)),spec)}}class PluginInstance{constructor(spec){this.spec=spec,this.mustUpdate=null,this.value=null}update(view){if(this.value){if(this.mustUpdate){let update=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(update)}catch(e){if(logException(update.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch(_){}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(view)}catch(e){logException(view.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(view){var _a;if(null===(_a=this.value)||void 0===_a?void 0:_a.destroy)try{this.value.destroy()}catch(e){logException(view.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const editorAttributes=Facet.define(),contentAttributes=Facet.define(),decorations=Facet.define(),outerDecorations=Facet.define(),atomicRanges=Facet.define(),bidiIsolatedRanges=Facet.define();function getIsolatedRanges(view,line){let isolates=view.state.facet(bidiIsolatedRanges);if(!isolates.length)return isolates;let sets=isolates.map((i=>i instanceof Function?i(view):i)),result=[];return RangeSet.spans(sets,line.from,line.to,{point(){},span(fromDoc,toDoc,active,open){let from=fromDoc-line.from,to=toDoc-line.from,level=result;for(let i=active.length-1;i>=0;i--,open--){let update,direction=active[i].spec.bidiIsolate;if(null==direction&&(direction=autoDirection(line.text,from,to)),open>0&&level.length&&(update=level[level.length-1]).to==from&&update.direction==direction)update.to=to,level=update.inner;else{let add={from:from,to:to,direction:direction,inner:[]};level.push(add),level=add.inner}}}}),result}const scrollMargins=Facet.define();function getScrollMargins(view){let left=0,right=0,top=0,bottom=0;for(let source of view.state.facet(scrollMargins)){let m=source(view);m&&(null!=m.left&&(left=Math.max(left,m.left)),null!=m.right&&(right=Math.max(right,m.right)),null!=m.top&&(top=Math.max(top,m.top)),null!=m.bottom&&(bottom=Math.max(bottom,m.bottom)))}return{left:left,right:right,top:top,bottom:bottom}}const styleModule=Facet.define();class ChangedRange{constructor(fromA,toA,fromB,toB){this.fromA=fromA,this.toA=toA,this.fromB=fromB,this.toB=toB}join(other){return new ChangedRange(Math.min(this.fromA,other.fromA),Math.max(this.toA,other.toA),Math.min(this.fromB,other.fromB),Math.max(this.toB,other.toB))}addToSet(set){let i=set.length,me=this;for(;i>0;i--){let range=set[i-1];if(!(range.fromA>me.toA)){if(range.toAend)break;rI+=2}if(!next)return result;new ChangedRange(next.fromA,next.toA,next.fromB,next.toB).addToSet(result),posA=next.toA,posB=next.toB}}}class ViewUpdate{constructor(view,state,transactions){this.view=view,this.state=state,this.transactions=transactions,this.flags=0,this.startState=view.state,this.changes=ChangeSet.empty(this.startState.doc.length);for(let tr of transactions)this.changes=this.changes.compose(tr.changes);let changedRanges=[];this.changes.iterChangedRanges(((fromA,toA,fromB,toB)=>changedRanges.push(new ChangedRange(fromA,toA,fromB,toB)))),this.changedRanges=changedRanges}static create(view,state,transactions){return new ViewUpdate(view,state,transactions)}get viewportChanged(){return(4&this.flags)>0}get heightChanged(){return(2&this.flags)>0}get geometryChanged(){return this.docChanged||(10&this.flags)>0}get focusChanged(){return(1&this.flags)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some((tr=>tr.selection))}get empty(){return 0==this.flags&&0==this.transactions.length}}class DocView extends ContentView{get length(){return this.view.state.doc.length}constructor(view){super(),this.view=view,this.decorations=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.editContextFormatting=Decoration.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(view.contentDOM),this.children=[new LineView],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new ChangedRange(0,0,0,view.state.doc.length)],0,null)}update(update){var _a;let changedRanges=update.changedRanges;this.minWidth>0&&changedRanges.length&&(changedRanges.every((_ref=>{let{fromA:fromA,toA:toA}=_ref;return toAthis.minWidthTo}))?(this.minWidthFrom=update.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=update.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(update);let readCompositionAt=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&((null===(_a=this.domChanged)||void 0===_a?void 0:_a.newSel)?readCompositionAt=this.domChanged.newSel.head:function(changes,composition){let touched=!1;composition&&changes.iterChangedRanges(((from,to)=>{fromcomposition.from&&(touched=!0)}));return touched}(update.changes,this.hasComposition)||update.selectionSet||(readCompositionAt=update.state.selection.main.head));let composition=readCompositionAt>-1?function(view,changes,headPos){let found=findCompositionNode(view,headPos);if(!found)return null;let{node:textNode,from:from,to:to}=found,text=textNode.nodeValue;if(/[\n\r]/.test(text))return null;if(view.state.doc.sliceString(found.from,found.to)!=text)return null;let inv=changes.invertedDesc,range=new ChangedRange(inv.mapPos(from),inv.mapPos(to),from,to),marks=[];for(let parent=textNode.parentNode;;parent=parent.parentNode){let parentView=ContentView.get(parent);if(parentView instanceof MarkView)marks.push({node:parent,deco:parentView.mark});else{if(parentView instanceof LineView||"DIV"==parent.nodeName&&parent.parentNode==view.contentDOM)return{range:range,text:textNode,marks:marks,line:parent};if(parent==view.contentDOM)return null;marks.push({node:parent,deco:new MarkDecoration({inclusive:!0,attributes:getAttrs$1(parent),tagName:parent.tagName.toLowerCase()})})}}}(this.view,update.changes,readCompositionAt):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:from,to:to}=this.hasComposition;changedRanges=new ChangedRange(from,to,update.changes.mapPos(from,-1),update.changes.mapPos(to,1)).addToSet(changedRanges.slice())}this.hasComposition=composition?{from:composition.range.fromB,to:composition.range.toB}:null,(browser.ie||browser.chrome)&&!composition&&update&&update.state.doc.lines!=update.startState.doc.lines&&(this.forceSelection=!0);let decoDiff=function(a,b,diff){let comp=new class{constructor(){this.changes=[]}compareRange(from,to){addRange(from,to,this.changes)}comparePoint(from,to){addRange(from,to,this.changes)}};return RangeSet.compare(a,b,diff,comp),comp.changes}(this.decorations,this.updateDeco(),update.changes);return changedRanges=ChangedRange.extendWithRanges(changedRanges,decoDiff),!!(7&this.flags||0!=changedRanges.length)&&(this.updateInner(changedRanges,update.startState.doc.length,composition),update.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(changes,oldLength,composition){this.view.viewState.mustMeasureContent=!0,this.updateChildren(changes,oldLength,composition);let{observer:observer}=this.view;observer.ignore((()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let track=browser.chrome||browser.ios?{node:observer.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,track),this.flags&=-8,track&&(track.written||observer.selectionRange.focusNode!=track.node)&&(this.forceSelection=!0),this.dom.style.height=""})),this.markedForComposition.forEach((cView=>cView.flags&=-9));let gaps=[];if(this.view.viewport.from||this.view.viewport.to=0?ranges[i]:null;if(!next)break;let content,breakAtStart,openStart,openEnd,{fromA:fromA,toA:toA,fromB:fromB,toB:toB}=next;if(composition&&composition.range.fromBfromB){let before=ContentBuilder.build(this.view.state.doc,fromB,composition.range.fromB,this.decorations,this.dynamicDecorationMap),after=ContentBuilder.build(this.view.state.doc,composition.range.toB,toB,this.decorations,this.dynamicDecorationMap);breakAtStart=before.breakAtStart,openStart=before.openStart,openEnd=after.openEnd;let compLine=this.compositionView(composition);after.breakAtStart?compLine.breakAfter=1:after.content.length&&compLine.merge(compLine.length,compLine.length,after.content[0],!1,after.openStart,0)&&(compLine.breakAfter=after.content[0].breakAfter,after.content.shift()),before.content.length&&compLine.merge(0,0,before.content[before.content.length-1],!0,0,before.openEnd)&&before.content.pop(),content=before.content.concat(compLine).concat(after.content)}else({content:content,breakAtStart:breakAtStart,openStart:openStart,openEnd:openEnd}=ContentBuilder.build(this.view.state.doc,fromB,toB,this.decorations,this.dynamicDecorationMap));let{i:toI,off:toOff}=cursor.findPos(toA,1),{i:fromI,off:fromOff}=cursor.findPos(fromA,-1);replaceRange(this,fromI,fromOff,toI,toOff,content,breakAtStart,openStart,openEnd)}composition&&this.fixCompositionDOM(composition)}updateEditContextFormatting(update){this.editContextFormatting=this.editContextFormatting.map(update.changes);for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setEditContextFormatting)&&(this.editContextFormatting=effect.value)}compositionView(composition){let cur=new TextView(composition.text.nodeValue);cur.flags|=8;for(let{deco:deco}of composition.marks)cur=new MarkView(deco,[cur],cur.length);let line=new LineView;return line.append(cur,0),line}fixCompositionDOM(composition){let fix=(dom,cView)=>{cView.flags|=8|(cView.children.some((c=>7&c.flags))?1:0),this.markedForComposition.add(cView);let prev=ContentView.get(dom);prev&&prev!=cView&&(prev.dom=null),cView.setDOM(dom)},pos=this.childPos(composition.range.fromB,1),cView=this.children[pos.i];fix(composition.line,cView);for(let i=composition.marks.length-1;i>=-1;i--)pos=cView.childPos(pos.off,1),cView=cView.children[pos.i],fix(i>=0?composition.marks[i].node:composition.text,cView)}updateSelection(){let fromPointer=arguments.length>1&&void 0!==arguments[1]&&arguments[1];!(arguments.length>0&&void 0!==arguments[0]&&arguments[0])&&this.view.observer.selectionRange.focusNode||this.view.observer.readSelectionRange();let activeElt=this.view.root.activeElement,focused=activeElt==this.dom,selectionNotFocus=!focused&&hasSelection(this.dom,this.view.observer.selectionRange)&&!(activeElt&&this.dom.contains(activeElt));if(!(focused||fromPointer||selectionNotFocus))return;let force=this.forceSelection;this.forceSelection=!1;let main=this.view.state.selection.main,anchor=this.moveToLine(this.domAtPos(main.anchor)),head=main.empty?anchor:this.moveToLine(this.domAtPos(main.head));if(browser.gecko&&main.empty&&!this.hasComposition&&(1==(pos=anchor).node.nodeType&&pos.node.firstChild&&(0==pos.offset||"false"==pos.node.childNodes[pos.offset-1].contentEditable)&&(pos.offset==pos.node.childNodes.length||"false"==pos.node.childNodes[pos.offset].contentEditable))){let dummy=document.createTextNode("");this.view.observer.ignore((()=>anchor.node.insertBefore(dummy,anchor.node.childNodes[anchor.offset]||null))),anchor=head=new DOMPos(dummy,0),force=!0}var pos;let domSel=this.view.observer.selectionRange;!force&&domSel.focusNode&&(isEquivalentPosition(anchor.node,anchor.offset,domSel.anchorNode,domSel.anchorOffset)&&isEquivalentPosition(head.node,head.offset,domSel.focusNode,domSel.focusOffset)||this.suppressWidgetCursorChange(domSel,main))||(this.view.observer.ignore((()=>{browser.android&&browser.chrome&&this.dom.contains(domSel.focusNode)&&function(node,inside){for(let cur=node;cur&&cur!=inside;cur=cur.assignedSlot||cur.parentNode)if(1==cur.nodeType&&"false"==cur.contentEditable)return!0;return!1}(domSel.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let rawSel=getSelection(this.view.root);if(rawSel)if(main.empty){if(browser.gecko){let nextTo=(node=anchor.node,offset=anchor.offset,1!=node.nodeType?0:(offset&&"false"==node.childNodes[offset-1].contentEditable?1:0)|(offsetmain.head&&([anchor,head]=[head,anchor]),range.setEnd(head.node,head.offset),range.setStart(anchor.node,anchor.offset),rawSel.removeAllRanges(),rawSel.addRange(range)}else;var node,offset;selectionNotFocus&&this.view.root.activeElement==this.dom&&(this.dom.blur(),activeElt&&activeElt.focus())})),this.view.observer.setSelectionRange(anchor,head)),this.impreciseAnchor=anchor.precise?null:new DOMPos(domSel.anchorNode,domSel.anchorOffset),this.impreciseHead=head.precise?null:new DOMPos(domSel.focusNode,domSel.focusOffset)}suppressWidgetCursorChange(sel,cursor){return this.hasComposition&&cursor.empty&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)&&this.posFromDOM(sel.focusNode,sel.focusOffset)==cursor.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:view}=this,cursor=view.state.selection.main,sel=getSelection(view.root),{anchorNode:anchorNode,anchorOffset:anchorOffset}=view.observer.selectionRange;if(!(sel&&cursor.empty&&cursor.assoc&&sel.modify))return;let line=LineView.find(this,cursor.head);if(!line)return;let lineStart=line.posAtStart;if(cursor.head==lineStart||cursor.head==lineStart+line.length)return;let before=this.coordsAt(cursor.head,-1),after=this.coordsAt(cursor.head,1);if(!before||!after||before.bottom>after.top)return;let dom=this.domAtPos(cursor.head+cursor.assoc);sel.collapse(dom.node,dom.offset),sel.modify("move",cursor.assoc<0?"forward":"backward","lineboundary"),view.observer.readSelectionRange();let newRange=view.observer.selectionRange;view.docView.posFromDOM(newRange.anchorNode,newRange.anchorOffset)!=cursor.from&&sel.collapse(anchorNode,anchorOffset)}moveToLine(pos){let newPos,dom=this.dom;if(pos.node!=dom)return pos;for(let i=pos.offset;!newPos&&i=0;i--){let view=ContentView.get(dom.childNodes[i]);view instanceof LineView&&(newPos=view.domAtPos(view.length))}return newPos?new DOMPos(newPos.node,newPos.offset,!0):pos}nearest(dom){for(let cur=dom;cur;){let domView=ContentView.get(cur);if(domView&&domView.rootView==this)return domView;cur=cur.parentNode}return null}posFromDOM(node,offset){let view=this.nearest(node);if(!view)throw new RangeError("Trying to find position for a DOM position outside of the document");return view.localPosFromDOM(node,offset)+view.posAtStart}domAtPos(pos){let{i:i,off:off}=this.childCursor().findPos(pos,-1);for(;i=0;i--){let child=this.children[i],end=off-child.breakAfter,start=end-child.length;if(endpos||child.covers(1))&&(!best||child instanceof LineView&&!(best instanceof LineView&&side>=0)))best=child,bestPos=start;else if(best&&start==pos&&end==pos&&child instanceof BlockWidgetView&&Math.abs(side)<2){if(child.deco.startSide<0)break;i&&(best=null)}off=start}return best?best.coordsAt(pos-bestPos,side):null}coordsForChar(pos){let{i:i,off:off}=this.childPos(pos,1),child=this.children[i];if(!(child instanceof LineView))return null;for(;child.children.length;){let{i:i,off:childOff}=child.childPos(off,1);for(;;i++){if(i==child.children.length)return null;if((child=child.children[i]).length)break}off=childOff}if(!(child instanceof TextView))return null;let end=findClusterBreak(child.text,off);if(end==off)return null;let rects=textRange(child.dom,off,end).getClientRects();for(let i=0;iMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,widest=-1,ltr=this.view.textDirection==Direction.LTR;for(let pos=0,i=0;ito)break;if(pos>=from){let childRect=child.dom.getBoundingClientRect();if(result.push(childRect.height),isWider){let last=child.dom.lastChild,rects=last?clientRectsFor(last):[];if(rects.length){let rect=rects[rects.length-1],width=ltr?rect.right-childRect.left:childRect.right-rect.left;width>widest&&(widest=width,this.minWidth=contentWidth,this.minWidthFrom=pos,this.minWidthTo=end)}}}pos=end+child.breakAfter}return result}textDirectionAt(pos){let{i:i}=this.childPos(pos,1);return"rtl"==getComputedStyle(this.children[i].dom).direction?Direction.RTL:Direction.LTR}measureTextSize(){for(let child of this.children)if(child instanceof LineView){let measure=child.measureTextSize();if(measure)return measure}let lineHeight,charWidth,textHeight,dummy=document.createElement("div");return dummy.className="cm-line",dummy.style.width="99999px",dummy.style.position="absolute",dummy.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore((()=>{this.dom.appendChild(dummy);let rect=clientRectsFor(dummy.firstChild)[0];lineHeight=dummy.getBoundingClientRect().height,charWidth=rect?rect.width/27:7,textHeight=rect?rect.height:lineHeight,dummy.remove()})),{lineHeight:lineHeight,charWidth:charWidth,textHeight:textHeight}}childCursor(){let pos=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.length,i=this.children.length;return i&&(pos-=this.children[--i].length),new ChildCursor(this.children,pos,i)}computeBlockGapDeco(){let deco=[],vs=this.view.viewState;for(let pos=0,i=0;;i++){let next=i==vs.viewports.length?null:vs.viewports[i],end=next?next.from-1:this.length;if(end>pos){let height=(vs.lineBlockAt(end).bottom-vs.lineBlockAt(pos).top)/this.view.scaleY;deco.push(Decoration.replace({widget:new BlockGapWidget(height),block:!0,inclusive:!0,isBlockGap:!0}).range(pos,end))}if(!next)break;pos=next.to+1}return Decoration.set(deco)}updateDeco(){let i=1,allDeco=this.view.state.facet(decorations).map((d=>(this.dynamicDecorationMap[i++]="function"==typeof d)?d(this.view):d)),dynamicOuter=!1,outerDeco=this.view.state.facet(outerDecorations).map(((d,i)=>{let dynamic="function"==typeof d;return dynamic&&(dynamicOuter=!0),dynamic?d(this.view):d}));for(outerDeco.length&&(this.dynamicDecorationMap[i++]=dynamicOuter,allDeco.push(RangeSet.join(outerDeco))),this.decorations=[this.editContextFormatting,...allDeco,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];irange.anchor?-1:1);if(!rect)return;!range.empty&&(other=this.coordsAt(range.anchor,range.anchor>range.head?-1:1))&&(rect={left:Math.min(rect.left,other.left),top:Math.min(rect.top,other.top),right:Math.max(rect.right,other.right),bottom:Math.max(rect.bottom,other.bottom)});let margins=getScrollMargins(this.view),targetRect={left:rect.left-margins.left,top:rect.top-margins.top,right:rect.right+margins.right,bottom:rect.bottom+margins.bottom},{offsetWidth:offsetWidth,offsetHeight:offsetHeight}=this.view.scrollDOM;!function(dom,rect,side,x,y,xMargin,yMargin,ltr){let doc=dom.ownerDocument,win=doc.defaultView||window;for(let cur=dom,stop=!1;cur&&!stop;)if(1==cur.nodeType){let bounding,top=cur==doc.body,scaleX=1,scaleY=1;if(top)bounding=windowRect(win);else{if(/^(fixed|sticky)$/.test(getComputedStyle(cur).position)&&(stop=!0),cur.scrollHeight<=cur.clientHeight&&cur.scrollWidth<=cur.clientWidth){cur=cur.assignedSlot||cur.parentNode;continue}let rect=cur.getBoundingClientRect();({scaleX:scaleX,scaleY:scaleY}=getScale(cur,rect)),bounding={left:rect.left,right:rect.left+cur.clientWidth*scaleX,top:rect.top,bottom:rect.top+cur.clientHeight*scaleY}}let moveX=0,moveY=0;if("nearest"==y)rect.top0&&rect.bottom>bounding.bottom+moveY&&(moveY=rect.bottom-bounding.bottom+moveY+yMargin)):rect.bottom>bounding.bottom&&(moveY=rect.bottom-bounding.bottom+yMargin,side<0&&rect.top-moveY0&&rect.right>bounding.right+moveX&&(moveX=rect.right-bounding.right+moveX+xMargin)):rect.right>bounding.right&&(moveX=rect.right-bounding.right+xMargin,side<0&&rect.leftx?rect.left-x:Math.max(0,x-rect.right)}function getdy(y,rect){return rect.top>y?rect.top-y:Math.max(0,y-rect.bottom)}function yOverlap(a,b){return a.topb.top+1}function upTop(rect,top){return toprect.bottom?{top:rect.top,left:rect.left,right:rect.right,bottom:bottom}:rect}function domPosAtCoords(parent,x,y){let closest,closestRect,closestX,closestY,above,below,aboveRect,belowRect,closestOverlap=!1;for(let child=parent.firstChild;child;child=child.nextSibling){let rects=clientRectsFor(child);for(let i=0;idy||closestY==dy&&closestX>dx){closest=child,closestRect=rect,closestX=dx,closestY=dy;let side=dy?y0?i0)}0==dx?y>rect.bottom&&(!aboveRect||aboveRect.bottomrect.top)&&(below=child,belowRect=rect):aboveRect&&yOverlap(aboveRect,rect)?aboveRect=upBot(aboveRect,rect.bottom):belowRect&&yOverlap(belowRect,rect)&&(belowRect=upTop(belowRect,rect.top))}}if(aboveRect&&aboveRect.bottom>=y?(closest=above,closestRect=aboveRect):belowRect&&belowRect.top<=y&&(closest=below,closestRect=belowRect),!closest)return{node:parent,offset:0};let clipX=Math.max(closestRect.left,Math.min(closestRect.right,x));return 3==closest.nodeType?domPosInText(closest,clipX,y):closestOverlap&&"false"!=closest.contentEditable?domPosAtCoords(closest,clipX,y):{node:parent,offset:Array.prototype.indexOf.call(parent.childNodes,closest)+(x>=(closestRect.left+closestRect.right)/2?1:0)}}function domPosInText(node,x,y){let len=node.nodeValue.length,closestOffset=-1,closestDY=1e9,generalSide=0;for(let i=0;iy?rect.top-y:y-rect.bottom)-1;if(rect.left-1<=x&&rect.right+1>=x&&dy=(rect.left+rect.right)/2,after=right;if(browser.chrome||browser.gecko){textRange(node,i).getBoundingClientRect().left==rect.right&&(after=!right)}if(dy<=0)return{node:node,offset:i+(after?1:0)};closestOffset=i+(after?1:0),closestDY=dy}}}return{node:node,offset:closestOffset>-1?closestOffset:generalSide>0?node.nodeValue.length:0}}function posAtCoords(view,coords,precise){let bias=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;var _a,_b;let block,content=view.contentDOM.getBoundingClientRect(),docTop=content.top+view.viewState.paddingTop,{docHeight:docHeight}=view.viewState,{x:x,y:y}=coords,yOffset=y-docTop;if(yOffset<0)return 0;if(yOffset>docHeight)return view.state.doc.length;for(let halfLine=view.viewState.heightOracle.textHeight/2,bounced=!1;block=view.elementAtHeight(yOffset),block.type!=BlockType.Text;)for(;yOffset=bias>0?block.bottom+halfLine:block.top-halfLine,!(yOffset>=0&&yOffset<=docHeight);){if(bounced)return precise?null:0;bounced=!0,bias=-bias}y=docTop+yOffset;let lineStart=block.from;if(lineStartview.viewport.to)return view.viewport.to==view.state.doc.length?view.state.doc.length:precise?null:posAtCoordsImprecise(view,content,block,x,y);let doc=view.dom.ownerDocument,root=view.root.elementFromPoint?view.root:doc,element=root.elementFromPoint(x,y);element&&!view.contentDOM.contains(element)&&(element=null),element||(x=Math.max(content.left+1,Math.min(content.right-1,x)),element=root.elementFromPoint(x,y),element&&!view.contentDOM.contains(element)&&(element=null));let node,offset=-1;if(element&&0!=(null===(_a=view.docView.nearest(element))||void 0===_a?void 0:_a.isEditable))if(doc.caretPositionFromPoint){let pos=doc.caretPositionFromPoint(x,y);pos&&({offsetNode:node,offset:offset}=pos)}else if(doc.caretRangeFromPoint){let range=doc.caretRangeFromPoint(x,y);range&&(({startContainer:node,startOffset:offset}=range),(!view.contentDOM.contains(node)||browser.safari&&isSuspiciousSafariCaretResult(node,offset,x)||browser.chrome&&isSuspiciousChromeCaretResult(node,offset,x))&&(node=void 0))}if(!node||!view.docView.dom.contains(node)){let line=LineView.find(view.docView,lineStart);if(!line)return yOffset>block.top+block.height/2?block.to:block.from;({node:node,offset:offset}=domPosAtCoords(line.dom,x,y))}let nearest=view.docView.nearest(node);if(!nearest)return null;if(nearest.isWidget&&1==(null===(_b=nearest.dom)||void 0===_b?void 0:_b.nodeType)){let rect=nearest.dom.getBoundingClientRect();return coords.y1.5*view.defaultLineHeight){let textHeight=view.viewState.heightOracle.textHeight;into+=Math.floor((y-block.top-.5*(view.defaultLineHeight-textHeight))/textHeight)*view.viewState.heightOracle.lineLength}let content=view.state.sliceDoc(block.from,block.to);return block.from+findColumn(content,into,view.state.tabSize)}function isSuspiciousSafariCaretResult(node,offset,x){let len;if(3!=node.nodeType||offset!=(len=node.nodeValue.length))return!1;for(let next=node.nextSibling;next;next=next.nextSibling)if(1!=next.nodeType||"BR"!=next.nodeName)return!1;return textRange(node,len-1,len).getBoundingClientRect().left>x}function isSuspiciousChromeCaretResult(node,offset,x){if(0!=offset)return!1;for(let cur=node;;){let parent=cur.parentNode;if(!parent||1!=parent.nodeType||parent.firstChild!=cur)return!1;if(parent.classList.contains("cm-line"))break;cur=parent}return x-(1==node.nodeType?node.getBoundingClientRect():textRange(node,0,Math.max(node.nodeValue.length,1)).getBoundingClientRect()).left>5}function blockAt(view,pos){let line=view.lineBlockAt(pos);if(Array.isArray(line.type))for(let l of line.type)if(l.to>pos||l.to==pos&&(l.to==line.to||l.type==BlockType.Text))return l;return line}function moveByChar(view,start,forward,by){let line=view.state.doc.lineAt(start.head),spans=view.bidiSpans(line),direction=view.textDirectionAt(line.from);for(let cur=start,check=null;;){let next=moveVisually(line,spans,direction,cur,forward),char=movedOver;if(!next){if(line.number==(forward?view.state.doc.lines:1))return cur;char="\n",line=view.state.doc.line(line.number+(forward?1:-1)),spans=view.bidiSpans(line),next=view.visualLineSide(line,!forward)}if(check){if(!check(char))return cur}else{if(!by)return next;check=by(char)}cur=next}}function skipAtomicRanges(atoms,pos,bias){for(;;){let moved=0;for(let set of atoms)set.between(pos-1,pos+1,((from,to,value)=>{if(pos>from&&posf(view))),pos.from,oldPos.head>pos.from?-1:1);return newPos==pos.from?pos:EditorSelection.cursor(newPos,newPosnull)),browser.gecko&&function(doc){appliedFirefoxHack.has(doc)||(appliedFirefoxHack.add(doc),doc.addEventListener("copy",(()=>{})),doc.addEventListener("cut",(()=>{})))}(view.contentDOM.ownerDocument)}handleEvent(event){(function(view,event){if(!event.bubbles)return!0;if(event.defaultPrevented)return!1;for(let cView,node=event.target;node!=view.contentDOM;node=node.parentNode)if(!node||11==node.nodeType||(cView=ContentView.get(node))&&cView.ignoreEvent(event))return!1;return!0})(this.view,event)&&!this.ignoreDuringComposition(event)&&("keydown"==event.type&&this.keydown(event)||this.runHandlers(event.type,event))}runHandlers(type,event){let handlers=this.handlers[type];if(handlers){for(let observer of handlers.observers)observer(this.view,event);for(let handler of handlers.handlers){if(event.defaultPrevented)break;if(handler(this.view,event)){event.preventDefault();break}}}}ensureHandlers(plugins){let handlers=computeHandlers(plugins),prev=this.handlers,dom=this.view.contentDOM;for(let type in handlers)if("scroll"!=type){let passive=!handlers[type].handlers.length,exists=prev[type];exists&&passive!=!exists.handlers.length&&(dom.removeEventListener(type,this.handleEvent),exists=null),exists||dom.addEventListener(type,this.handleEvent,{passive:passive})}for(let type in prev)"scroll"==type||handlers[type]||dom.removeEventListener(type,this.handleEvent);this.handlers=handlers}keydown(event){if(this.lastKeyCode=event.keyCode,this.lastKeyTime=Date.now(),9==event.keyCode&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&27!=event.keyCode&&modifierCodes.indexOf(event.keyCode)<0&&(this.tabFocusMode=-1),browser.android&&browser.chrome&&!event.synthetic&&(13==event.keyCode||8==event.keyCode))return this.view.observer.delayAndroidKey(event.key,event.keyCode),!0;let pending;return!browser.ios||event.synthetic||event.altKey||event.metaKey||!((pending=PendingKeys.find((key=>key.keyCode==event.keyCode)))&&!event.ctrlKey||EmacsyPendingKeys.indexOf(event.key)>-1&&event.ctrlKey&&!event.shiftKey)?(229!=event.keyCode&&this.view.observer.forceFlush(),!1):(this.pendingIOSKey=pending||event,setTimeout((()=>this.flushIOSKey()),250),!0)}flushIOSKey(change){let key=this.pendingIOSKey;return!!key&&(!("Enter"==key.key&&change&&change.from0||!!(browser.safari&&!browser.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100)&&(this.compositionPendingKey=!1,!0))}startMouseSelection(mouseSelection){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=mouseSelection}update(update){this.view.observer.update(update),this.mouseSelection&&this.mouseSelection.update(update),this.draggedContent&&update.docChanged&&(this.draggedContent=this.draggedContent.map(update.changes)),update.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function bindHandler(plugin,handler){return(view,event)=>{try{return handler.call(plugin,event,view)}catch(e){logException(view.state,e)}}}function computeHandlers(plugins){let result=Object.create(null);function record(type){return result[type]||(result[type]={observers:[],handlers:[]})}for(let plugin of plugins){let spec=plugin.spec;if(spec&&spec.domEventHandlers)for(let type in spec.domEventHandlers){let f=spec.domEventHandlers[type];f&&record(type).handlers.push(bindHandler(plugin.value,f))}if(spec&&spec.domEventObservers)for(let type in spec.domEventObservers){let f=spec.domEventObservers[type];f&&record(type).observers.push(bindHandler(plugin.value,f))}}for(let type in handlers)record(type).handlers.push(handlers[type]);for(let type in observers)record(type).observers.push(observers[type]);return result}const PendingKeys=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],EmacsyPendingKeys="dthko",modifierCodes=[16,17,18,20,91,92,224,225];function dragScrollSpeed(dist){return.7*Math.max(0,dist)+8}class MouseSelection{constructor(view,startEvent,style,mustSelect){this.view=view,this.startEvent=startEvent,this.style=style,this.mustSelect=mustSelect,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=startEvent,this.scrollParents=function(dom){let x,y,doc=dom.ownerDocument;for(let cur=dom.parentNode;cur&&!(cur==doc.body||x&&y);)if(1==cur.nodeType)!y&&cur.scrollHeight>cur.clientHeight&&(y=cur),!x&&cur.scrollWidth>cur.clientWidth&&(x=cur),cur=cur.assignedSlot||cur.parentNode;else{if(11!=cur.nodeType)break;cur=cur.host}return{x:x,y:y}}(view.contentDOM),this.atoms=view.state.facet(atomicRanges).map((f=>f(view)));let doc=view.contentDOM.ownerDocument;doc.addEventListener("mousemove",this.move=this.move.bind(this)),doc.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=startEvent.shiftKey,this.multiple=view.state.facet(EditorState.allowMultipleSelections)&&function(view,event){let facet=view.state.facet(clickAddsSelectionRange);return facet.length?facet[0](event):browser.mac?event.metaKey:event.ctrlKey}(view,startEvent),this.dragging=!(!function(view,event){let{main:main}=view.state.selection;if(main.empty)return!1;let sel=getSelection(view.root);if(!sel||0==sel.rangeCount)return!0;let rects=sel.getRangeAt(0).getClientRects();for(let i=0;i=event.clientX&&rect.top<=event.clientY&&rect.bottom>=event.clientY)return!0}return!1}(view,startEvent)||1!=getClickType(startEvent))&&null}start(event){!1===this.dragging&&this.select(event)}move(event){if(0==event.buttons)return this.destroy();if(this.dragging||null==this.dragging&&(a=this.startEvent,b=event,Math.max(Math.abs(a.clientX-b.clientX),Math.abs(a.clientY-b.clientY))<10))return;var a,b;this.select(this.lastEvent=event);let sx=0,sy=0,left=0,top=0,right=this.view.win.innerWidth,bottom=this.view.win.innerHeight;this.scrollParents.x&&({left:left,right:right}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:top,bottom:bottom}=this.scrollParents.y.getBoundingClientRect());let margins=getScrollMargins(this.view);event.clientX-margins.left<=left+6?sx=-dragScrollSpeed(left-event.clientX):event.clientX+margins.right>=right-6&&(sx=dragScrollSpeed(event.clientX-right)),event.clientY-margins.top<=top+6?sy=-dragScrollSpeed(top-event.clientY):event.clientY+margins.bottom>=bottom-6&&(sy=dragScrollSpeed(event.clientY-bottom)),this.setScrollSpeed(sx,sy)}up(event){null==this.dragging&&this.select(this.lastEvent),this.dragging||event.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let doc=this.view.contentDOM.ownerDocument;doc.removeEventListener("mousemove",this.move),doc.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(sx,sy){this.scrollSpeed={x:sx,y:sy},sx||sy?this.scrolling<0&&(this.scrolling=setInterval((()=>this.scroll()),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:x,y:y}=this.scrollSpeed;x&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=x,x=0),y&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=y,y=0),(x||y)&&this.view.win.scrollBy(x,y),!1===this.dragging&&this.select(this.lastEvent)}skipAtoms(sel){let ranges=null;for(let i=0;itr.isUserEvent("input.type")))?this.destroy():this.style.update(update)&&setTimeout((()=>this.select(this.lastEvent)),20)}}const handlers=Object.create(null),observers=Object.create(null),brokenClipboardAPI=browser.ie&&browser.ie_version<15||browser.ios&&browser.webkit_version<604;function doPaste(view,input){let changes,{state:state}=view,i=1,text=state.toText(input),byLine=text.lines==state.selection.ranges.length;if(null!=lastLinewiseCopy&&state.selection.ranges.every((r=>r.empty))&&lastLinewiseCopy==text.toString()){let lastLine=-1;changes=state.changeByRange((range=>{let line=state.doc.lineAt(range.from);if(line.from==lastLine)return{range:range};lastLine=line.from;let insert=state.toText((byLine?text.line(i++).text:input)+state.lineBreak);return{changes:{from:line.from,insert:insert},range:EditorSelection.cursor(range.from+insert.length)}}))}else changes=byLine?state.changeByRange((range=>{let line=text.line(i++);return{changes:{from:range.from,to:range.to,insert:line.text},range:EditorSelection.cursor(range.from+line.length)}})):state.replaceSelection(text);view.dispatch(changes,{userEvent:"input.paste",scrollIntoView:!0})}function rangeForClick(view,pos,bias,type){if(1==type)return EditorSelection.cursor(pos,bias);if(2==type)return function(state,pos){let bias=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,categorize=state.charCategorizer(pos),line=state.doc.lineAt(pos),linePos=pos-line.from;if(0==line.length)return EditorSelection.cursor(pos);0==linePos?bias=1:linePos==line.length&&(bias=-1);let from=linePos,to=linePos;bias<0?from=findClusterBreak(line.text,linePos,!1):to=findClusterBreak(line.text,linePos);let cat=categorize(line.text.slice(from,to));for(;from>0;){let prev=findClusterBreak(line.text,from,!1);if(categorize(line.text.slice(prev,from))!=cat)break;from=prev}for(;to{view.inputState.lastScrollTop=view.scrollDOM.scrollTop,view.inputState.lastScrollLeft=view.scrollDOM.scrollLeft},handlers.keydown=(view,event)=>(view.inputState.setSelectionOrigin("select"),27==event.keyCode&&0!=view.inputState.tabFocusMode&&(view.inputState.tabFocusMode=Date.now()+2e3),!1),observers.touchstart=(view,e)=>{view.inputState.lastTouchTime=Date.now(),view.inputState.setSelectionOrigin("select.pointer")},observers.touchmove=view=>{view.inputState.setSelectionOrigin("select.pointer")},handlers.mousedown=(view,event)=>{if(view.observer.flush(),view.inputState.lastTouchTime>Date.now()-2e3)return!1;let style=null;for(let makeStyle of view.state.facet(mouseSelectionStyle))if(style=makeStyle(view,event),style)break;if(style||0!=event.button||(style=function(view,event){let start=queryPos(view,event),type=getClickType(event),startSel=view.state.selection;return{update(update){update.docChanged&&(start.pos=update.changes.mapPos(start.pos),startSel=startSel.map(update.changes))},get(event,extend,multiple){let removed,cur=queryPos(view,event),range=rangeForClick(view,cur.pos,cur.bias,type);if(start.pos!=cur.pos&&!extend){let startRange=rangeForClick(view,start.pos,start.bias,type),from=Math.min(startRange.from,range.from),to=Math.max(startRange.to,range.to);range=from1&&(removed=function(sel,pos){for(let i=0;i=pos)return EditorSelection.create(sel.ranges.slice(0,i).concat(sel.ranges.slice(i+1)),sel.mainIndex==i?0:sel.mainIndex-(sel.mainIndex>i?1:0))}return null}(startSel,cur.pos))?removed:multiple?startSel.addRange(range):EditorSelection.create([range])}}}(view,event)),style){let mustFocus=!view.hasFocus;view.inputState.startMouseSelection(new MouseSelection(view,event,style,mustFocus)),mustFocus&&view.observer.ignore((()=>{focusPreventScroll(view.contentDOM);let active=view.root.activeElement;active&&!active.contains(view.contentDOM)&&active.blur()}));let mouseSel=view.inputState.mouseSelection;if(mouseSel)return mouseSel.start(event),!1===mouseSel.dragging}return!1};let insideY=(y,rect)=>y>=rect.top&&y<=rect.bottom,inside=(x,y,rect)=>insideY(y,rect)&&x>=rect.left&&x<=rect.right;function findPositionSide(view,pos,x,y){let line=LineView.find(view.docView,pos);if(!line)return 1;let off=pos-line.posAtStart;if(0==off)return 1;if(off==line.length)return-1;let before=line.coordsAt(off,-1);if(before&&inside(x,y,before))return-1;let after=line.coordsAt(off,1);return after&&inside(x,y,after)?1:before&&insideY(y,before)?-1:1}function queryPos(view,event){let pos=view.posAtCoords({x:event.clientX,y:event.clientY},!1);return{pos:pos,bias:findPositionSide(view,pos,event.clientX,event.clientY)}}const BadMouseDetail=browser.ie&&browser.ie_version<=11;let lastMouseDown=null,lastMouseDownCount=0,lastMouseDownTime=0;function getClickType(event){if(!BadMouseDetail)return event.detail;let last=lastMouseDown,lastTime=lastMouseDownTime;return lastMouseDown=event,lastMouseDownTime=Date.now(),lastMouseDownCount=!last||lastTime>Date.now()-400&&Math.abs(last.clientX-event.clientX)<2&&Math.abs(last.clientY-event.clientY)<2?(lastMouseDownCount+1)%3:1}function dropText(view,event,text,direct){if(!text)return;let dropPos=view.posAtCoords({x:event.clientX,y:event.clientY},!1),{draggedContent:draggedContent}=view.inputState,del=direct&&draggedContent&&function(view,event){let facet=view.state.facet(dragMovesSelection$1);return facet.length?facet[0](event):browser.mac?!event.altKey:!event.ctrlKey}(view,event)?{from:draggedContent.from,to:draggedContent.to}:null,ins={from:dropPos,insert:text},changes=view.state.changes(del?[del,ins]:ins);view.focus(),view.dispatch({changes:changes,selection:{anchor:changes.mapPos(dropPos,-1),head:changes.mapPos(dropPos,1)},userEvent:del?"move.drop":"input.drop"}),view.inputState.draggedContent=null}handlers.dragstart=(view,event)=>{let{selection:{main:range}}=view.state;if(event.target.draggable){let cView=view.docView.nearest(event.target);if(cView&&cView.isWidget){let from=cView.posAtStart,to=from+cView.length;(from>=range.to||to<=range.from)&&(range=EditorSelection.range(from,to))}}let{inputState:inputState}=view;return inputState.mouseSelection&&(inputState.mouseSelection.dragging=!0),inputState.draggedContent=range,event.dataTransfer&&(event.dataTransfer.setData("Text",view.state.sliceDoc(range.from,range.to)),event.dataTransfer.effectAllowed="copyMove"),!1},handlers.dragend=view=>(view.inputState.draggedContent=null,!1),handlers.drop=(view,event)=>{if(!event.dataTransfer)return!1;if(view.state.readOnly)return!0;let files=event.dataTransfer.files;if(files&&files.length){let text=Array(files.length),read=0,finishFile=()=>{++read==files.length&&dropText(view,event,text.filter((s=>null!=s)).join(view.state.lineBreak),!1)};for(let i=0;i{/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)||(text[i]=reader.result),finishFile()},reader.readAsText(files[i])}return!0}{let text=event.dataTransfer.getData("Text");if(text)return dropText(view,event,text,!0),!0}return!1},handlers.paste=(view,event)=>{if(view.state.readOnly)return!0;view.observer.flush();let data=brokenClipboardAPI?null:event.clipboardData;return data?(doPaste(view,data.getData("text/plain")||data.getData("text/uri-list")),!0):(function(view){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.focus(),setTimeout((()=>{view.focus(),target.remove(),doPaste(view,target.value)}),50)}(view),!1)};let lastLinewiseCopy=null;handlers.copy=handlers.cut=(view,event)=>{let{text:text,ranges:ranges,linewise:linewise}=function(state){let content=[],ranges=[],linewise=!1;for(let range of state.selection.ranges)range.empty||(content.push(state.sliceDoc(range.from,range.to)),ranges.push(range));if(!content.length){let upto=-1;for(let{from:from}of state.selection.ranges){let line=state.doc.lineAt(from);line.number>upto&&(content.push(line.text),ranges.push({from:line.from,to:Math.min(state.doc.length,line.to+1)})),upto=line.number}linewise=!0}return{text:content.join(state.lineBreak),ranges:ranges,linewise:linewise}}(view.state);if(!text&&!linewise)return!1;lastLinewiseCopy=linewise?text:null,"cut"!=event.type||view.state.readOnly||view.dispatch({changes:ranges,scrollIntoView:!0,userEvent:"delete.cut"});let data=brokenClipboardAPI?null:event.clipboardData;return data?(data.clearData(),data.setData("text/plain",text),!0):(function(view,text){let parent=view.dom.parentNode;if(!parent)return;let target=parent.appendChild(document.createElement("textarea"));target.style.cssText="position: fixed; left: -10000px; top: 10px",target.value=text,target.focus(),target.selectionEnd=text.length,target.selectionStart=0,setTimeout((()=>{target.remove(),view.focus()}),50)}(view,text),!1)};const isFocusChange=Annotation.define();function focusChangeTransaction(state,focus){let effects=[];for(let getEffect of state.facet(focusChangeEffect)){let effect=getEffect(state,focus);effect&&effects.push(effect)}return effects?state.update({effects:effects,annotations:isFocusChange.of(!0)}):null}function updateForFocusChange(view){setTimeout((()=>{let focus=view.hasFocus;if(focus!=view.inputState.notifiedFocused){let tr=focusChangeTransaction(view.state,focus);tr?view.dispatch(tr):view.update([])}}),10)}observers.focus=view=>{view.inputState.lastFocusTime=Date.now(),view.scrollDOM.scrollTop||!view.inputState.lastScrollTop&&!view.inputState.lastScrollLeft||(view.scrollDOM.scrollTop=view.inputState.lastScrollTop,view.scrollDOM.scrollLeft=view.inputState.lastScrollLeft),updateForFocusChange(view)},observers.blur=view=>{view.observer.clearSelectionRange(),updateForFocusChange(view)},observers.compositionstart=observers.compositionupdate=view=>{view.observer.editContext||(null==view.inputState.compositionFirstChange&&(view.inputState.compositionFirstChange=!0),view.inputState.composing<0&&(view.inputState.composing=0))},observers.compositionend=view=>{view.observer.editContext||(view.inputState.composing=-1,view.inputState.compositionEndedAt=Date.now(),view.inputState.compositionPendingKey=!0,view.inputState.compositionPendingChange=view.observer.pendingRecords().length>0,view.inputState.compositionFirstChange=null,browser.chrome&&browser.android?view.observer.flushSoon():view.inputState.compositionPendingChange?Promise.resolve().then((()=>view.observer.flush())):setTimeout((()=>{view.inputState.composing<0&&view.docView.hasComposition&&view.update([])}),50))},observers.contextmenu=view=>{view.inputState.lastContextMenu=Date.now()},handlers.beforeinput=(view,event)=>{var _a;let pending;if(browser.chrome&&browser.android&&(pending=PendingKeys.find((key=>key.inputType==event.inputType)))&&(view.observer.delayAndroidKey(pending.key,pending.keyCode),"Backspace"==pending.key||"Delete"==pending.key)){let startViewHeight=(null===(_a=window.visualViewport)||void 0===_a?void 0:_a.height)||0;setTimeout((()=>{var _a;((null===(_a=window.visualViewport)||void 0===_a?void 0:_a.height)||0)>startViewHeight+10&&view.hasFocus&&(view.contentDOM.blur(),view.focus())}),100)}return browser.ios&&"deleteContentForward"==event.inputType&&view.observer.flushSoon(),browser.safari&&"insertText"==event.inputType&&view.inputState.composing>=0&&setTimeout((()=>observers.compositionend(view,event)),20),!1};const appliedFirefoxHack=new Set;const wrappingWhiteSpace=["pre-wrap","normal","pre-line","break-spaces"];class HeightOracle{constructor(lineWrapping){this.lineWrapping=lineWrapping,this.doc=Text.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(from,to){let lines=this.doc.lineAt(to).number-this.doc.lineAt(from).number+1;return this.lineWrapping&&(lines+=Math.max(0,Math.ceil((to-from-lines*this.lineLength*.5)/this.lineLength))),this.lineHeight*lines}heightForLine(length){if(!this.lineWrapping)return this.lineHeight;return(1+Math.max(0,Math.ceil((length-this.lineLength)/(this.lineLength-5))))*this.lineHeight}setDoc(doc){return this.doc=doc,this}mustRefreshForWrapping(whiteSpace){return wrappingWhiteSpace.indexOf(whiteSpace)>-1!=this.lineWrapping}mustRefreshForHeights(lineHeights){let newHeight=!1;for(let i=0;i-1,changed=Math.round(lineHeight)!=Math.round(this.lineHeight)||this.lineWrapping!=lineWrapping;if(this.lineWrapping=lineWrapping,this.lineHeight=lineHeight,this.charWidth=charWidth,this.textHeight=textHeight,this.lineLength=lineLength,changed){this.heightSamples={};for(let i=0;i2&&void 0!==arguments[2]?arguments[2]:2;this.length=length,this.height=height,this.flags=flags}get outdated(){return(2&this.flags)>0}set outdated(value){this.flags=(value?2:0)|-3&this.flags}setHeight(oracle,height){this.height!=height&&(Math.abs(this.height-height)>.001&&(oracle.heightChanged=!0),this.height=height)}replace(_from,_to,nodes){return HeightMap.of(nodes)}decomposeLeft(_to,result){result.push(this)}decomposeRight(_from,result){result.push(this)}applyChanges(decorations,oldDoc,oracle,changes){let me=this,doc=oracle.doc;for(let i=changes.length-1;i>=0;i--){let{fromA:fromA,toA:toA,fromB:fromB,toB:toB}=changes[i],start=me.lineAt(fromA,QueryType$1.ByPosNoHeight,oracle.setDoc(oldDoc),0,0),end=start.to>=toA?start:me.lineAt(toA,QueryType$1.ByPosNoHeight,oracle,0,0);for(toB+=end.to-toA,toA=end.to;i>0&&start.from<=changes[i-1].toA;)fromA=changes[i-1].fromA,fromB=changes[i-1].fromB,i--,fromA2*after){let split=nodes[i-1];split.break?nodes.splice(--i,1,split.left,null,split.right):nodes.splice(--i,1,split.left,split.right),j+=1+split.break,before-=split.size}else{if(!(after>2*before))break;{let split=nodes[j];split.break?nodes.splice(j,1,split.left,null,split.right):nodes.splice(j,1,split.left,split.right),j+=2+split.break,after-=split.size}}else if(before=offset&&f(this.blockAt(0,oracle,top,offset))}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,measured=arguments.length>3?arguments[3]:void 0;return measured&&measured.from<=offset&&measured.more&&this.setHeight(oracle,measured.heights[measured.index++]),this.outdated=!1,this}toString(){return"block(".concat(this.length,")")}}class HeightMapText extends HeightMapBlock{constructor(length,height){super(length,height,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(_height,_oracle,top,offset){return new BlockInfo(offset,this.length,top,this.height,this.breaks)}replace(_from,_to,nodes){let node=nodes[0];return 1==nodes.length&&(node instanceof HeightMapText||node instanceof HeightMapGap&&4&node.flags)&&Math.abs(this.length-node.length)<10?(node instanceof HeightMapGap?node=new HeightMapText(node.length,this.height):node.height=this.height,this.outdated||(node.outdated=!1),node):HeightMap.of(nodes)}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0;return measured&&measured.from<=offset&&measured.more?this.setHeight(oracle,measured.heights[measured.index++]):(force||this.outdated)&&this.setHeight(oracle,Math.max(this.widgetHeight,oracle.heightForLine(this.length-this.collapsed))+this.breaks*oracle.lineHeight),this.outdated=!1,this}toString(){return"line(".concat(this.length).concat(this.collapsed?-this.collapsed:"").concat(this.widgetHeight?":"+this.widgetHeight:"",")")}}class HeightMapGap extends HeightMap{constructor(length){super(length,0)}heightMetrics(oracle,offset){let perLine,firstLine=oracle.doc.lineAt(offset).number,lastLine=oracle.doc.lineAt(offset+this.length).number,lines=lastLine-firstLine+1,perChar=0;if(oracle.lineWrapping){let totalPerLine=Math.min(this.height,oracle.lineHeight*lines);perLine=totalPerLine/lines,this.length>lines+1&&(perChar=(this.height-totalPerLine)/(this.length-lines-1))}else perLine=this.height/lines;return{firstLine:firstLine,lastLine:lastLine,perLine:perLine,perChar:perChar}}blockAt(height,oracle,top,offset){let{firstLine:firstLine,lastLine:lastLine,perLine:perLine,perChar:perChar}=this.heightMetrics(oracle,offset);if(oracle.lineWrapping){let guess=offset+(height0){let last=nodes[nodes.length-1];last instanceof HeightMapGap?nodes[nodes.length-1]=new HeightMapGap(last.length+after):nodes.push(null,new HeightMapGap(after-1))}if(from>0){let first=nodes[0];first instanceof HeightMapGap?nodes[0]=new HeightMapGap(from+first.length):nodes.unshift(new HeightMapGap(from-1),null)}return HeightMap.of(nodes)}decomposeLeft(to,result){result.push(new HeightMapGap(to-1),null)}decomposeRight(from,result){result.push(null,new HeightMapGap(this.length-from-1))}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0,end=offset+this.length;if(measured&&measured.from<=offset+this.length&&measured.more){let nodes=[],pos=Math.max(offset,measured.from),singleHeight=-1;for(measured.from>offset&&nodes.push(new HeightMapGap(measured.from-offset-1).updateHeight(oracle,offset));pos<=end&&measured.more;){let len=oracle.doc.lineAt(pos).length;nodes.length&&nodes.push(null);let height=measured.heights[measured.index++];-1==singleHeight?singleHeight=height:Math.abs(height-singleHeight)>=.001&&(singleHeight=-2);let line=new HeightMapText(len,height);line.outdated=!1,nodes.push(line),pos+=len+1}pos<=end&&nodes.push(null,new HeightMapGap(end-pos).updateHeight(oracle,pos));let result=HeightMap.of(nodes);return(singleHeight<0||Math.abs(result.height-this.height)>=.001||Math.abs(singleHeight-this.heightMetrics(oracle,offset).perLine)>=.001)&&(oracle.heightChanged=!0),result}return(force||this.outdated)&&(this.setHeight(oracle,oracle.heightForGap(offset,offset+this.length)),this.outdated=!1),this}toString(){return"gap(".concat(this.length,")")}}class HeightMapBranch extends HeightMap{constructor(left,brk,right){super(left.length+brk+right.length,left.height+right.height,brk|(left.outdated||right.outdated?2:0)),this.left=left,this.right=right,this.size=left.size+right.size}get break(){return 1&this.flags}blockAt(height,oracle,top,offset){let mid=top+this.left.height;return heightrightOffset))return base;let subQuery=type==QueryType$1.ByPosNoHeight?QueryType$1.ByPosNoHeight:QueryType$1.ByPos;return left?base.join(this.right.lineAt(rightOffset,subQuery,oracle,rightTop,rightOffset)):this.left.lineAt(rightOffset,subQuery,oracle,top,offset).join(base)}forEachLine(from,to,oracle,top,offset,f){let rightTop=top+this.left.height,rightOffset=offset+this.left.length+this.break;if(this.break)from=rightOffset&&this.right.forEachLine(from,to,oracle,rightTop,rightOffset,f);else{let mid=this.lineAt(rightOffset,QueryType$1.ByPos,oracle,top,offset);from=from&&mid.from<=to&&f(mid),to>mid.to&&this.right.forEachLine(mid.to+1,to,oracle,rightTop,rightOffset,f)}}replace(from,to,nodes){let rightStart=this.left.length+this.break;if(tothis.left.length)return this.balanced(this.left,this.right.replace(from-rightStart,to-rightStart,nodes));let result=[];from>0&&this.decomposeLeft(from,result);let left=result.length;for(let node of nodes)result.push(node);if(from>0&&mergeGaps(result,left-1),to=left&&result.push(null)),to>left&&this.right.decomposeLeft(to-left,result)}decomposeRight(from,result){let left=this.left.length,right=left+this.break;if(from>=right)return this.right.decomposeRight(from-right,result);from2*right.size||right.size>2*left.size?HeightMap.of(this.break?[left,null,right]:[left,right]):(this.left=left,this.right=right,this.height=left.height+right.height,this.outdated=left.outdated||right.outdated,this.size=left.size+right.size,this.length=left.length+this.break+right.length,this)}updateHeight(oracle){let offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,force=arguments.length>2&&void 0!==arguments[2]&&arguments[2],measured=arguments.length>3?arguments[3]:void 0,{left:left,right:right}=this,rightStart=offset+left.length+this.break,rebalance=null;return measured&&measured.from<=offset+left.length&&measured.more?rebalance=left=left.updateHeight(oracle,offset,force,measured):left.updateHeight(oracle,offset,force),measured&&measured.from<=rightStart+right.length&&measured.more?rebalance=right=right.updateHeight(oracle,rightStart,force,measured):right.updateHeight(oracle,rightStart,force),rebalance?this.balanced(left,right):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function mergeGaps(nodes,around){let before,after;null==nodes[around]&&(before=nodes[around-1])instanceof HeightMapGap&&(after=nodes[around+1])instanceof HeightMapGap&&nodes.splice(around-1,3,new HeightMapGap(before.length+1+after.length))}class NodeBuilder{constructor(pos,oracle){this.pos=pos,this.oracle=oracle,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=pos}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(_from,to){if(this.lineStart>-1){let end=Math.min(to,this.lineEnd),last=this.nodes[this.nodes.length-1];last instanceof HeightMapText?last.length+=end-this.pos:(end>this.pos||!this.isCovered)&&this.nodes.push(new HeightMapText(end-this.pos,-1)),this.writtenTo=end,to>end&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=to}point(from,to,deco){if(from=5)&&this.addLineDeco(height,breaks,len)}else to>from&&this.span(from,to);this.lineEnd>-1&&this.lineEnd-1)return;let{from:from,to:to}=this.oracle.doc.lineAt(this.pos);this.lineStart=from,this.lineEnd=to,this.writtenTofrom&&this.nodes.push(new HeightMapText(this.pos-from,-1)),this.writtenTo=this.pos}blankContent(from,to){let gap=new HeightMapGap(to-from);return this.oracle.doc.lineAt(from).to==to&&(gap.flags|=4),gap}ensureLine(){this.enterLine();let last=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(last instanceof HeightMapText)return last;let line=new HeightMapText(0,-1);return this.nodes.push(line),line}addBlock(block){this.enterLine();let deco=block.deco;deco&&deco.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(block),this.writtenTo=this.pos=this.pos+block.length,deco&&deco.endSide>0&&(this.covering=block)}addLineDeco(height,breaks,length){let line=this.ensureLine();line.length+=length,line.collapsed+=length,line.widgetHeight=Math.max(line.widgetHeight,height),line.breaks+=breaks,this.writtenTo=this.pos=this.pos+length}finish(from){let last=0==this.nodes.length?null:this.nodes[this.nodes.length-1];!(this.lineStart>-1)||last instanceof HeightMapText||this.isCovered?(this.writtenToelt.clientHeight||elt.scrollWidth>elt.clientWidth)&&"visible"!=style.overflow){let parentRect=elt.getBoundingClientRect();left=Math.max(left,parentRect.left),right=Math.min(right,parentRect.right),top=Math.max(top,parentRect.top),bottom=parent==dom.parentNode?parentRect.bottom:Math.min(bottom,parentRect.bottom)}parent="absolute"==style.position||"fixed"==style.position?elt.offsetParent:elt.parentNode}else{if(11!=parent.nodeType)break;parent=parent.host}return{left:left-rect.left,right:Math.max(left,right)-rect.left,top:top-(rect.top+paddingTop),bottom:Math.max(top,bottom)-(rect.top+paddingTop)}}function fullPixelRange(dom,paddingTop){let rect=dom.getBoundingClientRect();return{left:0,right:rect.right-rect.left,top:paddingTop,bottom:rect.bottom-(rect.top+paddingTop)}}class LineGap{constructor(from,to,size){this.from=from,this.to=to,this.size=size}static same(a,b){if(a.length!=b.length)return!1;for(let i=0;i"function"!=typeof v&&"cm-lineWrapping"==v.class));this.heightOracle=new HeightOracle(guessWrapping),this.stateDeco=state.facet(decorations).filter((d=>"function"!=typeof d)),this.heightMap=HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle.setDoc(state.doc),[new ChangedRange(0,0,0,state.doc.length)]);for(let i=0;i<2&&(this.viewport=this.getViewport(0,null),this.updateForViewport());i++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Decoration.set(this.lineGaps.map((gap=>gap.draw(this,!1)))),this.computeVisibleRanges()}updateForViewport(){let viewports=[this.viewport],{main:main}=this.state.selection;for(let i=0;i<=1;i++){let pos=i?main.head:main.anchor;if(!viewports.some((_ref2=>{let{from:from,to:to}=_ref2;return pos>=from&&pos<=to}))){let{from:from,to:to}=this.lineBlockAt(pos);viewports.push(new Viewport(from,to))}}return this.viewports=viewports.sort(((a,b)=>a.from-b.from)),this.updateScaler()}updateScaler(){let scaler=this.scaler;return this.scaler=this.heightMap.height<=7e6?IdScaler:new BigScaler(this.heightOracle,this.heightMap,this.viewports),scaler.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,(block=>{this.viewportLines.push(scaleBlock(block,this.scaler))}))}update(update){let scrollTarget=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;this.state=update.state;let prevDeco=this.stateDeco;this.stateDeco=this.state.facet(decorations).filter((d=>"function"!=typeof d));let contentChanges=update.changedRanges,heightChanges=ChangedRange.extendWithRanges(contentChanges,function(a,b,diff){let comp=new DecorationComparator;return RangeSet.compare(a,b,diff,comp,0),comp.changes}(prevDeco,this.stateDeco,update?update.changes:ChangeSet.empty(this.state.doc.length))),prevHeight=this.heightMap.height,scrollAnchor=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,update.startState.doc,this.heightOracle.setDoc(this.state.doc),heightChanges),this.heightMap.height!=prevHeight&&(update.flags|=2),scrollAnchor?(this.scrollAnchorPos=update.changes.mapPos(scrollAnchor.from,-1),this.scrollAnchorHeight=scrollAnchor.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let viewport=heightChanges.length?this.mapViewport(this.viewport,update.changes):this.viewport;(scrollTarget&&(scrollTarget.range.headviewport.to)||!this.viewportIsAppropriate(viewport))&&(viewport=this.getViewport(0,scrollTarget));let viewportChange=viewport.from!=this.viewport.from||viewport.to!=this.viewport.to;this.viewport=viewport,update.flags|=this.updateForViewport(),(viewportChange||!update.changes.empty||2&update.flags)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,update.changes))),update.flags|=this.computeVisibleRanges(),scrollTarget&&(this.scrollTarget=scrollTarget),!this.mustEnforceCursorAssoc&&update.selectionSet&&update.view.lineWrapping&&update.state.selection.main.empty&&update.state.selection.main.assoc&&!update.state.facet(nativeSelectionHidden)&&(this.mustEnforceCursorAssoc=!0)}measure(view){let dom=view.contentDOM,style=window.getComputedStyle(dom),oracle=this.heightOracle,whiteSpace=style.whiteSpace;this.defaultTextDirection="rtl"==style.direction?Direction.RTL:Direction.LTR;let refresh=this.heightOracle.mustRefreshForWrapping(whiteSpace),domRect=dom.getBoundingClientRect(),measureContent=refresh||this.mustMeasureContent||this.contentDOMHeight!=domRect.height;this.contentDOMHeight=domRect.height,this.mustMeasureContent=!1;let result=0,bias=0;if(domRect.width&&domRect.height){let{scaleX:scaleX,scaleY:scaleY}=getScale(dom,domRect);(scaleX>.005&&Math.abs(this.scaleX-scaleX)>.005||scaleY>.005&&Math.abs(this.scaleY-scaleY)>.005)&&(this.scaleX=scaleX,this.scaleY=scaleY,result|=8,refresh=measureContent=!0)}let paddingTop=(parseInt(style.paddingTop)||0)*this.scaleY,paddingBottom=(parseInt(style.paddingBottom)||0)*this.scaleY;this.paddingTop==paddingTop&&this.paddingBottom==paddingBottom||(this.paddingTop=paddingTop,this.paddingBottom=paddingBottom,result|=10),this.editorWidth!=view.scrollDOM.clientWidth&&(oracle.lineWrapping&&(measureContent=!0),this.editorWidth=view.scrollDOM.clientWidth,result|=8);let scrollTop=view.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=scrollTop&&(this.scrollAnchorHeight=-1,this.scrollTop=scrollTop),this.scrolledToBottom=isScrolledToBottom(view.scrollDOM);let pixelViewport=(this.printing?fullPixelRange:visiblePixelRange)(dom,this.paddingTop),dTop=pixelViewport.top-this.pixelViewport.top,dBottom=pixelViewport.bottom-this.pixelViewport.bottom;this.pixelViewport=pixelViewport;let inView=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(inView!=this.inView&&(this.inView=inView,inView&&(measureContent=!0)),!this.inView&&!this.scrollTarget)return 0;let contentWidth=domRect.width;if(this.contentDOMWidth==contentWidth&&this.editorHeight==view.scrollDOM.clientHeight||(this.contentDOMWidth=domRect.width,this.editorHeight=view.scrollDOM.clientHeight,result|=8),measureContent){let lineHeights=view.docView.measureVisibleLineHeights(this.viewport);if(oracle.mustRefreshForHeights(lineHeights)&&(refresh=!0),refresh||oracle.lineWrapping&&Math.abs(contentWidth-this.contentDOMWidth)>oracle.charWidth){let{lineHeight:lineHeight,charWidth:charWidth,textHeight:textHeight}=view.docView.measureTextSize();refresh=lineHeight>0&&oracle.refresh(whiteSpace,lineHeight,charWidth,textHeight,contentWidth/charWidth,lineHeights),refresh&&(view.docView.minWidth=0,result|=8)}dTop>0&&dBottom>0?bias=Math.max(dTop,dBottom):dTop<0&&dBottom<0&&(bias=Math.min(dTop,dBottom)),oracle.heightChanged=!1;for(let vp of this.viewports){let heights=vp.from==this.viewport.from?lineHeights:view.docView.measureVisibleLineHeights(vp);this.heightMap=(refresh?HeightMap.empty().applyChanges(this.stateDeco,Text.empty,this.heightOracle,[new ChangedRange(0,0,0,view.state.doc.length)]):this.heightMap).updateHeight(oracle,0,refresh,new MeasuredHeights(vp.from,heights))}oracle.heightChanged&&(result|=2)}let viewportChange=!this.viewportIsAppropriate(this.viewport,bias)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return viewportChange&&(2&result&&(result|=this.updateScaler()),this.viewport=this.getViewport(bias,this.scrollTarget),result|=this.updateForViewport()),(2&result||viewportChange)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(refresh?[]:this.lineGaps,view)),result|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,view.docView.enforceCursorAssoc()),result}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(bias,scrollTarget){let marginTop=.5-Math.max(-.5,Math.min(.5,bias/1e3/2)),map=this.heightMap,oracle=this.heightOracle,{visibleTop:visibleTop,visibleBottom:visibleBottom}=this,viewport=new Viewport(map.lineAt(visibleTop-1e3*marginTop,QueryType$1.ByHeight,oracle,0,0).from,map.lineAt(visibleBottom+1e3*(1-marginTop),QueryType$1.ByHeight,oracle,0,0).to);if(scrollTarget){let{head:head}=scrollTarget.range;if(headviewport.to){let topPos,viewHeight=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),block=map.lineAt(head,QueryType$1.ByPos,oracle,0,0);topPos="center"==scrollTarget.y?(block.top+block.bottom)/2-viewHeight/2:"start"==scrollTarget.y||"nearest"==scrollTarget.y&&head1&&void 0!==arguments[1]?arguments[1]:0;if(!this.inView)return!0;let{top:top}=this.heightMap.lineAt(from,QueryType$1.ByPos,this.heightOracle,0,0),{bottom:bottom}=this.heightMap.lineAt(to,QueryType$1.ByPos,this.heightOracle,0,0),{visibleTop:visibleTop,visibleBottom:visibleBottom}=this;return(0==from||top<=visibleTop-Math.max(10,Math.min(-bias,250)))&&(to==this.state.doc.length||bottom>=visibleBottom+Math.max(10,Math.min(bias,250)))&&top>visibleTop-2e3&&bottom>1,doubleMargin=margin<<1;if(this.defaultTextDirection!=Direction.LTR&&!wrapping)return[];let gaps=[],addGap=(from,to,line,structure)=>{if(to-fromfrom&&posgap.from>=line.from&&gap.to<=line.to&&Math.abs(gap.from-from)gap.frompos))));if(!gap){if(tor.from<=to&&r.to>=to))){let lineStart=mayMeasure.moveToLineBoundary(EditorSelection.cursor(to),!1,!0).head;lineStart>from&&(to=lineStart)}gap=new LineGap(from,to,this.gapSize(line,from,to,structure))}gaps.push(gap)},checkLine=line=>{if(line.lengthpos&&(ranges.push({from:pos,to:from}),total+=from-pos),pos=to}},20),posline.from&&addGap(line.from,viewFrom,line,structure),viewTogap.draw(this,this.heightOracle.lineWrapping)))))}computeVisibleRanges(){let deco=this.stateDeco;this.lineGaps.length&&(deco=deco.concat(this.lineGapDeco));let ranges=[];RangeSet.spans(deco,this.viewport.from,this.viewport.to,{span(from,to){ranges.push({from:from,to:to})},point(){}},20);let changed=ranges.length!=this.visibleRanges.length||this.visibleRanges.some(((r,i)=>r.from!=ranges[i].from||r.to!=ranges[i].to));return this.visibleRanges=ranges,changed?4:0}lineBlockAt(pos){return pos>=this.viewport.from&&pos<=this.viewport.to&&this.viewportLines.find((b=>b.from<=pos&&b.to>=pos))||scaleBlock(this.heightMap.lineAt(pos,QueryType$1.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(height){return height>=this.viewportLines[0].top&&height<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find((l=>l.top<=height&&l.bottom>=height))||scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height),QueryType$1.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(scrollTop){let block=this.lineBlockAtHeight(scrollTop+8);return block.from>=this.viewport.from||this.viewportLines[0].top-scrollTop>200?block:this.viewportLines[0]}elementAtHeight(height){return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Viewport{constructor(from,to){this.from=from,this.to=to}}function findPosition(_ref4,ratio){let{total:total,ranges:ranges}=_ref4;if(ratio<=0)return ranges[0].from;if(ratio>=1)return ranges[ranges.length-1].to;let dist=Math.floor(total*ratio);for(let i=0;;i++){let{from:from,to:to}=ranges[i],size=to-from;if(dist<=size)return from+dist;dist-=size}}function findFraction(structure,pos){let counted=0;for(let{from:from,to:to}of structure.ranges){if(pos<=to){counted+=pos-from;break}counted+=to-from}return counted/structure.total}const IdScaler={toDOM:n=>n,fromDOM:n=>n,scale:1,eq(other){return other==this}};class BigScaler{constructor(oracle,heightMap,viewports){let vpHeight=0,base=0,domBase=0;this.viewports=viewports.map((_ref5=>{let{from:from,to:to}=_ref5,top=heightMap.lineAt(from,QueryType$1.ByPos,oracle,0,0).top,bottom=heightMap.lineAt(to,QueryType$1.ByPos,oracle,0,0).bottom;return vpHeight+=bottom-top,{from:from,to:to,top:top,bottom:bottom,domTop:0,domBottom:0}})),this.scale=(7e6-vpHeight)/(heightMap.height-vpHeight);for(let obj of this.viewports)obj.domTop=domBase+(obj.top-base)*this.scale,domBase=obj.domBottom=obj.domTop+(obj.bottom-obj.top),base=obj.bottom}toDOM(n){for(let i=0,base=0,domBase=0;;i++){let vp=ivp.from==other.viewports[i].from&&vp.to==other.viewports[i].to)))}}function scaleBlock(block,scaler){if(1==scaler.scale)return block;let bTop=scaler.toDOM(block.top),bBottom=scaler.toDOM(block.bottom);return new BlockInfo(block.from,block.length,bTop,bBottom-bTop,Array.isArray(block._content)?block._content.map((b=>scaleBlock(b,scaler))):block._content)}const theme=Facet.define({combine:strs=>strs.join(" ")}),darkTheme=Facet.define({combine:values=>values.indexOf(!0)>-1}),baseThemeID=StyleModule.newName(),baseLightID=StyleModule.newName(),baseDarkID=StyleModule.newName(),lightDarkIDs={"&light":"."+baseLightID,"&dark":"."+baseDarkID};function buildTheme(main,spec,scopes){return new StyleModule(spec,{finish:sel=>/&/.test(sel)?sel.replace(/&\w*/,(m=>{if("&"==m)return main;if(!scopes||!scopes[m])throw new RangeError("Unsupported selector: ".concat(m));return scopes[m]})):main+" "+sel})}const baseTheme$1$3=buildTheme("."+baseThemeID,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:'url(\'data:image/svg+xml,\')',backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},lightDarkIDs);class DOMReader{constructor(points,state){this.points=points,this.text="",this.lineSeparator=state.facet(EditorState.lineSeparator)}append(text){this.text+=text}lineBreak(){this.text+="￿"}readRange(start,end){if(!start)return this;let parent=start.parentNode;for(let cur=start;;){this.findPointBefore(parent,cur);let oldLen=this.text.length;this.readNode(cur);let next=cur.nextSibling;if(next==end)break;let view=ContentView.get(cur),nextView=ContentView.get(next);(view&&nextView?view.breakAfter:(view?view.breakAfter:isBlockElement(cur))||isBlockElement(next)&&("BR"!=cur.nodeName||cur.cmIgnore)&&this.text.length>oldLen)&&this.lineBreak(),cur=next}return this.findPointBefore(parent,end),this}readTextNode(node){let text=node.nodeValue;for(let point of this.points)point.node==node&&(point.pos=this.text.length+Math.min(point.offset,text.length));for(let off=0,re=this.lineSeparator?null:/\r\n?|\n/g;;){let m,nextBreak=-1,breakSize=1;if(this.lineSeparator?(nextBreak=text.indexOf(this.lineSeparator,off),breakSize=this.lineSeparator.length):(m=re.exec(text))&&(nextBreak=m.index,breakSize=m[0].length),this.append(text.slice(off,nextBreak<0?text.length:nextBreak)),nextBreak<0)break;if(this.lineBreak(),breakSize>1)for(let point of this.points)point.node==node&&point.pos>this.text.length&&(point.pos-=breakSize-1);off=nextBreak+breakSize}}readNode(node){if(node.cmIgnore)return;let view=ContentView.get(node),fromView=view&&view.overrideDOMText;if(null!=fromView){this.findPointInside(node,fromView.length);for(let i=fromView.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else 3==node.nodeType?this.readTextNode(node):"BR"==node.nodeName?node.nextSibling&&this.lineBreak():1==node.nodeType&&this.readRange(node.firstChild,null)}findPointBefore(node,next){for(let point of this.points)point.node==node&&node.childNodes[point.offset]==next&&(point.pos=this.text.length)}findPointInside(node,length){for(let point of this.points)(3==node.nodeType?point.node==node:node.contains(point.node))&&(point.pos=this.text.length+(isAtEnd(node,point.node,point.offset)?length:0))}}function isAtEnd(parent,node,offset){for(;;){if(!node||offset-1;let{impreciseHead:iHead,impreciseAnchor:iAnchor}=view.docView;if(view.state.readOnly&&start>-1)this.newSel=null;else if(start>-1&&(this.bounds=view.docView.domBoundsAround(start,end,0))){let selPoints=iHead||iAnchor?[]:function(view){let result=[];if(view.root.activeElement!=view.contentDOM)return result;let{anchorNode:anchorNode,anchorOffset:anchorOffset,focusNode:focusNode,focusOffset:focusOffset}=view.observer.selectionRange;anchorNode&&(result.push(new DOMPoint(anchorNode,anchorOffset)),focusNode==anchorNode&&focusOffset==anchorOffset||result.push(new DOMPoint(focusNode,focusOffset)));return result}(view),reader=new DOMReader(selPoints,view.state);reader.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=reader.text,this.newSel=function(points,base){if(0==points.length)return null;let anchor=points[0].pos,head=2==points.length?points[1].pos:anchor;return anchor>-1&&head>-1?EditorSelection.single(anchor+base,head+base):null}(selPoints,this.bounds.from)}else{let domSel=view.observer.selectionRange,head=iHead&&iHead.node==domSel.focusNode&&iHead.offset==domSel.focusOffset||!contains(view.contentDOM,domSel.focusNode)?view.state.selection.main.head:view.docView.posFromDOM(domSel.focusNode,domSel.focusOffset),anchor=iAnchor&&iAnchor.node==domSel.anchorNode&&iAnchor.offset==domSel.anchorOffset||!contains(view.contentDOM,domSel.anchorNode)?view.state.selection.main.anchor:view.docView.posFromDOM(domSel.anchorNode,domSel.anchorOffset),vp=view.viewport;if((browser.ios||browser.chrome)&&view.state.selection.main.empty&&head!=anchor&&(vp.from>0||vp.toDate.now()-100?view.inputState.lastKeyCode:-1;if(domChange.bounds){let{from:from,to:to}=domChange.bounds,preferredPos=sel.from,preferredSide=null;(8===lastKey||browser.android&&domChange.text.length0&&toB>0&&a.charCodeAt(toA-1)==b.charCodeAt(toB-1);)toA--,toB--;if("end"==preferredSide){preferredPos-=toA+Math.max(0,from-Math.min(toA,toB))-from}if(toA=toA?from-preferredPos:0,toB=from+(toB-toA),toA=from}else if(toB=toB?from-preferredPos:0,toA=from+(toA-toB),toB=from}return{from:from,toA:toA,toB:toB}}(view.state.doc.sliceString(from,to,"￿"),domChange.text,preferredPos-from,preferredSide);diff&&(browser.chrome&&13==lastKey&&diff.toB==diff.from+2&&"￿￿"==domChange.text.slice(diff.from,diff.toB)&&diff.toB--,change={from:from+diff.from,to:from+diff.toA,insert:Text.of(domChange.text.slice(diff.from,diff.toB).split("￿"))})}else newSel&&(!view.hasFocus&&view.state.facet(editable)||newSel.main.eq(sel))&&(newSel=null);if(!change&&!newSel)return!1;if(!change&&domChange.typeOver&&!sel.empty&&newSel&&newSel.main.empty?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,sel.to)}:change&&change.from>=sel.from&&change.to<=sel.to&&(change.from!=sel.from||change.to!=sel.to)&&sel.to-sel.from-(change.to-change.from)<=4?change={from:sel.from,to:sel.to,insert:view.state.doc.slice(sel.from,change.from).append(change.insert).append(view.state.doc.slice(change.to,sel.to))}:(browser.mac||browser.android)&&change&&change.from==change.to&&change.from==sel.head-1&&/^\. ?$/.test(change.insert.toString())&&"off"==view.contentDOM.getAttribute("autocorrect")?(newSel&&2==change.insert.length&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}):browser.chrome&&change&&change.from==change.to&&change.from==sel.head&&"\n "==change.insert.toString()&&view.lineWrapping&&(newSel&&(newSel=EditorSelection.single(newSel.main.anchor-1,newSel.main.head-1)),change={from:sel.from,to:sel.to,insert:Text.of([" "])}),change)return applyDOMChangeInner(view,change,newSel,lastKey);if(newSel&&!newSel.main.eq(sel)){let scrollIntoView=!1,userEvent="select";return view.inputState.lastSelectionTime>Date.now()-50&&("select"==view.inputState.lastSelectionOrigin&&(scrollIntoView=!0),userEvent=view.inputState.lastSelectionOrigin),view.dispatch({selection:newSel,scrollIntoView:scrollIntoView,userEvent:userEvent}),!0}return!1}function applyDOMChangeInner(view,change,newSel){let lastKey=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1;if(browser.ios&&view.inputState.flushIOSKey(change))return!0;let sel=view.state.selection.main;if(browser.android&&(change.to==sel.to&&(change.from==sel.from||change.from==sel.from-1&&" "==view.state.sliceDoc(change.from,sel.from))&&1==change.insert.length&&2==change.insert.lines&&dispatchKey(view.contentDOM,"Enter",13)||(change.from==sel.from-1&&change.to==sel.to&&0==change.insert.length||8==lastKey&&change.insert.lengthsel.head)&&dispatchKey(view.contentDOM,"Backspace",8)||change.from==sel.from&&change.to==sel.to+1&&0==change.insert.length&&dispatchKey(view.contentDOM,"Delete",46)))return!0;let defaultTr,text=change.insert.toString();view.inputState.composing>=0&&view.inputState.composing++;let defaultInsert=()=>defaultTr||(defaultTr=applyDefaultInsert(view,change,newSel));return view.state.facet(inputHandler$1).some((h=>h(view,change.from,change.to,text,defaultInsert)))||view.dispatch(defaultInsert()),!0}function applyDefaultInsert(view,change,newSel){let tr,startState=view.state,sel=startState.selection.main;if(change.from>=sel.from&&change.to<=sel.to&&change.to-change.from>=(sel.to-sel.from)/3&&(!newSel||newSel.main.empty&&newSel.main.from==change.from+change.insert.length)&&view.inputState.composing<0){let before=sel.fromchange.to?startState.sliceDoc(change.to,sel.to):"";tr=startState.replaceSelection(view.state.toText(before+change.insert.sliceString(0,void 0,view.state.lineBreak)+after))}else{let changes=startState.changes(change),mainSel=newSel&&newSel.main.to<=changes.newLength?newSel.main:void 0;if(startState.selection.ranges.length>1&&view.inputState.composing>=0&&change.to<=sel.to&&change.to>=sel.to-10){let compositionRange,replaced=view.state.sliceDoc(change.from,change.to),composition=newSel&&findCompositionNode(view,newSel.main.head);if(composition){let dLen=change.insert.length-(change.to-change.from);compositionRange={from:composition.from,to:composition.to-dLen}}else compositionRange=view.state.doc.lineAt(sel.head);let offset=sel.to-change.to,size=sel.to-sel.from;tr=startState.changeByRange((range=>{if(range.from==sel.from&&range.to==sel.to)return{changes:changes,range:mainSel||range.map(changes)};let to=range.to-offset,from=to-replaced.length;if(range.to-range.from!=size||view.state.sliceDoc(from,to)!=replaced||range.to>=compositionRange.from&&range.from<=compositionRange.to)return{range:range};let rangeChanges=startState.changes({from:from,to:to,insert:change.insert}),selOff=range.to-sel.to;return{changes:rangeChanges,range:mainSel?EditorSelection.range(Math.max(0,mainSel.anchor+selOff),Math.max(0,mainSel.head+selOff)):range.map(rangeChanges)}}))}else tr={changes:changes,selection:mainSel&&startState.selection.replaceRange(mainSel)}}let userEvent="input.type";return(view.composing||view.inputState.compositionPendingChange&&view.inputState.compositionEndedAt>Date.now()-50)&&(view.inputState.compositionPendingChange=!1,userEvent+=".compose",view.inputState.compositionFirstChange&&(userEvent+=".start",view.inputState.compositionFirstChange=!1)),startState.update(tr,{userEvent:userEvent,scrollIntoView:!0})}const observeOptions={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},useCharData=browser.ie&&browser.ie_version<=11;class DOMObserver{constructor(view){this.view=view,this.active=!1,this.editContext=null,this.selectionRange=new DOMSelectionState,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=view.contentDOM,this.observer=new MutationObserver((mutations=>{for(let mut of mutations)this.queue.push(mut);(browser.ie&&browser.ie_version<=11||browser.ios&&view.composing)&&mutations.some((m=>"childList"==m.type&&m.removedNodes.length||"characterData"==m.type&&m.oldValue.length>m.target.nodeValue.length))?this.flushSoon():this.flush()})),!window.EditContext||!1===view.constructor.EDIT_CONTEXT||browser.chrome&&browser.chrome_version<126||(this.editContext=new EditContextManager(view),view.state.facet(editable)&&(view.contentDOM.editContext=this.editContext.editContext)),useCharData&&(this.onCharData=event=>{this.queue.push({target:event.target,type:"characterData",oldValue:event.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),"function"==typeof ResizeObserver&&(this.resizeScroll=new ResizeObserver((()=>{var _a;(null===(_a=this.view.docView)||void 0===_a?void 0:_a.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),entries.length>0&&entries[entries.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))}),{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver((entries=>{entries.length>0&&entries[entries.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))}),{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout((()=>{this.resizeTimeout=-1,this.view.requestMeasure()}),50))}onPrint(event){("change"!=event.type||event.matches)&&(this.view.viewState.printing=!0,this.view.measure(),setTimeout((()=>{this.view.viewState.printing=!1,this.view.requestMeasure()}),500))}updateGaps(gaps){if(this.gapIntersection&&(gaps.length!=this.gaps.length||this.gaps.some(((g,i)=>g!=gaps[i])))){this.gapIntersection.disconnect();for(let gap of gaps)this.gapIntersection.observe(gap);this.gaps=gaps}}onSelectionChange(event){let wasChanged=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:view}=this,sel=this.selectionRange;if(view.state.facet(editable)?view.root.activeElement!=this.dom:!hasSelection(view.dom,sel))return;let context=sel.anchorNode&&view.docView.nearest(sel.anchorNode);context&&context.ignoreEvent(event)?wasChanged||(this.selectionChanged=!1):(browser.ie&&browser.ie_version<=11||browser.android&&browser.chrome)&&!view.state.selection.main.empty&&sel.focusNode&&isEquivalentPosition(sel.focusNode,sel.focusOffset,sel.anchorNode,sel.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:view}=this,selection=getSelection(view.root);if(!selection)return!1;let range=browser.safari&&11==view.root.nodeType&&function(doc){let elt=doc.activeElement;for(;elt&&elt.shadowRoot;)elt=elt.shadowRoot.activeElement;return elt}(this.dom.ownerDocument)==this.dom&&function(view,selection){if(selection.getComposedRanges){let range=selection.getComposedRanges(view.root)[0];if(range)return buildSelectionRangeFromRange(view,range)}let found=null;function read(event){event.preventDefault(),event.stopImmediatePropagation(),found=event.getTargetRanges()[0]}return view.contentDOM.addEventListener("beforeinput",read,!0),view.dom.ownerDocument.execCommand("indent"),view.contentDOM.removeEventListener("beforeinput",read,!0),found?buildSelectionRangeFromRange(view,found):null}(this.view,selection)||selection;if(!range||this.selectionRange.eq(range))return!1;let local=hasSelection(this.dom,range);return local&&!this.selectionChanged&&view.inputState.lastFocusTime>Date.now()-200&&view.inputState.lastTouchTime{let key=this.delayedAndroidKey;if(key){this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=key.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&key.force&&dispatchKey(this.dom,key.key,key.keyCode)}};this.flushingAndroidKey=this.view.win.requestAnimationFrame(flush)}this.delayedAndroidKey&&"Enter"!=key||(this.delayedAndroidKey={key:key,keyCode:keyCode,force:this.lastChange{this.delayedFlush=-1,this.flush()})))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let mut of this.observer.takeRecords())this.queue.push(mut);return this.queue}processRecords(){let records=this.pendingRecords();records.length&&(this.queue=[]);let from=-1,to=-1,typeOver=!1;for(let record of records){let range=this.readMutation(record);range&&(range.typeOver&&(typeOver=!0),-1==from?({from:from,to:to}=range):(from=Math.min(range.from,from),to=Math.max(range.to,to)))}return{from:from,to:to,typeOver:typeOver}}readChange(){let{from:from,to:to,typeOver:typeOver}=this.processRecords(),newSel=this.selectionChanged&&hasSelection(this.dom,this.selectionRange);if(from<0&&!newSel)return null;from>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let change=new DOMChange(this.view,from,to,typeOver);return this.view.docView.domChanged={newSel:change.newSel?change.newSel.main:null},change}flush(){let readSelection=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;readSelection&&this.readSelectionRange();let domChange=this.readChange();if(!domChange)return this.view.requestMeasure(),!1;let startState=this.view.state,handled=applyDOMChange(this.view,domChange);return this.view.state==startState&&(domChange.domChanged||domChange.newSel&&!domChange.newSel.main.eq(this.view.state.selection.main))&&this.view.update([]),handled}readMutation(rec){let cView=this.view.docView.nearest(rec.target);if(!cView||cView.ignoreMutation(rec))return null;if(cView.markDirty("attributes"==rec.type),"attributes"==rec.type&&(cView.flags|=4),"childList"==rec.type){let childBefore=findChild(cView,rec.previousSibling||rec.target.previousSibling,-1),childAfter=findChild(cView,rec.nextSibling||rec.target.nextSibling,1);return{from:childBefore?cView.posAfter(childBefore):cView.posAtStart,to:childAfter?cView.posBefore(childAfter):cView.posAtEnd,typeOver:!1}}return"characterData"==rec.type?{from:cView.posAtStart,to:cView.posAtEnd,typeOver:rec.target.nodeValue==rec.oldValue}:null}setWindow(win){win!=this.win&&(this.removeWindowListeners(this.win),this.win=win,this.addWindowListeners(this.win))}addWindowListeners(win){win.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener("change",this.onPrint):win.addEventListener("beforeprint",this.onPrint),win.addEventListener("scroll",this.onScroll),win.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(win){win.removeEventListener("scroll",this.onScroll),win.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener("change",this.onPrint):win.removeEventListener("beforeprint",this.onPrint),win.document.removeEventListener("selectionchange",this.onSelectionChange)}update(update){this.editContext&&(this.editContext.update(update),update.startState.facet(editable)!=update.state.facet(editable)&&(update.view.contentDOM.editContext=update.state.facet(editable)?this.editContext.editContext:null))}destroy(){var _a,_b,_c;this.stop(),null===(_a=this.intersection)||void 0===_a||_a.disconnect(),null===(_b=this.gapIntersection)||void 0===_b||_b.disconnect(),null===(_c=this.resizeScroll)||void 0===_c||_c.disconnect();for(let dom of this.scrollTargets)dom.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function findChild(cView,dom,dir){for(;dom;){let curView=ContentView.get(dom);if(curView&&curView.parent==cView)return curView;let parent=dom.parentNode;dom=parent!=cView.dom?parent:dir>0?dom.nextSibling:dom.previousSibling}return null}function buildSelectionRangeFromRange(view,range){let anchorNode=range.startContainer,anchorOffset=range.startOffset,focusNode=range.endContainer,focusOffset=range.endOffset,curAnchor=view.docView.domAtPos(view.state.selection.main.anchor);return isEquivalentPosition(curAnchor.node,curAnchor.offset,focusNode,focusOffset)&&([anchorNode,anchorOffset,focusNode,focusOffset]=[focusNode,focusOffset,anchorNode,anchorOffset]),{anchorNode:anchorNode,anchorOffset:anchorOffset,focusNode:focusNode,focusOffset:focusOffset}}class EditContextManager{constructor(view){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.resetRange(view.state);let context=this.editContext=new window.EditContext({text:view.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,view.state.selection.main.anchor))),selectionEnd:this.toContextPos(view.state.selection.main.head)});this.handlers.textupdate=e=>{let{anchor:anchor}=view.state.selection.main,change={from:this.toEditorPos(e.updateRangeStart),to:this.toEditorPos(e.updateRangeEnd),insert:Text.of(e.text.split("\n"))};change.from==this.from&&anchorthis.to&&(change.to=anchor),(change.from!=change.to||change.insert.length)&&(this.pendingContextChange=change,applyDOMChangeInner(view,change,EditorSelection.single(this.toEditorPos(e.selectionStart),this.toEditorPos(e.selectionEnd))),this.pendingContextChange&&this.revertPending(view.state))},this.handlers.characterboundsupdate=e=>{let rects=[],prev=null;for(let i=this.toEditorPos(e.rangeStart),end=this.toEditorPos(e.rangeEnd);i{let deco=[];for(let format of e.getTextFormats()){let lineStyle=format.underlineStyle,thickness=format.underlineThickness;if("None"!=lineStyle&&"None"!=thickness){let style="text-decoration: underline ".concat("Dashed"==lineStyle?"dashed ":"Squiggle"==lineStyle?"wavy ":"").concat("Thin"==thickness?1:2,"px");deco.push(Decoration.mark({attributes:{style:style}}).range(this.toEditorPos(format.rangeStart),this.toEditorPos(format.rangeEnd)))}}view.dispatch({effects:setEditContextFormatting.of(Decoration.set(deco))})},this.handlers.compositionstart=()=>{view.inputState.composing<0&&(view.inputState.composing=0,view.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{view.inputState.composing=-1,view.inputState.compositionFirstChange=null};for(let event in this.handlers)context.addEventListener(event,this.handlers[event]);this.measureReq={read:view=>{this.editContext.updateControlBounds(view.contentDOM.getBoundingClientRect());let sel=getSelection(view.root);sel&&sel.rangeCount&&this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect())}}}applyEdits(update){let off=0,abort=!1,pending=this.pendingContextChange;return update.changes.iterChanges(((fromA,toA,_fromB,_toB,insert)=>{if(abort)return;let dLen=insert.length-(toA-fromA);if(pending&&toA>=pending.to){if(pending.from==fromA&&pending.to==toA&&pending.insert.eq(insert))return pending=this.pendingContextChange=null,off+=dLen,void(this.to+=dLen);pending=null,this.revertPending(update.state)}if(fromA+=off,(toA+=off)<=this.from)this.from+=dLen,this.to+=dLen;else if(fromAthis.to||this.to-this.from+insert.length>3e4)return void(abort=!0);this.editContext.updateText(this.toContextPos(fromA),this.toContextPos(toA),insert.toString()),this.to+=dLen}off+=dLen})),pending&&!abort&&this.revertPending(update.state),!abort}update(update){this.applyEdits(update)&&this.rangeIsValid(update.state)?(update.docChanged||update.selectionSet)&&this.setSelection(update.state):(this.pendingContextChange=null,this.resetRange(update.state),this.editContext.updateText(0,this.editContext.text.length,update.state.doc.sliceString(this.from,this.to)),this.setSelection(update.state)),(update.geometryChanged||update.docChanged||update.selectionSet)&&update.view.requestMeasure(this.measureReq)}resetRange(state){let{head:head}=state.selection.main;this.from=Math.max(0,head-1e4),this.to=Math.min(state.doc.length,head+1e4)}revertPending(state){let pending=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(pending.from),this.toContextPos(pending.to+pending.insert.length),state.doc.sliceString(pending.from,pending.to))}setSelection(state){let{main:main}=state.selection,start=this.toContextPos(Math.max(this.from,Math.min(this.to,main.anchor))),end=this.toContextPos(main.head);this.editContext.selectionStart==start&&this.editContext.selectionEnd==end||this.editContext.updateSelection(start,end)}rangeIsValid(state){let{head:head}=state.selection.main;return!(this.from>0&&head-this.from<500||this.to3e4)}toEditorPos(contextPos){return contextPos+this.from}toContextPos(editorPos){return editorPos-this.from}destroy(){for(let event in this.handlers)this.editContext.removeEventListener(event,this.handlers[event])}}class EditorView{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),config.parent&&config.parent.appendChild(this.dom);let{dispatch:dispatch}=config;this.dispatchTransactions=config.dispatchTransactions||dispatch&&(trs=>trs.forEach((tr=>dispatch(tr,this))))||(trs=>this.update(trs)),this.dispatch=this.dispatch.bind(this),this._root=config.root||function(node){for(;node;){if(node&&(9==node.nodeType||11==node.nodeType&&node.host))return node;node=node.assignedSlot||node.parentNode}return null}(config.parent)||document,this.viewState=new ViewState(config.state||EditorState.create(config)),config.scrollTo&&config.scrollTo.is(scrollIntoView$1)&&(this.viewState.scrollTarget=config.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(viewPlugin).map((spec=>new PluginInstance(spec)));for(let plugin of this.plugins)plugin.update(this);this.observer=new DOMObserver(this),this.inputState=new InputState(this),this.inputState.ensureHandlers(this.plugins),this.docView=new DocView(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(){for(var _len3=arguments.length,input=new Array(_len3),_key3=0;_key3<_len3;_key3++)input[_key3]=arguments[_key3];let trs=1==input.length&&input[0]instanceof Transaction?input:1==input.length&&Array.isArray(input[0])?input[0]:[this.state.update(...input)];this.dispatchTransactions(trs,this)}update(transactions){if(0!=this.updateState)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let update,redrawn=!1,attrsChanged=!1,state=this.state;for(let tr of transactions){if(tr.startState!=state)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");state=tr.state}if(this.destroyed)return void(this.viewState.state=state);let focus=this.hasFocus,focusFlag=0,dispatchFocus=null;transactions.some((tr=>tr.annotation(isFocusChange)))?(this.inputState.notifiedFocused=focus,focusFlag=1):focus!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=focus,dispatchFocus=focusChangeTransaction(state,focus),dispatchFocus||(focusFlag=1));let pendingKey=this.observer.delayedAndroidKey,domChange=null;if(pendingKey?(this.observer.clearDelayedAndroidKey(),domChange=this.observer.readChange(),(domChange&&!this.state.doc.eq(state.doc)||!this.state.selection.eq(state.selection))&&(domChange=null)):this.observer.clear(),state.facet(EditorState.phrases)!=this.state.facet(EditorState.phrases))return this.setState(state);update=ViewUpdate.create(this,state,transactions),update.flags|=focusFlag;let scrollTarget=this.viewState.scrollTarget;try{this.updateState=2;for(let tr of transactions){if(scrollTarget&&(scrollTarget=scrollTarget.map(tr.changes)),tr.scrollIntoView){let{main:main}=tr.state.selection;scrollTarget=new ScrollTarget(main.empty?main:EditorSelection.cursor(main.head,main.head>main.anchor?-1:1))}for(let e of tr.effects)e.is(scrollIntoView$1)&&(scrollTarget=e.value.clip(this.state))}this.viewState.update(update,scrollTarget),this.bidiCache=CachedOrder.update(this.bidiCache,update.changes),update.empty||(this.updatePlugins(update),this.inputState.update(update)),redrawn=this.docView.update(update),this.state.facet(styleModule)!=this.styleModules&&this.mountStyles(),attrsChanged=this.updateAttrs(),this.showAnnouncements(transactions),this.docView.updateSelection(redrawn,transactions.some((tr=>tr.isUserEvent("select.pointer"))))}finally{this.updateState=0}if(update.startState.facet(theme)!=update.state.facet(theme)&&(this.viewState.mustMeasureContent=!0),(redrawn||attrsChanged||scrollTarget||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),redrawn&&this.docViewUpdate(),!update.empty)for(let listener of this.state.facet(updateListener))try{listener(update)}catch(e){logException(this.state,e,"update listener")}(dispatchFocus||domChange)&&Promise.resolve().then((()=>{dispatchFocus&&this.state==dispatchFocus.startState&&this.dispatch(dispatchFocus),domChange&&!applyDOMChange(this,domChange)&&pendingKey.force&&dispatchKey(this.contentDOM,pendingKey.key,pendingKey.keyCode)}))}setState(newState){if(0!=this.updateState)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed)return void(this.viewState.state=newState);this.updateState=2;let hadFocus=this.hasFocus;try{for(let plugin of this.plugins)plugin.destroy(this);this.viewState=new ViewState(newState),this.plugins=newState.facet(viewPlugin).map((spec=>new PluginInstance(spec))),this.pluginMap.clear();for(let plugin of this.plugins)plugin.update(this);this.docView.destroy(),this.docView=new DocView(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}hadFocus&&this.focus(),this.requestMeasure()}updatePlugins(update){let prevSpecs=update.startState.facet(viewPlugin),specs=update.state.facet(viewPlugin);if(prevSpecs!=specs){let newPlugins=[];for(let spec of specs){let found=prevSpecs.indexOf(spec);if(found<0)newPlugins.push(new PluginInstance(spec));else{let plugin=this.plugins[found];plugin.mustUpdate=update,newPlugins.push(plugin)}}for(let plugin of this.plugins)plugin.mustUpdate!=update&&plugin.destroy(this);this.plugins=newPlugins,this.pluginMap.clear()}else for(let p of this.plugins)p.mustUpdate=update;for(let i=0;i0&&void 0!==arguments[0])||arguments[0];if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey)return this.measureScheduled=-1,void this.requestMeasure();this.measureScheduled=0,flush&&this.observer.forceFlush();let updated=null,sDOM=this.scrollDOM,scrollTop=sDOM.scrollTop*this.scaleY,{scrollAnchorPos:scrollAnchorPos,scrollAnchorHeight:scrollAnchorHeight}=this.viewState;Math.abs(scrollTop-this.viewState.scrollTop)>1&&(scrollAnchorHeight=-1),this.viewState.scrollAnchorHeight=-1;try{for(let i=0;;i++){if(scrollAnchorHeight<0)if(isScrolledToBottom(sDOM))scrollAnchorPos=-1,scrollAnchorHeight=this.viewState.heightMap.height;else{let block=this.viewState.scrollAnchorAt(scrollTop);scrollAnchorPos=block.from,scrollAnchorHeight=block.top}this.updateState=1;let changed=this.viewState.measure(this);if(!changed&&!this.measureRequests.length&&null==this.viewState.scrollTarget)break;if(i>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let measuring=[];4&changed||([this.measureRequests,measuring]=[measuring,this.measureRequests]);let measured=measuring.map((m=>{try{return m.read(this)}catch(e){return logException(this.state,e),BadMeasure}})),update=ViewUpdate.create(this,this.state,[]),redrawn=!1;update.flags|=changed,updated?updated.flags|=changed:updated=update,this.updateState=2,update.empty||(this.updatePlugins(update),this.inputState.update(update),this.updateAttrs(),redrawn=this.docView.update(update),redrawn&&this.docViewUpdate());for(let i=0;i1||diff<-1){scrollTop+=diff,sDOM.scrollTop=scrollTop/this.scaleY,scrollAnchorHeight=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(updated&&!updated.empty)for(let listener of this.state.facet(updateListener))listener(updated)}get themeClasses(){return baseThemeID+" "+(this.state.facet(darkTheme)?baseDarkID:baseLightID)+" "+this.state.facet(theme)}updateAttrs(){let editorAttrs=attrsFromFacet(this,editorAttributes,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),contentAttrs={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(editable)?"true":"false",class:"cm-content",style:"".concat(browser.tabSize,": ").concat(this.state.tabSize),role:"textbox","aria-multiline":"true"};this.state.readOnly&&(contentAttrs["aria-readonly"]="true"),attrsFromFacet(this,contentAttributes,contentAttrs);let changed=this.observer.ignore((()=>{let changedContent=updateAttrs(this.contentDOM,this.contentAttrs,contentAttrs),changedEditor=updateAttrs(this.dom,this.editorAttrs,editorAttrs);return changedContent||changedEditor}));return this.editorAttrs=editorAttrs,this.contentAttrs=contentAttrs,changed}showAnnouncements(trs){let first=!0;for(let tr of trs)for(let effect of tr.effects)if(effect.is(EditorView.announce)){first&&(this.announceDOM.textContent=""),first=!1,this.announceDOM.appendChild(document.createElement("div")).textContent=effect.value}}mountStyles(){this.styleModules=this.state.facet(styleModule);let nonce=this.state.facet(EditorView.cspNonce);StyleModule.mount(this.root,this.styleModules.concat(baseTheme$1$3).reverse(),nonce?{nonce:nonce}:void 0)}readMeasured(){if(2==this.updateState)throw new Error("Reading the editor layout isn't allowed during an update");0==this.updateState&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(request){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame((()=>this.measure()))),request){if(this.measureRequests.indexOf(request)>-1)return;if(null!=request.key)for(let i=0;ip.spec==plugin))||null),known&&known.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(height){return this.readMeasured(),this.viewState.elementAtHeight(height)}lineBlockAtHeight(height){return this.readMeasured(),this.viewState.lineBlockAtHeight(height)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(pos){return this.viewState.lineBlockAt(pos)}get contentHeight(){return this.viewState.contentHeight}moveByChar(start,forward,by){return skipAtoms(this,start,moveByChar(this,start,forward,by))}moveByGroup(start,forward){return skipAtoms(this,start,moveByChar(this,start,forward,(initial=>function(view,pos,start){let categorize=view.state.charCategorizer(pos),cat=categorize(start);return next=>{let nextCat=categorize(next);return cat==CharCategory.Space&&(cat=nextCat),cat==nextCat}}(this,start.head,initial))))}visualLineSide(line,end){let order=this.bidiSpans(line),dir=this.textDirectionAt(line.from),span=order[end?order.length-1:0];return EditorSelection.cursor(span.side(end,dir)+line.from,span.forward(!end,dir)?1:-1)}moveToLineBoundary(start,forward){return function(view,start,forward,includeWrap){let line=blockAt(view,start.head),coords=includeWrap&&line.type==BlockType.Text&&(view.lineWrapping||line.widgetLineBreaks)?view.coordsAtPos(start.assoc<0&&start.head>line.from?start.head-1:start.head):null;if(coords){let editorRect=view.dom.getBoundingClientRect(),direction=view.textDirectionAt(line.from),pos=view.posAtCoords({x:forward==(direction==Direction.LTR)?editorRect.right-1:editorRect.left+1,y:(coords.top+coords.bottom)/2});if(null!=pos)return EditorSelection.cursor(pos,forward?-1:1)}return EditorSelection.cursor(forward?line.to:line.from,forward?-1:1)}(this,start,forward,!(arguments.length>2&&void 0!==arguments[2])||arguments[2])}moveVertically(start,forward,distance){return skipAtoms(this,start,function(view,start,forward,distance){let startPos=start.head,dir=forward?1:-1;if(startPos==(forward?view.state.doc.length:0))return EditorSelection.cursor(startPos,start.assoc);let startY,goal=start.goalColumn,rect=view.contentDOM.getBoundingClientRect(),startCoords=view.coordsAtPos(startPos,start.assoc||-1),docTop=view.documentTop;if(startCoords)null==goal&&(goal=startCoords.left-rect.left),startY=dir<0?startCoords.top:startCoords.bottom;else{let line=view.viewState.lineBlockAt(startPos);null==goal&&(goal=Math.min(rect.right-rect.left,view.defaultCharacterWidth*(startPos-line.from))),startY=(dir<0?line.top:line.bottom)+docTop}let resolvedGoal=rect.left+goal,dist=null!=distance?distance:view.viewState.heightOracle.textHeight>>1;for(let extra=0;;extra+=10){let curY=startY+(dist+extra)*dir,pos=posAtCoords(view,{x:resolvedGoal,y:curY},!1,dir);if(curYrect.bottom||(dir<0?posstartPos)){let charRect=view.docView.coordsForChar(pos),assoc=!charRect||curY1&&void 0!==arguments[1]?arguments[1]:0;return this.docView.posFromDOM(node,offset)}posAtCoords(coords){let precise=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.readMeasured(),posAtCoords(this,coords,precise)}coordsAtPos(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;this.readMeasured();let rect=this.docView.coordsAt(pos,side);if(!rect||rect.left==rect.right)return rect;let line=this.state.doc.lineAt(pos),order=this.bidiSpans(line);return flattenRect(rect,order[BidiSpan.find(order,pos-line.from,-1,side)].dir==Direction.LTR==side>0)}coordsForChar(pos){return this.readMeasured(),this.docView.coordsForChar(pos)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(pos){return!this.state.facet(perLineTextDirection)||posthis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(pos))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(line){if(line.length>MaxBidiLine)return trivialOrder(line.length);let isolates,dir=this.textDirectionAt(line.from);for(let entry of this.bidiCache)if(entry.from==line.from&&entry.dir==dir&&(entry.fresh||isolatesEq(entry.isolates,isolates=getIsolatedRanges(this,line))))return entry.order;isolates||(isolates=getIsolatedRanges(this,line));let order=function(line,direction,isolates){if(!line)return[new BidiSpan(0,0,direction==RTL?1:0)];if(direction==LTR&&!isolates.length&&!BidiRE.test(line))return trivialOrder(line.length);if(isolates.length)for(;line.length>types.length;)types[types.length]=256;let order=[],level=direction==LTR?0:1;return computeSectionOrder(line,level,level,isolates,0,line.length,order),order}(line.text,dir,isolates);return this.bidiCache.push(new CachedOrder(line.from,line.to,dir,isolates,!0,order)),order}get hasFocus(){var _a;return(this.dom.ownerDocument.hasFocus()||browser.safari&&(null===(_a=this.inputState)||void 0===_a?void 0:_a.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore((()=>{focusPreventScroll(this.contentDOM),this.docView.updateSelection()}))}setRoot(root){this._root!=root&&(this._root=root,this.observer.setWindow((9==root.nodeType?root:root.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let plugin of this.plugins)plugin.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(pos){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return scrollIntoView$1.of(new ScrollTarget("number"==typeof pos?EditorSelection.cursor(pos):pos,options.y,options.x,options.yMargin,options.xMargin))}scrollSnapshot(){let{scrollTop:scrollTop,scrollLeft:scrollLeft}=this.scrollDOM,ref=this.viewState.scrollAnchorAt(scrollTop);return scrollIntoView$1.of(new ScrollTarget(EditorSelection.cursor(ref.from),"start","start",ref.top-scrollTop,scrollLeft,!0))}setTabFocusMode(to){null==to?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:"boolean"==typeof to?this.inputState.tabFocusMode=to?0:-1:0!=this.inputState.tabFocusMode&&(this.inputState.tabFocusMode=Date.now()+to)}static domEventHandlers(handlers){return ViewPlugin.define((()=>({})),{eventHandlers:handlers})}static domEventObservers(observers){return ViewPlugin.define((()=>({})),{eventObservers:observers})}static theme(spec,options){let prefix=StyleModule.newName(),result=[theme.of(prefix),styleModule.of(buildTheme(".".concat(prefix),spec))];return options&&options.dark&&result.push(darkTheme.of(!0)),result}static baseTheme(spec){return Prec.lowest(styleModule.of(buildTheme("."+baseThemeID,spec,lightDarkIDs)))}static findFromDOM(dom){var _a;let content=dom.querySelector(".cm-content"),cView=content&&ContentView.get(content)||ContentView.get(dom);return(null===(_a=null==cView?void 0:cView.rootView)||void 0===_a?void 0:_a.view)||null}}EditorView.styleModule=styleModule,EditorView.inputHandler=inputHandler$1,EditorView.scrollHandler=scrollHandler,EditorView.focusChangeEffect=focusChangeEffect,EditorView.perLineTextDirection=perLineTextDirection,EditorView.exceptionSink=exceptionSink,EditorView.updateListener=updateListener,EditorView.editable=editable,EditorView.mouseSelectionStyle=mouseSelectionStyle,EditorView.dragMovesSelection=dragMovesSelection$1,EditorView.clickAddsSelectionRange=clickAddsSelectionRange,EditorView.decorations=decorations,EditorView.outerDecorations=outerDecorations,EditorView.atomicRanges=atomicRanges,EditorView.bidiIsolatedRanges=bidiIsolatedRanges,EditorView.scrollMargins=scrollMargins,EditorView.darkTheme=darkTheme,EditorView.cspNonce=Facet.define({combine:values=>values.length?values[0]:""}),EditorView.contentAttributes=contentAttributes,EditorView.editorAttributes=editorAttributes,EditorView.lineWrapping=EditorView.contentAttributes.of({class:"cm-lineWrapping"}),EditorView.announce=StateEffect.define();const MaxBidiLine=4096,BadMeasure={};class CachedOrder{constructor(from,to,dir,isolates,fresh,order){this.from=from,this.to=to,this.dir=dir,this.isolates=isolates,this.fresh=fresh,this.order=order}static update(cache,changes){if(changes.empty&&!cache.some((c=>c.fresh)))return cache;let result=[],lastDir=cache.length?cache[cache.length-1].dir:Direction.LTR;for(let i=Math.max(0,cache.length-10);i=0;i--){let source=sources[i],value="function"==typeof source?source(view):source;value&&combineAttrs(value,base)}return base}const currentPlatform=browser.mac?"mac":browser.windows?"win":browser.linux?"linux":"key";function normalizeKeyName(name,platform){const parts=name.split(/-(?!$)/);let alt,ctrl,shift,meta,result=parts[parts.length-1];"Space"==result&&(result=" ");for(let i=0;irunHandlers(getKeymap(view.state),event,view,"editor")})),keymap=Facet.define({enables:handleKeyEvents}),Keymaps=new WeakMap;function getKeymap(state){let bindings=state.facet(keymap),map=Keymaps.get(bindings);return map||Keymaps.set(bindings,map=function(bindings){let platform=arguments.length>1&&void 0!==arguments[1]?arguments[1]:currentPlatform,bound=Object.create(null),isPrefix=Object.create(null),checkPrefix=(name,is)=>{let current=isPrefix[name];if(null==current)isPrefix[name]=is;else if(current!=is)throw new Error("Key binding "+name+" is used both as a regular binding and as a multi-stroke prefix")},add=(scope,key,command,preventDefault,stopPropagation)=>{var _a,_b;let scopeObj=bound[scope]||(bound[scope]=Object.create(null)),parts=key.split(/ (?!$)/).map((k=>normalizeKeyName(k,platform)));for(let i=1;i{let ourObj=storedPrefix={view:view,prefix:prefix,scope:scope};return setTimeout((()=>{storedPrefix==ourObj&&(storedPrefix=null)}),4e3),!0}]})}let full=parts.join(" ");checkPrefix(full,!1);let binding=scopeObj[full]||(scopeObj[full]={preventDefault:!1,stopPropagation:!1,run:(null===(_b=null===(_a=scopeObj._any)||void 0===_a?void 0:_a.run)||void 0===_b?void 0:_b.slice())||[]});command&&binding.run.push(command),preventDefault&&(binding.preventDefault=!0),stopPropagation&&(binding.stopPropagation=!0)};for(let b of bindings){let scopes=b.scope?b.scope.split(" "):["editor"];if(b.any)for(let scope of scopes){let scopeObj=bound[scope]||(bound[scope]=Object.create(null));scopeObj._any||(scopeObj._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:any}=b;for(let key in scopeObj)scopeObj[key].run.push((view=>any(view,currentKeyEvent)))}let name=b[platform]||b.key;if(name)for(let scope of scopes)add(scope,name,b.run,b.preventDefault,b.stopPropagation),b.shift&&add(scope,"Shift-"+name,b.shift,b.preventDefault,b.stopPropagation)}return bound}(bindings.reduce(((a,b)=>a.concat(b)),[]))),map}let storedPrefix=null;let currentKeyEvent=null;function runHandlers(map,event,view,scope){currentKeyEvent=event;let name=function(event){var name=!(mac&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie$1&&event.shiftKey&&event.key&&1==event.key.length||"Unidentified"==event.key)&&event.key||(event.shiftKey?shift:base)[event.keyCode]||event.key||"Unidentified";return"Esc"==name&&(name="Escape"),"Del"==name&&(name="Delete"),"Left"==name&&(name="ArrowLeft"),"Up"==name&&(name="ArrowUp"),"Right"==name&&(name="ArrowRight"),"Down"==name&&(name="ArrowDown"),name}(event),isChar=codePointSize(codePointAt(name,0))==name.length&&" "!=name,prefix="",handled=!1,prevented=!1,stopPropagation=!1;storedPrefix&&storedPrefix.view==view&&storedPrefix.scope==scope&&(prefix=storedPrefix.prefix+" ",modifierCodes.indexOf(event.keyCode)<0&&(prevented=!0,storedPrefix=null));let baseName,shiftName,ran=new Set,runFor=binding=>{if(binding){for(let cmd of binding.run)if(!ran.has(cmd)&&(ran.add(cmd),cmd(view)))return binding.stopPropagation&&(stopPropagation=!0),!0;binding.preventDefault&&(binding.stopPropagation&&(stopPropagation=!0),prevented=!0)}return!1},scopeObj=map[scope];return scopeObj&&(runFor(scopeObj[prefix+modifiers(name,event,!isChar)])?handled=!0:isChar&&(event.altKey||event.metaKey||event.ctrlKey)&&!(browser.windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name?(runFor(scopeObj[prefix+modifiers(baseName,event,!0)])||event.shiftKey&&(shiftName=shift[event.keyCode])!=name&&shiftName!=baseName&&runFor(scopeObj[prefix+modifiers(shiftName,event,!1)]))&&(handled=!0):isChar&&event.shiftKey&&runFor(scopeObj[prefix+modifiers(name,event,!0)])&&(handled=!0),!handled&&runFor(scopeObj._any)&&(handled=!0)),prevented&&(handled=!0),handled&&stopPropagation&&event.stopPropagation(),currentKeyEvent=null,handled}class RectangleMarker{constructor(className,left,top,width,height){this.className=className,this.left=left,this.top=top,this.width=width,this.height=height}draw(){let elt=document.createElement("div");return elt.className=this.className,this.adjust(elt),elt}update(elt,prev){return prev.className==this.className&&(this.adjust(elt),!0)}adjust(elt){elt.style.left=this.left+"px",elt.style.top=this.top+"px",null!=this.width&&(elt.style.width=this.width+"px"),elt.style.height=this.height+"px"}eq(p){return this.left==p.left&&this.top==p.top&&this.width==p.width&&this.height==p.height&&this.className==p.className}static forRange(view,className,range){if(range.empty){let pos=view.coordsAtPos(range.head,range.assoc||1);if(!pos)return[];let base=getBase(view);return[new RectangleMarker(className,pos.left-base.left,pos.top-base.top,null,pos.bottom-pos.top)]}return function(view,className,range){if(range.to<=view.viewport.from||range.from>=view.viewport.to)return[];let from=Math.max(range.from,view.viewport.from),to=Math.min(range.to,view.viewport.to),ltr=view.textDirection==Direction.LTR,content=view.contentDOM,contentRect=content.getBoundingClientRect(),base=getBase(view),lineElt=content.querySelector(".cm-line"),lineStyle=lineElt&&window.getComputedStyle(lineElt),leftSide=contentRect.left+(lineStyle?parseInt(lineStyle.paddingLeft)+Math.min(0,parseInt(lineStyle.textIndent)):0),rightSide=contentRect.right-(lineStyle?parseInt(lineStyle.paddingRight):0),startBlock=blockAt(view,from),endBlock=blockAt(view,to),visualStart=startBlock.type==BlockType.Text?startBlock:null,visualEnd=endBlock.type==BlockType.Text?endBlock:null;visualStart&&(view.lineWrapping||startBlock.widgetLineBreaks)&&(visualStart=wrappedLine(view,from,1,visualStart));visualEnd&&(view.lineWrapping||endBlock.widgetLineBreaks)&&(visualEnd=wrappedLine(view,to,-1,visualEnd));if(visualStart&&visualEnd&&visualStart.from==visualEnd.from&&visualStart.to==visualEnd.to)return pieces(drawForLine(range.from,range.to,visualStart));{let top=visualStart?drawForLine(range.from,null,visualStart):drawForWidget(startBlock,!1),bottom=visualEnd?drawForLine(null,range.to,visualEnd):drawForWidget(endBlock,!0),between=[];return(visualStart||startBlock).to<(visualEnd||endBlock).from-(visualStart&&visualEnd?1:0)||startBlock.widgetLineBreaks>1&&top.bottom+view.defaultLineHeight/2start&&r.from=endPos)break;spanTo>pos&&addSpan(Math.max(spanFrom,pos),null==from&&spanFrom<=start,Math.min(spanTo,endPos),null==to&&spanTo>=end,span.dir)}if(pos=docLine.to+1,pos>=endPos)break}return 0==horizontal.length&&addSpan(start,null==from,end,null==to,view.textDirection),{top:top,bottom:bottom,horizontal:horizontal}}function drawForWidget(block,top){let y=contentRect.top+(top?block.top:block.bottom);return{top:y,bottom:y,horizontal:[]}}}(view,className,range)}}function getBase(view){let rect=view.scrollDOM.getBoundingClientRect();return{left:(view.textDirection==Direction.LTR?rect.left:rect.right-view.scrollDOM.clientWidth*view.scaleX)-view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-view.scrollDOM.scrollTop*view.scaleY}}function wrappedLine(view,pos,side,inside){let coords=view.coordsAtPos(pos,2*side);if(!coords)return inside;let editorRect=view.dom.getBoundingClientRect(),y=(coords.top+coords.bottom)/2,left=view.posAtCoords({x:editorRect.left+1,y:y}),right=view.posAtCoords({x:editorRect.right-1,y:y});return null==left||null==right?inside:{from:Math.max(inside.from,Math.min(left,right)),to:Math.min(inside.to,Math.max(left,right))}}class LayerView{constructor(view,layer){this.view=view,this.layer=layer,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=view.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),layer.above&&this.dom.classList.add("cm-layer-above"),layer.class&&this.dom.classList.add(layer.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(view.state),view.requestMeasure(this.measureReq),layer.mount&&layer.mount(this.dom,view)}update(update){update.startState.facet(layerOrder)!=update.state.facet(layerOrder)&&this.setOrder(update.state),(this.layer.update(update,this.dom)||update.geometryChanged)&&(this.scale(),update.view.requestMeasure(this.measureReq))}docViewUpdate(view){!1!==this.layer.updateOnDocViewUpdate&&view.requestMeasure(this.measureReq)}setOrder(state){let pos=0,order=state.facet(layerOrder);for(;pos{return a=p,b=this.drawn[i],!(a.constructor==b.constructor&&a.eq(b));var a,b}))){let old=this.dom.firstChild,oldI=0;for(let marker of markers)marker.update&&old&&marker.constructor&&this.drawn[oldI].constructor&&marker.update(old,this.drawn[oldI])?(old=old.nextSibling,oldI++):this.dom.insertBefore(marker.draw(),old);for(;old;){let next=old.nextSibling;old.remove(),old=next}this.drawn=markers}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const layerOrder=Facet.define();function layer(config){return[ViewPlugin.define((v=>new LayerView(v,config))),layerOrder.of(config)]}const CanHidePrimary=!browser.ios,selectionConfig=Facet.define({combine:configs=>combineConfig(configs,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(a,b)=>Math.min(a,b),drawRangeCursor:(a,b)=>a||b})});function drawSelection(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[selectionConfig.of(config),cursorLayer,selectionLayer,hideNativeSelection,nativeSelectionHidden.of(!0)]}function configChanged(update){return update.startState.facet(selectionConfig)!=update.state.facet(selectionConfig)}const cursorLayer=layer({above:!0,markers(view){let{state:state}=view,conf=state.facet(selectionConfig),cursors=[];for(let r of state.selection.ranges){let prim=r==state.selection.main;if(r.empty?!prim||CanHidePrimary:conf.drawRangeCursor){let className=prim?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",cursor=r.empty?r:EditorSelection.cursor(r.head,r.head>r.anchor?-1:1);for(let piece of RectangleMarker.forRange(view,className,cursor))cursors.push(piece)}}return cursors},update(update,dom){update.transactions.some((tr=>tr.selection))&&(dom.style.animationName="cm-blink"==dom.style.animationName?"cm-blink2":"cm-blink");let confChange=configChanged(update);return confChange&&setBlinkRate(update.state,dom),update.docChanged||update.selectionSet||confChange},mount(dom,view){setBlinkRate(view.state,dom)},class:"cm-cursorLayer"});function setBlinkRate(state,dom){dom.style.animationDuration=state.facet(selectionConfig).cursorBlinkRate+"ms"}const selectionLayer=layer({above:!1,markers:view=>view.state.selection.ranges.map((r=>r.empty?[]:RectangleMarker.forRange(view,"cm-selectionBackground",r))).reduce(((a,b)=>a.concat(b))),update:(update,dom)=>update.docChanged||update.selectionSet||update.viewportChanged||configChanged(update),class:"cm-selectionLayer"}),themeSpec={".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"}},".cm-content":{"& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}};CanHidePrimary&&(themeSpec[".cm-line"].caretColor=themeSpec[".cm-content"].caretColor="transparent !important");const hideNativeSelection=Prec.highest(EditorView.theme(themeSpec)),setDropCursorPos=StateEffect.define({map:(pos,mapping)=>null==pos?null:mapping.mapPos(pos)}),dropCursorPos=StateField.define({create:()=>null,update:(pos,tr)=>(null!=pos&&(pos=tr.changes.mapPos(pos)),tr.effects.reduce(((pos,e)=>e.is(setDropCursorPos)?e.value:pos),pos))}),drawDropCursor=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(update){var _a;let cursorPos=update.state.field(dropCursorPos);null==cursorPos?null!=this.cursor&&(null===(_a=this.cursor)||void 0===_a||_a.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(update.startState.field(dropCursorPos)!=cursorPos||update.docChanged||update.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:view}=this,pos=view.state.field(dropCursorPos),rect=null!=pos&&view.coordsAtPos(pos);if(!rect)return null;let outer=view.scrollDOM.getBoundingClientRect();return{left:rect.left-outer.left+view.scrollDOM.scrollLeft*view.scaleX,top:rect.top-outer.top+view.scrollDOM.scrollTop*view.scaleY,height:rect.bottom-rect.top}}drawCursor(pos){if(this.cursor){let{scaleX:scaleX,scaleY:scaleY}=this.view;pos?(this.cursor.style.left=pos.left/scaleX+"px",this.cursor.style.top=pos.top/scaleY+"px",this.cursor.style.height=pos.height/scaleY+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(pos){this.view.state.field(dropCursorPos)!=pos&&this.view.dispatch({effects:setDropCursorPos.of(pos)})}},{eventObservers:{dragover(event){this.setDropPos(this.view.posAtCoords({x:event.clientX,y:event.clientY}))},dragleave(event){event.target!=this.view.contentDOM&&this.view.contentDOM.contains(event.relatedTarget)||this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function iterMatches(doc,re,from,to,f){re.lastIndex=0;for(let m,cursor=doc.iterRange(from,to),pos=from;!cursor.next().done;pos+=cursor.value.length)if(!cursor.lineBreak)for(;m=re.exec(cursor.value);)f(pos+m.index,m)}class MatchDecorator{constructor(config){const{regexp:regexp,decoration:decoration,decorate:decorate,boundary:boundary,maxLength:maxLength=1e3}=config;if(!regexp.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=regexp,decorate)this.addMatch=(match,view,from,add)=>decorate(add,from,from+match[0].length,match,view);else if("function"==typeof decoration)this.addMatch=(match,view,from,add)=>{let deco=decoration(match,view,from);deco&&add(from,from+match[0].length,deco)};else{if(!decoration)throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.addMatch=(match,_view,from,add)=>add(from,from+match[0].length,decoration)}this.boundary=boundary,this.maxLength=maxLength}createDeco(view){let build=new RangeSetBuilder,add=build.add.bind(build);for(let{from:from,to:to}of function(view,maxLength){let visible=view.visibleRanges;if(1==visible.length&&visible[0].from==view.viewport.from&&visible[0].to==view.viewport.to)return visible;let result=[];for(let{from:from,to:to}of visible)from=Math.max(view.state.doc.lineAt(from).from,from-maxLength),to=Math.min(view.state.doc.lineAt(to).to,to+maxLength),result.length&&result[result.length-1].to>=from?result[result.length-1].to=to:result.push({from:from,to:to});return result}(view,this.maxLength))iterMatches(view.state.doc,this.regexp,from,to,((from,m)=>this.addMatch(m,view,from,add)));return build.finish()}updateDeco(update,deco){let changeFrom=1e9,changeTo=-1;return update.docChanged&&update.changes.iterChanges(((_f,_t,from,to)=>{to>update.view.viewport.from&&from1e3?this.createDeco(update.view):changeTo>-1?this.updateRange(update.view,deco.map(update.changes),changeFrom,changeTo):deco}updateRange(view,deco,updateFrom,updateTo){for(let r of view.visibleRanges){let from=Math.max(r.from,updateFrom),to=Math.min(r.to,updateTo);if(to>from){let fromLine=view.state.doc.lineAt(from),toLine=fromLine.tofromLine.from;from--)if(this.boundary.test(fromLine.text[from-1-fromLine.from])){start=from;break}for(;toranges.push(deco.range(from,to));if(fromLine==toLine)for(this.regexp.lastIndex=start-fromLine.from;(m=this.regexp.exec(fromLine.text))&&m.indexthis.addMatch(m,view,from,add)));deco=deco.update({filterFrom:start,filterTo:end,filter:(from,to)=>fromend,add:ranges})}}return deco}}const UnicodeRegexpSupport=null!=/x/.unicode?"gu":"g",Specials=new RegExp("[\0-\b\n--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\ufeff-]",UnicodeRegexpSupport),Names={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let _supportsTabSize=null;const specialCharConfig=Facet.define({combine(configs){let config=combineConfig(configs,{render:null,specialChars:Specials,addSpecialChars:null});return(config.replaceTabs=!function(){var _a;if(null==_supportsTabSize&&"undefined"!=typeof document&&document.body){let styles=document.body.style;_supportsTabSize=null!=(null!==(_a=styles.tabSize)&&void 0!==_a?_a:styles.MozTabSize)}return _supportsTabSize||!1}())&&(config.specialChars=new RegExp("\t|"+config.specialChars.source,UnicodeRegexpSupport)),config.addSpecialChars&&(config.specialChars=new RegExp(config.specialChars.source+"|"+config.addSpecialChars.source,UnicodeRegexpSupport)),config}});function highlightSpecialChars(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[specialCharConfig.of(config),specialCharPlugin()]}let _plugin=null;function specialCharPlugin(){return _plugin||(_plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=Decoration.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(view.state.facet(specialCharConfig)),this.decorations=this.decorator.createDeco(view)}makeDecorator(conf){return new MatchDecorator({regexp:conf.specialChars,decoration:(m,view,pos)=>{let{doc:doc}=view.state,code=codePointAt(m[0],0);if(9==code){let line=doc.lineAt(pos),size=view.state.tabSize,col=countColumn(line.text,size,pos-line.from);return Decoration.replace({widget:new TabWidget((size-col%size)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[code]||(this.decorationCache[code]=Decoration.replace({widget:new SpecialCharWidget(conf,code)}))},boundary:conf.replaceTabs?void 0:/[^]/})}update(update){let conf=update.state.facet(specialCharConfig);update.startState.facet(specialCharConfig)!=conf?(this.decorator=this.makeDecorator(conf),this.decorations=this.decorator.createDeco(update.view)):this.decorations=this.decorator.updateDeco(update,this.decorations)}},{decorations:v=>v.decorations}))}class SpecialCharWidget extends WidgetType{constructor(options,code){super(),this.options=options,this.code=code}eq(other){return other.code==this.code}toDOM(view){let ph=function(code){return code>=32?"•":10==code?"␤":String.fromCharCode(9216+code)}(this.code),desc=view.state.phrase("Control character")+" "+(Names[this.code]||"0x"+this.code.toString(16)),custom=this.options.render&&this.options.render(this.code,desc,ph);if(custom)return custom;let span=document.createElement("span");return span.textContent=ph,span.title=desc,span.setAttribute("aria-label",desc),span.className="cm-specialChar",span}ignoreEvent(){return!1}}class TabWidget extends WidgetType{constructor(width){super(),this.width=width}eq(other){return other.width==this.width}toDOM(){let span=document.createElement("span");return span.textContent="\t",span.className="cm-tab",span.style.width=this.width+"px",span}ignoreEvent(){return!1}}const lineDeco=Decoration.line({class:"cm-activeLine"}),activeLineHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.docChanged||update.selectionSet)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let lastLineStart=-1,deco=[];for(let r of view.state.selection.ranges){let line=view.lineBlockAt(r.head);line.from>lastLineStart&&(deco.push(lineDeco.range(line.from)),lastLineStart=line.from)}return Decoration.set(deco)}},{decorations:v=>v.decorations});function getPos(view,event){let offset=view.posAtCoords({x:event.clientX,y:event.clientY},!1),line=view.state.doc.lineAt(offset),off=offset-line.from,col=off>2e3?-1:off==line.length?function(view,x){let ref=view.coordsAtPos(view.viewport.from);return ref?Math.round(Math.abs((ref.left-x)/view.defaultCharacterWidth)):-1}(view,event.clientX):countColumn(line.text,view.state.tabSize,offset-line.from);return{line:line.number,col:col,off:off}}function rectangleSelectionStyle(view,event){let start=getPos(view,event),startSel=view.state.selection;return start?{update(update){if(update.docChanged){let newStart=update.changes.mapPos(update.startState.doc.line(start.line).from),newLine=update.state.doc.lineAt(newStart);start={line:newLine.number,col:start.col,off:Math.min(start.off,newLine.length)},startSel=startSel.map(update.changes)}},get(event,_extend,multiple){let cur=getPos(view,event);if(!cur)return startSel;let ranges=function(state,a,b){let startLine=Math.min(a.line,b.line),endLine=Math.max(a.line,b.line),ranges=[];if(a.off>2e3||b.off>2e3||a.col<0||b.col<0){let startOff=Math.min(a.off,b.off),endOff=Math.max(a.off,b.off);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i);line.length<=endOff&&ranges.push(EditorSelection.range(line.from+startOff,line.to+endOff))}}else{let startCol=Math.min(a.col,b.col),endCol=Math.max(a.col,b.col);for(let i=startLine;i<=endLine;i++){let line=state.doc.line(i),start=findColumn(line.text,startCol,state.tabSize,!0);if(start<0)ranges.push(EditorSelection.cursor(line.to));else{let end=findColumn(line.text,endCol,state.tabSize);ranges.push(EditorSelection.range(line.from+start,line.from+end))}}}return ranges}(view.state,start,cur);return ranges.length?multiple?EditorSelection.create(ranges.concat(startSel.ranges)):EditorSelection.create(ranges):startSel}}:null}function rectangularSelection(options){let filter=(null==options?void 0:options.eventFilter)||(e=>e.altKey&&0==e.button);return EditorView.mouseSelectionStyle.of(((view,event)=>filter(event)?rectangleSelectionStyle(view,event):null))}const keys={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},showCrosshair={style:"cursor: crosshair"};function crosshairCursor(){let options=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},[code,getter]=keys[options.key||"Alt"],plugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.isDown=!1}set(isDown){this.isDown!=isDown&&(this.isDown=isDown,this.view.update([]))}},{eventObservers:{keydown(e){this.set(e.keyCode==code||getter(e))},keyup(e){e.keyCode!=code&&getter(e)||this.set(!1)},mousemove(e){this.set(getter(e))}}});return[plugin,EditorView.contentAttributes.of((view=>{var _a;return(null===(_a=view.plugin(plugin))||void 0===_a?void 0:_a.isDown)?showCrosshair:null}))]}class TooltipViewManager{constructor(view,facet,createTooltipView,removeTooltipView){this.facet=facet,this.createTooltipView=createTooltipView,this.removeTooltipView=removeTooltipView,this.input=view.state.facet(facet),this.tooltips=this.input.filter((t=>t));let prev=null;this.tooltipViews=this.tooltips.map((t=>prev=createTooltipView(t,prev)))}update(update,above){var _a;let input=update.state.facet(this.facet),tooltips=input.filter((x=>x));if(input===this.input){for(let t of this.tooltipViews)t.update&&t.update(update);return!1}let tooltipViews=[],newAbove=above?[]:null;for(let i=0;iabove[i]=val)),above.length=newAbove.length),this.input=input,this.tooltips=tooltips,this.tooltipViews=tooltipViews,!0}}function windowSpace(view){let{win:win}=view;return{top:0,left:0,bottom:win.innerHeight,right:win.innerWidth}}const tooltipConfig=Facet.define({combine:values=>{var _a,_b,_c;return{position:browser.ios?"absolute":(null===(_a=values.find((conf=>conf.position)))||void 0===_a?void 0:_a.position)||"fixed",parent:(null===(_b=values.find((conf=>conf.parent)))||void 0===_b?void 0:_b.parent)||null,tooltipSpace:(null===(_c=values.find((conf=>conf.tooltipSpace)))||void 0===_c?void 0:_c.tooltipSpace)||windowSpace}}}),knownHeight=new WeakMap,tooltipPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let config=view.state.facet(tooltipConfig);this.position=config.position,this.parent=config.parent,this.classes=view.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver="function"==typeof ResizeObserver?new ResizeObserver((()=>this.measureSoon())):null,this.manager=new TooltipViewManager(view,showTooltip,((t,p)=>this.createTooltip(t,p)),(t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()})),this.above=this.manager.tooltips.map((t=>!!t.above)),this.intersectionObserver="function"==typeof IntersectionObserver?new IntersectionObserver((entries=>{Date.now()>this.lastTransaction-50&&entries.length>0&&entries[entries.length-1].intersectionRatio<1&&this.measureSoon()}),{threshold:[1]}):null,this.observeIntersection(),view.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let tooltip of this.manager.tooltipViews)this.intersectionObserver.observe(tooltip.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout((()=>{this.measureTimeout=-1,this.maybeMeasure()}),50))}update(update){update.transactions.length&&(this.lastTransaction=Date.now());let updated=this.manager.update(update,this.above);updated&&this.observeIntersection();let shouldMeasure=updated||update.geometryChanged,newConfig=update.state.facet(tooltipConfig);if(newConfig.position!=this.position&&!this.madeAbsolute){this.position=newConfig.position;for(let t of this.manager.tooltipViews)t.dom.style.position=this.position;shouldMeasure=!0}if(newConfig.parent!=this.parent){this.parent&&this.container.remove(),this.parent=newConfig.parent,this.createContainer();for(let t of this.manager.tooltipViews)this.container.appendChild(t.dom);shouldMeasure=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);shouldMeasure&&this.maybeMeasure()}createTooltip(tooltip,prev){let tooltipView=tooltip.create(this.view),before=prev?prev.dom:null;if(tooltipView.dom.classList.add("cm-tooltip"),tooltip.arrow&&!tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let arrow=document.createElement("div");arrow.className="cm-tooltip-arrow",tooltipView.dom.appendChild(arrow)}return tooltipView.dom.style.position=this.position,tooltipView.dom.style.top="-10000px",tooltipView.dom.style.left="0px",this.container.insertBefore(tooltipView.dom,before),tooltipView.mount&&tooltipView.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(tooltipView.dom),tooltipView}destroy(){var _a,_b,_c;this.view.win.removeEventListener("resize",this.measureSoon);for(let tooltipView of this.manager.tooltipViews)tooltipView.dom.remove(),null===(_a=tooltipView.destroy)||void 0===_a||_a.call(tooltipView);this.parent&&this.container.remove(),null===(_b=this.resizeObserver)||void 0===_b||_b.disconnect(),null===(_c=this.intersectionObserver)||void 0===_c||_c.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let editor=this.view.dom.getBoundingClientRect(),scaleX=1,scaleY=1,makeAbsolute=!1;if("fixed"==this.position&&this.manager.tooltipViews.length){let{dom:dom}=this.manager.tooltipViews[0];if(browser.gecko)makeAbsolute=dom.offsetParent!=this.container.ownerDocument.body;else if("-10000px"==dom.style.top&&"0px"==dom.style.left){let rect=dom.getBoundingClientRect();makeAbsolute=Math.abs(rect.top+1e4)>1||Math.abs(rect.left)>1}}if(makeAbsolute||"absolute"==this.position)if(this.parent){let rect=this.parent.getBoundingClientRect();rect.width&&rect.height&&(scaleX=rect.width/this.parent.offsetWidth,scaleY=rect.height/this.parent.offsetHeight)}else({scaleX:scaleX,scaleY:scaleY}=this.view.viewState);return{editor:editor,parent:this.parent?this.container.getBoundingClientRect():editor,pos:this.manager.tooltips.map(((t,i)=>{let tv=this.manager.tooltipViews[i];return tv.getCoords?tv.getCoords(t.pos):this.view.coordsAtPos(t.pos)})),size:this.manager.tooltipViews.map((_ref7=>{let{dom:dom}=_ref7;return dom.getBoundingClientRect()})),space:this.view.state.facet(tooltipConfig).tooltipSpace(this.view),scaleX:scaleX,scaleY:scaleY,makeAbsolute:makeAbsolute}}writeMeasure(measured){var _a;if(measured.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t of this.manager.tooltipViews)t.dom.style.position="absolute"}let{editor:editor,space:space,scaleX:scaleX,scaleY:scaleY}=measured,others=[];for(let i=0;i=Math.min(editor.bottom,space.bottom)||pos.rightMath.min(editor.right,space.right)+.1){dom.style.top="-10000px";continue}let arrow=tooltip.arrow?tView.dom.querySelector(".cm-tooltip-arrow"):null,arrowHeight=arrow?7:0,width=size.right-size.left,height=null!==(_a=knownHeight.get(tView))&&void 0!==_a?_a:size.bottom-size.top,offset=tView.offset||noOffset,ltr=this.view.textDirection==Direction.LTR,left=size.width>space.right-space.left?ltr?space.left:space.right-size.width:ltr?Math.min(pos.left-(arrow?14:0)+offset.x,space.right-width):Math.max(space.left,pos.left-width+(arrow?14:0)-offset.x),above=this.above[i];!tooltip.strictSide&&(above?pos.top-(size.bottom-size.top)-offset.yspace.bottom)&&above==space.bottom-pos.bottom>pos.top-space.top&&(above=this.above[i]=!above);let spaceVert=(above?pos.top-space.top:space.bottom-pos.bottom)-arrowHeight;if(spaceVertleft&&r.toptop&&(top=above?r.top-height-2-arrowHeight:r.bottom+arrowHeight+2);if("absolute"==this.position?(dom.style.top=(top-measured.parent.top)/scaleY+"px",dom.style.left=(left-measured.parent.left)/scaleX+"px"):(dom.style.top=top/scaleY+"px",dom.style.left=left/scaleX+"px"),arrow){let arrowLeft=pos.left+(ltr?offset.x:-offset.x)-(left+14-7);arrow.style.left=arrowLeft/scaleX+"px"}!0!==tView.overlap&&others.push({left:left,top:top,right:right,bottom:top+height}),dom.classList.toggle("cm-tooltip-above",above),dom.classList.toggle("cm-tooltip-below",!above),tView.positioned&&tView.positioned(measured.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let tv of this.manager.tooltipViews)tv.dom.style.top="-10000px"}},{eventObservers:{scroll(){this.maybeMeasure()}}}),baseTheme$4=EditorView.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"".concat(7,"px"),width:"".concat(14,"px"),position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"".concat(7,"px solid transparent"),borderRight:"".concat(7,"px solid transparent")},".cm-tooltip-above &":{bottom:"-".concat(7,"px"),"&:before":{borderTop:"".concat(7,"px solid #bbb")},"&:after":{borderTop:"".concat(7,"px solid #f5f5f5"),bottom:"1px"}},".cm-tooltip-below &":{top:"-".concat(7,"px"),"&:before":{borderBottom:"".concat(7,"px solid #bbb")},"&:after":{borderBottom:"".concat(7,"px solid #f5f5f5"),top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),noOffset={x:0,y:0},showTooltip=Facet.define({enables:[tooltipPlugin,baseTheme$4]}),showHoverTooltip=Facet.define({combine:inputs=>inputs.reduce(((a,i)=>a.concat(i)),[])});class HoverTooltipHost{static create(view){return new HoverTooltipHost(view)}constructor(view){this.view=view,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new TooltipViewManager(view,showHoverTooltip,((t,p)=>this.createHostedView(t,p)),(t=>t.dom.remove()))}createHostedView(tooltip,prev){let hostedView=tooltip.create(this.view);return hostedView.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(hostedView.dom,prev?prev.dom.nextSibling:this.dom.firstChild),this.mounted&&hostedView.mount&&hostedView.mount(this.view),hostedView}mount(view){for(let hostedView of this.manager.tooltipViews)hostedView.mount&&hostedView.mount(view);this.mounted=!0}positioned(space){for(let hostedView of this.manager.tooltipViews)hostedView.positioned&&hostedView.positioned(space)}update(update){this.manager.update(update)}destroy(){var _a;for(let t of this.manager.tooltipViews)null===(_a=t.destroy)||void 0===_a||_a.call(t)}passProp(name){let value;for(let view of this.manager.tooltipViews){let given=view[name];if(void 0!==given)if(void 0===value)value=given;else if(value!==given)return}return value}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const showHoverTooltipHost=showTooltip.compute([showHoverTooltip],(state=>{let tooltips=state.facet(showHoverTooltip);return 0===tooltips.length?null:{pos:Math.min(...tooltips.map((t=>t.pos))),end:Math.max(...tooltips.map((t=>{var _a;return null!==(_a=t.end)&&void 0!==_a?_a:t.pos}))),create:HoverTooltipHost.create,above:tooltips[0].above,arrow:tooltips.some((t=>t.arrow))}}));class HoverPlugin{constructor(view,source,field,setHover,hoverTime){this.view=view,this.source=source,this.field=field,this.setHover=setHover,this.hoverTime=hoverTime,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:view.dom,time:0},this.checkHover=this.checkHover.bind(this),view.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),view.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout((()=>this.startHover()),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let hovered=Date.now()-this.lastMove.time;hoveredposCoords.bottom||lastMove.xposCoords.right+view.defaultCharacterWidth)return;let bidi=view.bidiSpans(view.state.doc.lineAt(pos)).find((s=>s.from<=pos&&s.to>=pos)),rtl=bidi&&bidi.dir==Direction.RTL?-1:1;side=lastMove.x{this.pending==pending&&(this.pending=null,!result||Array.isArray(result)&&!result.length||view.dispatch({effects:this.setHover.of(Array.isArray(result)?result:[result])}))}),(e=>logException(view.state,e,"hover tooltip")))}else!open||Array.isArray(open)&&!open.length||view.dispatch({effects:this.setHover.of(Array.isArray(open)?open:[open])})}get tooltip(){let plugin=this.view.plugin(tooltipPlugin),index=plugin?plugin.manager.tooltips.findIndex((t=>t.create==HoverTooltipHost.create)):-1;return index>-1?plugin.manager.tooltipViews[index]:null}mousemove(event){var _a,_b;this.lastMove={x:event.clientX,y:event.clientY,target:event.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:active,tooltip:tooltip}=this;if(active.length&&tooltip&&!function(tooltip,event){let rect=tooltip.getBoundingClientRect();return event.clientX>=rect.left-4&&event.clientX<=rect.right+4&&event.clientY>=rect.top-4&&event.clientY<=rect.bottom+4}(tooltip.dom,event)||this.pending){let{pos:pos}=active[0]||this.pending,end=null!==(_b=null===(_a=active[0])||void 0===_a?void 0:_a.end)&&void 0!==_b?_b:pos;(pos==end?this.view.posAtCoords(this.lastMove)==pos:function(view,from,to,x,y,margin){let rect=view.scrollDOM.getBoundingClientRect(),docBottom=view.documentTop+view.documentPadding.top+view.contentHeight;if(rect.left>x||rect.righty||Math.min(rect.bottom,docBottom)=from&&pos<=to}(this.view,pos,end,event.clientX,event.clientY))||(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(event){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:active}=this;if(active.length){let{tooltip:tooltip}=this;tooltip&&tooltip.dom.contains(event.relatedTarget)?this.watchTooltipLeave(tooltip.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(tooltip){let watch=event=>{tooltip.removeEventListener("mouseleave",watch),this.active.length&&!this.view.dom.contains(event.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};tooltip.addEventListener("mouseleave",watch)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}function getTooltip(view,tooltip){let plugin=view.plugin(tooltipPlugin);if(!plugin)return null;let found=plugin.manager.tooltips.indexOf(tooltip);return found<0?null:plugin.manager.tooltipViews[found]}const closeHoverTooltipEffect=StateEffect.define(),panelConfig=Facet.define({combine(configs){let topContainer,bottomContainer;for(let c of configs)topContainer=topContainer||c.topContainer,bottomContainer=bottomContainer||c.bottomContainer;return{topContainer:topContainer,bottomContainer:bottomContainer}}});function getPanel(view,panel){let plugin=view.plugin(panelPlugin),index=plugin?plugin.specs.indexOf(panel):-1;return index>-1?plugin.panels[index]:null}const panelPlugin=ViewPlugin.fromClass(class{constructor(view){this.input=view.state.facet(showPanel),this.specs=this.input.filter((s=>s)),this.panels=this.specs.map((spec=>spec(view)));let conf=view.state.facet(panelConfig);this.top=new PanelGroup(view,!0,conf.topContainer),this.bottom=new PanelGroup(view,!1,conf.bottomContainer),this.top.sync(this.panels.filter((p=>p.top))),this.bottom.sync(this.panels.filter((p=>!p.top)));for(let p of this.panels)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}update(update){let conf=update.state.facet(panelConfig);this.top.container!=conf.topContainer&&(this.top.sync([]),this.top=new PanelGroup(update.view,!0,conf.topContainer)),this.bottom.container!=conf.bottomContainer&&(this.bottom.sync([]),this.bottom=new PanelGroup(update.view,!1,conf.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let input=update.state.facet(showPanel);if(input!=this.input){let specs=input.filter((x=>x)),panels=[],top=[],bottom=[],mount=[];for(let spec of specs){let panel,known=this.specs.indexOf(spec);known<0?(panel=spec(update.view),mount.push(panel)):(panel=this.panels[known],panel.update&&panel.update(update)),panels.push(panel),(panel.top?top:bottom).push(panel)}this.specs=specs,this.panels=panels,this.top.sync(top),this.bottom.sync(bottom);for(let p of mount)p.dom.classList.add("cm-panel"),p.mount&&p.mount()}else for(let p of this.panels)p.update&&p.update(update)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:plugin=>EditorView.scrollMargins.of((view=>{let value=view.plugin(plugin);return value&&{top:value.top.scrollMargin(),bottom:value.bottom.scrollMargin()}}))});class PanelGroup{constructor(view,top,container){this.view=view,this.top=top,this.container=container,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(panels){for(let p of this.panels)p.destroy&&panels.indexOf(p)<0&&p.destroy();this.panels=panels,this.syncDOM()}syncDOM(){if(0==this.panels.length)return void(this.dom&&(this.dom.remove(),this.dom=void 0));if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let parent=this.container||this.view.dom;parent.insertBefore(this.dom,this.top?parent.firstChild:null)}let curDOM=this.dom.firstChild;for(let panel of this.panels)if(panel.dom.parentNode==this.dom){for(;curDOM!=panel.dom;)curDOM=rm(curDOM);curDOM=curDOM.nextSibling}else this.dom.insertBefore(panel.dom,curDOM);for(;curDOM;)curDOM=rm(curDOM)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(this.container&&this.classes!=this.view.themeClasses){for(let cls of this.classes.split(" "))cls&&this.container.classList.remove(cls);for(let cls of(this.classes=this.view.themeClasses).split(" "))cls&&this.container.classList.add(cls)}}}function rm(node){let next=node.nextSibling;return node.remove(),next}const showPanel=Facet.define({enables:panelPlugin});class GutterMarker extends RangeValue{compare(other){return this==other||this.constructor==other.constructor&&this.eq(other)}eq(other){return!1}destroy(dom){}}GutterMarker.prototype.elementClass="",GutterMarker.prototype.toDOM=void 0,GutterMarker.prototype.mapMode=MapMode.TrackBefore,GutterMarker.prototype.startSide=GutterMarker.prototype.endSide=-1,GutterMarker.prototype.point=!0;const gutterLineClass=Facet.define(),defaults$1={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>RangeSet.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},activeGutters=Facet.define();function gutter(config){return[gutters(),activeGutters.of(Object.assign(Object.assign({},defaults$1),config))]}const unfixGutters=Facet.define({combine:values=>values.some((x=>x))});function gutters(config){let result=[gutterView];return config&&!1===config.fixed&&result.push(unfixGutters.of(!0)),result}const gutterView=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.prevViewport=view.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=view.state.facet(activeGutters).map((conf=>new SingleGutterView(view,conf)));for(let gutter of this.gutters)this.dom.appendChild(gutter.dom);this.fixed=!view.state.facet(unfixGutters),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),view.scrollDOM.insertBefore(this.dom,view.contentDOM)}update(update){if(this.updateGutters(update)){let vpA=this.prevViewport,vpB=update.view.viewport,vpOverlap=Math.min(vpA.to,vpB.to)-Math.max(vpA.from,vpB.from);this.syncGutters(vpOverlap<.8*(vpB.to-vpB.from))}update.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px"),this.view.state.facet(unfixGutters)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=update.view.viewport}syncGutters(detach){let after=this.dom.nextSibling;detach&&this.dom.remove();let lineClasses=RangeSet.iter(this.view.state.facet(gutterLineClass),this.view.viewport.from),classSet=[],contexts=this.gutters.map((gutter=>new UpdateContext(gutter,this.view.viewport,-this.view.documentPadding.top)));for(let line of this.view.viewportLineBlocks)if(classSet.length&&(classSet=[]),Array.isArray(line.type)){let first=!0;for(let b of line.type)if(b.type==BlockType.Text&&first){advanceCursor(lineClasses,classSet,b.from);for(let cx of contexts)cx.line(this.view,b,classSet);first=!1}else if(b.widget)for(let cx of contexts)cx.widget(this.view,b)}else if(line.type==BlockType.Text){advanceCursor(lineClasses,classSet,line.from);for(let cx of contexts)cx.line(this.view,line,classSet)}else if(line.widget)for(let cx of contexts)cx.widget(this.view,line);for(let cx of contexts)cx.finish();detach&&this.view.scrollDOM.insertBefore(this.dom,after)}updateGutters(update){let prev=update.startState.facet(activeGutters),cur=update.state.facet(activeGutters),change=update.docChanged||update.heightChanged||update.viewportChanged||!RangeSet.eq(update.startState.facet(gutterLineClass),update.state.facet(gutterLineClass),update.view.viewport.from,update.view.viewport.to);if(prev==cur)for(let gutter of this.gutters)gutter.update(update)&&(change=!0);else{change=!0;let gutters=[];for(let conf of cur){let known=prev.indexOf(conf);known<0?gutters.push(new SingleGutterView(this.view,conf)):(this.gutters[known].update(update),gutters.push(this.gutters[known]))}for(let g of this.gutters)g.dom.remove(),gutters.indexOf(g)<0&&g.destroy();for(let g of gutters)this.dom.appendChild(g.dom);this.gutters=gutters}return change}destroy(){for(let view of this.gutters)view.destroy();this.dom.remove()}},{provide:plugin=>EditorView.scrollMargins.of((view=>{let value=view.plugin(plugin);return value&&0!=value.gutters.length&&value.fixed?view.textDirection==Direction.LTR?{left:value.dom.offsetWidth*view.scaleX}:{right:value.dom.offsetWidth*view.scaleX}:null}))});function asArray(val){return Array.isArray(val)?val:[val]}function advanceCursor(cursor,collect,pos){for(;cursor.value&&cursor.from<=pos;)cursor.from==pos&&collect.push(cursor.value),cursor.next()}class UpdateContext{constructor(gutter,viewport,height){this.gutter=gutter,this.height=height,this.i=0,this.cursor=RangeSet.iter(gutter.markers,viewport.from)}addElement(view,block,markers){let{gutter:gutter}=this,above=(block.top-this.height)/view.scaleY,height=block.height/view.scaleY;if(this.i==gutter.elements.length){let newElt=new GutterElement(view,height,above,markers);gutter.elements.push(newElt),gutter.dom.appendChild(newElt.dom)}else gutter.elements[this.i].update(view,height,above,markers);this.height=block.bottom,this.i++}line(view,line,extraMarkers){let localMarkers=[];advanceCursor(this.cursor,localMarkers,line.from),extraMarkers.length&&(localMarkers=localMarkers.concat(extraMarkers));let forLine=this.gutter.config.lineMarker(view,line,localMarkers);forLine&&localMarkers.unshift(forLine);let gutter=this.gutter;(0!=localMarkers.length||gutter.config.renderEmptyElements)&&this.addElement(view,line,localMarkers)}widget(view,block){let marker=this.gutter.config.widgetMarker(view,block.widget,block);marker&&this.addElement(view,block,[marker])}finish(){let gutter=this.gutter;for(;gutter.elements.length>this.i;){let last=gutter.elements.pop();gutter.dom.removeChild(last.dom),last.destroy()}}}class SingleGutterView{constructor(view,config){this.view=view,this.config=config,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let prop in config.domEventHandlers)this.dom.addEventListener(prop,(event=>{let y,target=event.target;if(target!=this.dom&&this.dom.contains(target)){for(;target.parentNode!=this.dom;)target=target.parentNode;let rect=target.getBoundingClientRect();y=(rect.top+rect.bottom)/2}else y=event.clientY;let line=view.lineBlockAtHeight(y-view.documentTop);config.domEventHandlers[prop](view,line,event)&&event.preventDefault()}));this.markers=asArray(config.markers(view)),config.initialSpacer&&(this.spacer=new GutterElement(view,0,0,[config.initialSpacer(view)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(update){let prevMarkers=this.markers;if(this.markers=asArray(this.config.markers(update.view)),this.spacer&&this.config.updateSpacer){let updated=this.config.updateSpacer(this.spacer.markers[0],update);updated!=this.spacer.markers[0]&&this.spacer.update(update.view,0,0,[updated])}let vp=update.view.viewport;return!RangeSet.eq(this.markers,prevMarkers,vp.from,vp.to)||!!this.config.lineMarkerChange&&this.config.lineMarkerChange(update)}destroy(){for(let elt of this.elements)elt.destroy()}}class GutterElement{constructor(view,height,above,markers){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(view,height,above,markers)}update(view,height,above,markers){this.height!=height&&(this.height=height,this.dom.style.height=height+"px"),this.above!=above&&(this.dom.style.marginTop=(this.above=above)?above+"px":""),function(a,b){if(a.length!=b.length)return!1;for(let i=0;icombineConfig(values,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(a,b){let result=Object.assign({},a);for(let event in b){let exists=result[event],add=b[event];result[event]=exists?(view,line,event)=>exists(view,line,event)||add(view,line,event):add}return result}})});class NumberMarker extends GutterMarker{constructor(number){super(),this.number=number}eq(other){return this.number==other.number}toDOM(){return document.createTextNode(this.number)}}function formatNumber(view,number){return view.state.facet(lineNumberConfig).formatNumber(number,view.state)}const lineNumberGutter=activeGutters.compute([lineNumberConfig],(state=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers:view=>view.state.facet(lineNumberMarkers),lineMarker:(view,line,others)=>others.some((m=>m.toDOM))?null:new NumberMarker(formatNumber(view,view.state.doc.lineAt(line.from).number)),widgetMarker:()=>null,lineMarkerChange:update=>update.startState.facet(lineNumberConfig)!=update.state.facet(lineNumberConfig),initialSpacer:view=>new NumberMarker(formatNumber(view,maxLineNumber(view.state.doc.lines))),updateSpacer(spacer,update){let max=formatNumber(update.view,maxLineNumber(update.view.state.doc.lines));return max==spacer.number?spacer:new NumberMarker(max)},domEventHandlers:state.facet(lineNumberConfig).domEventHandlers})));function lineNumbers(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[lineNumberConfig.of(config),gutters(),lineNumberGutter]}function maxLineNumber(lines){let last=9;for(;last{let marks=[],last=-1;for(let range of state.selection.ranges){let linePos=state.doc.lineAt(range.head).from;linePos>last&&(last=linePos,marks.push(activeLineGutterMarker.range(linePos)))}return RangeSet.of(marks)}));const DefaultBufferLength=1024;let nextPropID=0;class Range{constructor(from,to){this.from=from,this.to=to}}class NodeProp{constructor(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.id=nextPropID++,this.perNode=!!config.perNode,this.deserialize=config.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(match){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof match&&(match=NodeType.match(match)),type=>{let result=match(type);return void 0===result?null:[this,result]}}}NodeProp.closedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.group=new NodeProp({deserialize:str=>str.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});class MountedTree{constructor(tree,overlay,parser){this.tree=tree,this.overlay=overlay,this.parser=parser}}const noProps=Object.create(null);class NodeType{constructor(name,props,id){let flags=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;this.name=name,this.props=props,this.id=id,this.flags=flags}static define(spec){let props=spec.props&&spec.props.length?Object.create(null):noProps,flags=(spec.top?1:0)|(spec.skipped?2:0)|(spec.error?4:0)|(null==spec.name?8:0),type=new NodeType(spec.name||"",props,spec.id,flags);if(spec.props)for(let src of spec.props)if(Array.isArray(src)||(src=src(type)),src){if(src[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");props[src[0].id]=src[1]}return type}prop(prop){return this.props[prop.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(name){if("string"==typeof name){if(this.name==name)return!0;let group=this.prop(NodeProp.group);return!!group&&group.indexOf(name)>-1}return this.id==name}static match(map){let direct=Object.create(null);for(let prop in map)for(let name of prop.split(" "))direct[name]=map[prop];return node=>{for(let groups=node.prop(NodeProp.group),i=-1;i<(groups?groups.length:0);i++){let found=direct[i<0?node.name:groups[i]];if(found)return found}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(types){this.types=types;for(let i=0;i0&&void 0!==arguments[0]?arguments[0]:0;return new TreeCursor(this.topNode,mode)}cursorAt(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,scope=CachedNode.get(this)||this.topNode,cursor=new TreeCursor(scope);return cursor.moveTo(pos,side),CachedNode.set(this,cursor._tree),cursor}get topNode(){return new TreeNode(this,0,0,null)}resolve(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,node=resolveNode(CachedNode.get(this)||this.topNode,pos,side,!1);return CachedNode.set(this,node),node}resolveInner(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,node=resolveNode(CachedInnerNode.get(this)||this.topNode,pos,side,!0);return CachedInnerNode.set(this,node),node}iterate(spec){let{enter:enter,leave:leave,from:from=0,to:to=this.length}=spec,mode=spec.mode||0,anon=(mode&IterMode.IncludeAnonymous)>0;for(let c=this.cursor(mode|IterMode.IncludeAnonymous);;){let entered=!1;if(c.from<=to&&c.to>=from&&(!anon&&c.type.isAnonymous||!1!==enter(c))){if(c.firstChild())continue;entered=!0}for(;entered&&leave&&(anon||!c.type.isAnonymous)&&leave(c),!c.nextSibling();){if(!c.parent())return;entered=!0}}}prop(prop){return prop.perNode?this.props?this.props[prop.id]:void 0:this.type.prop(prop)}get propValues(){let result=[];if(this.props)for(let id in this.props)result.push([+id,this.props[id]]);return result}balance(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((children,positions,length)=>new Tree(this.type,children,positions,length,this.propValues)),config.makeTree||((children,positions,length)=>new Tree(NodeType.none,children,positions,length)))}static build(data){return function(data){var _a;let{buffer:buffer,nodeSet:nodeSet,maxBufferLength:maxBufferLength=DefaultBufferLength,reused:reused=[],minRepeatType:minRepeatType=nodeSet.types.length}=data,cursor=Array.isArray(buffer)?new FlatBufferCursor(buffer,buffer.length):buffer,types=nodeSet.types,contextHash=0,lookAhead=0;function takeNode(parentStart,minPos,children,positions,inRepeat){let{id:id,start:start,end:end,size:size}=cursor,lookAheadAtStart=lookAhead;for(;size<0;){if(cursor.next(),-1==size){let node=reused[id];return children.push(node),void positions.push(start-parentStart)}if(-3==size)return void(contextHash=id);if(-4==size)return void(lookAhead=id);throw new RangeError("Unrecognized record size: ".concat(size))}let node,buffer,type=types[id],startPos=start-parentStart;if(end-start<=maxBufferLength&&(buffer=findBufferSize(cursor.pos-minPos,inRepeat))){let data=new Uint16Array(buffer.size-buffer.skip),endPos=cursor.pos-buffer.size,index=data.length;for(;cursor.pos>endPos;)index=copyToBuffer(buffer.start,data,index);node=new TreeBuffer(data,end-buffer.start,nodeSet),startPos=buffer.start-parentStart}else{let endPos=cursor.pos-size;cursor.next();let localChildren=[],localPositions=[],localInRepeat=id>=minRepeatType?id:-1,lastGroup=0,lastEnd=end;for(;cursor.pos>endPos;)localInRepeat>=0&&cursor.id==localInRepeat&&cursor.size>=0?(cursor.end<=lastEnd-maxBufferLength&&(makeRepeatLeaf(localChildren,localPositions,start,lastGroup,cursor.end,lastEnd,localInRepeat,lookAheadAtStart),lastGroup=localChildren.length,lastEnd=cursor.end),cursor.next()):takeNode(start,endPos,localChildren,localPositions,localInRepeat);if(localInRepeat>=0&&lastGroup>0&&lastGroup-1&&lastGroup>0){let make=makeBalanced(type);node=balanceRange(type,localChildren,localPositions,0,localChildren.length,0,end-start,make,make)}else node=makeTree(type,localChildren,localPositions,end-start,lookAheadAtStart-end)}children.push(node),positions.push(startPos)}function makeBalanced(type){return(children,positions,length)=>{let last,lookAheadProp,lookAhead=0,lastI=children.length-1;if(lastI>=0&&(last=children[lastI])instanceof Tree){if(!lastI&&last.type==type&&last.length==length)return last;(lookAheadProp=last.prop(NodeProp.lookAhead))&&(lookAhead=positions[lastI]+last.length+lookAheadProp)}return makeTree(type,children,positions,length,lookAhead)}}function makeRepeatLeaf(children,positions,base,i,from,to,type,lookAhead){let localChildren=[],localPositions=[];for(;children.length>i;)localChildren.push(children.pop()),localPositions.push(positions.pop()+base-from);children.push(makeTree(nodeSet.types[type],localChildren,localPositions,to-from,lookAhead-to)),positions.push(from-base)}function makeTree(type,children,positions,length){let lookAhead=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,props=arguments.length>5?arguments[5]:void 0;if(contextHash){let pair=[NodeProp.contextHash,contextHash];props=props?[pair].concat(props):[pair]}if(lookAhead>25){let pair=[NodeProp.lookAhead,lookAhead];props=props?[pair].concat(props):[pair]}return new Tree(type,children,positions,length,props)}function findBufferSize(maxSize,inRepeat){let fork=cursor.fork(),size=0,start=0,skip=0,minStart=fork.end-maxBufferLength,result={size:0,start:0,skip:0};scan:for(let minPos=fork.pos-maxSize;fork.pos>minPos;){let nodeSize=fork.size;if(fork.id==inRepeat&&nodeSize>=0){result.size=size,result.start=start,result.skip=skip,skip+=4,size+=4,fork.next();continue}let startPos=fork.pos-nodeSize;if(nodeSize<0||startPos=minRepeatType?4:0,nodeStart=fork.start;for(fork.next();fork.pos>startPos;){if(fork.size<0){if(-3!=fork.size)break scan;localSkipped+=4}else fork.id>=minRepeatType&&(localSkipped+=4);fork.next()}start=nodeStart,size+=nodeSize,skip+=localSkipped}return(inRepeat<0||size==maxSize)&&(result.size=size,result.start=start,result.skip=skip),result.size>4?result:void 0}function copyToBuffer(bufferStart,buffer,index){let{id:id,start:start,end:end,size:size}=cursor;if(cursor.next(),size>=0&&id4){let endPos=cursor.pos-(size-4);for(;cursor.pos>endPos;)index=copyToBuffer(bufferStart,buffer,index)}buffer[--index]=startIndex,buffer[--index]=end-bufferStart,buffer[--index]=start-bufferStart,buffer[--index]=id}else-3==size?contextHash=id:-4==size&&(lookAhead=id);return index}let children=[],positions=[];for(;cursor.pos>0;)takeNode(data.start||0,data.bufferStart||0,children,positions,-1);let length=null!==(_a=data.length)&&void 0!==_a?_a:children.length?positions[0]+children[0].length:0;return new Tree(types[data.topID],children.reverse(),positions.reverse(),length)}(data)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(buffer,index){this.buffer=buffer,this.index=index}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(buffer,length,set){this.buffer=buffer,this.length=length,this.set=set}get type(){return NodeType.none}toString(){let result=[];for(let index=0;index0));i=buffer[i+3]);return pick}slice(startI,endI,from){let b=this.buffer,copy=new Uint16Array(endI-startI),len=0;for(let i=startI,j=0;i=pos&&frompos;case 1:return from<=pos&&to>pos;case 2:return to>pos;case 4:return!0}}function enterUnfinishedNodesBefore(node,pos){let scan=node.childBefore(pos);for(;scan;){let last=scan.lastChild;if(!last||last.to!=scan.to)break;last.type.isError&&last.from==last.to?(node=scan,scan=last.prevSibling):scan=last}return node}function resolveNode(node,pos,side,overlays){for(var _a;node.from==node.to||(side<1?node.from>=pos:node.from>pos)||(side>-1?node.to<=pos:node.to4&&void 0!==arguments[4]?arguments[4]:0;for(let parent=this;;){for(let{children:children,positions:positions}=parent._tree,e=dir>0?children.length:-1;i!=e;i+=dir){let next=children[i],start=positions[i]+parent.from;if(checkSide(side,pos,start,start+next.length))if(next instanceof TreeBuffer){if(mode&IterMode.ExcludeBuffers)continue;let index=next.findChild(0,next.buffer.length,dir,pos-start,side);if(index>-1)return new BufferNode(new BufferContext(parent,next,i,start),null,index)}else if(mode&IterMode.IncludeAnonymous||!next.type.isAnonymous||hasChild(next)){let mounted;if(!(mode&IterMode.IgnoreMounts)&&next.props&&(mounted=next.prop(NodeProp.mounted))&&!mounted.overlay)return new TreeNode(mounted.tree,start,i,parent);let inner=new TreeNode(next,start,i,parent);return mode&IterMode.IncludeAnonymous||!inner.type.isAnonymous?inner:inner.nextChild(dir<0?next.children.length-1:0,dir,pos,side)}}if(mode&IterMode.IncludeAnonymous||!parent.type.isAnonymous)return null;if(i=parent.index>=0?parent.index+dir:dir<0?-1:parent._parent._tree.children.length,parent=parent._parent,!parent)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(pos){return this.nextChild(0,1,pos,2)}childBefore(pos){return this.nextChild(this._tree.children.length-1,-1,pos,-2)}enter(pos,side){let mounted,mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!(mode&IterMode.IgnoreOverlays)&&(mounted=this._tree.prop(NodeProp.mounted))&&mounted.overlay){let rPos=pos-this.from;for(let{from:from,to:to}of mounted.overlay)if((side>0?from<=rPos:from=rPos:to>rPos))return new TreeNode(mounted.tree,mounted.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,pos,side,mode)}nextSignificantParent(){let val=this;for(;val.type.isAnonymous&&val._parent;)val=val._parent;return val}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(){return new TreeCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}get tree(){return this._tree}toTree(){return this._tree}resolve(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!1)}resolveInner(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}getChild(type){let r=getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null);return r.length?r[0]:null}getChildren(type){return getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}toString(){return this._tree.toString()}get node(){return this}matchContext(context){return matchNodeContext(this,context)}}function getChildren(node,type,before,after){let cur=node.cursor(),result=[];if(!cur.firstChild())return result;if(null!=before)for(;!cur.type.is(before);)if(!cur.nextSibling())return result;for(;;){if(null!=after&&cur.type.is(after))return result;if(cur.type.is(type)&&result.push(cur.node),!cur.nextSibling())return null==after?result:[]}}function matchNodeContext(node,context){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:context.length-1;for(let p=node.parent;i>=0;p=p.parent){if(!p)return!1;if(!p.type.isAnonymous){if(context[i]&&context[i]!=p.name)return!1;i--}}return!0}class BufferContext{constructor(parent,buffer,index,start){this.parent=parent,this.buffer=buffer,this.index=index,this.start=start}}class BufferNode{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(context,_parent,index){this.context=context,this._parent=_parent,this.index=index,this.type=context.buffer.set.types[context.buffer.buffer[index]]}child(dir,pos,side){let{buffer:buffer}=this.context,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(pos){return this.child(1,pos,2)}childBefore(pos){return this.child(-1,pos,-2)}enter(pos,side){if((arguments.length>2&&void 0!==arguments[2]?arguments[2]:0)&IterMode.ExcludeBuffers)return null;let{buffer:buffer}=this.context,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],side>0?1:-1,pos-this.context.start,side);return index<0?null:new BufferNode(this.context,this,index)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(dir){return this._parent?null:this.context.parent.nextChild(this.context.index+dir,dir,0,4)}get nextSibling(){let{buffer:buffer}=this.context,after=buffer.buffer[this.index+3];return after<(this._parent?buffer.buffer[this._parent.index+3]:buffer.buffer.length)?new BufferNode(this.context,this._parent,after):this.externalSibling(1)}get prevSibling(){let{buffer:buffer}=this.context,parentStart=this._parent?this._parent.index+4:0;return this.index==parentStart?this.externalSibling(-1):new BufferNode(this.context,this._parent,buffer.findChild(parentStart,this.index,-1,0,4))}cursor(){return new TreeCursor(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}get tree(){return null}toTree(){let children=[],positions=[],{buffer:buffer}=this.context,startI=this.index+4,endI=buffer.buffer[this.index+3];if(endI>startI){let from=buffer.buffer[this.index+1];children.push(buffer.slice(startI,endI,from)),positions.push(0)}return new Tree(this.type,children,positions,this.to-this.from)}resolve(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!1)}resolveInner(pos){return resolveNode(this,pos,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,!0)}enterUnfinishedNodesBefore(pos){return enterUnfinishedNodesBefore(this,pos)}toString(){return this.context.buffer.childString(this.index)}getChild(type){let r=getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null);return r.length?r[0]:null}getChildren(type){return getChildren(this,type,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)}get node(){return this}matchContext(context){return matchNodeContext(this,context)}}class TreeCursor{get name(){return this.type.name}constructor(node){let mode=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.mode=mode,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,node instanceof TreeNode)this.yieldNode(node);else{this._tree=node.context.parent,this.buffer=node.context;for(let n=node._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=node,this.yieldBuf(node.index)}}yieldNode(node){return!!node&&(this._tree=node,this.type=node.type,this.from=node.from,this.to=node.to,!0)}yieldBuf(index,type){this.index=index;let{start:start,buffer:buffer}=this.buffer;return this.type=type||buffer.set.types[buffer.buffer[index]],this.from=start+buffer.buffer[index+1],this.to=start+buffer.buffer[index+2],!0}yield(node){return!!node&&(node instanceof TreeNode?(this.buffer=null,this.yieldNode(node)):(this.buffer=node.context,this.yieldBuf(node.index,node.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(dir,pos,side){if(!this.buffer)return this.yield(this._tree.nextChild(dir<0?this._tree._tree.children.length-1:0,dir,pos,side,this.mode));let{buffer:buffer}=this.buffer,index=buffer.findChild(this.index+4,buffer.buffer[this.index+3],dir,pos-this.buffer.start,side);return!(index<0)&&(this.stack.push(this.index),this.yieldBuf(index))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(pos){return this.enterChild(1,pos,2)}childBefore(pos){return this.enterChild(-1,pos,-2)}enter(pos,side){let mode=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.mode;return this.buffer?!(mode&IterMode.ExcludeBuffers)&&this.enterChild(1,pos,side):this.yield(this._tree.enter(pos,side,mode))}parent(){if(!this.buffer)return this.yieldNode(this.mode&IterMode.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let parent=this.mode&IterMode.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(parent)}sibling(dir){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+dir,dir,0,4,this.mode));let{buffer:buffer}=this.buffer,d=this.stack.length-1;if(dir<0){let parentStart=d<0?0:this.stack[d]+4;if(this.index!=parentStart)return this.yieldBuf(buffer.findChild(parentStart,this.index,-1,0,4))}else{let after=buffer.buffer[this.index+3];if(after<(d<0?buffer.buffer.length:buffer.buffer[this.stack[d]+3]))return this.yieldBuf(after)}return d<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+dir,dir,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(dir){let index,parent,{buffer:buffer}=this;if(buffer){if(dir>0){if(this.index-1)for(let i=index+dir,e=dir<0?-1:parent._tree.children.length;i!=e;i+=dir){let child=parent._tree.children[i];if(this.mode&IterMode.IncludeAnonymous||child instanceof TreeBuffer||!child.type.isAnonymous||hasChild(child))return!1}return!0}move(dir,enter){if(enter&&this.enterChild(dir,0,4))return!0;for(;;){if(this.sibling(dir))return!0;if(this.atLastNode(dir)||!this.parent())return!1}}next(){let enter=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.move(1,enter)}prev(){let enter=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this.move(-1,enter)}moveTo(pos){let side=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;for(;(this.from==this.to||(side<1?this.from>=pos:this.from>pos)||(side>-1?this.to<=pos:this.to=0;){for(let c=cache;c;c=c._parent)if(c.index==index){if(index==this.index)return c;result=c,depth=d+1;break scan}index=this.stack[--d]}for(let i=depth;i=0;d--){if(d<0)return matchNodeContext(this.node,context,i);let type=types[buffer.buffer[this.stack[d]]];if(!type.isAnonymous){if(context[i]&&context[i]!=type.name)return!1;i--}}return!0}}function hasChild(tree){return tree.children.some((ch=>ch instanceof TreeBuffer||!ch.type.isAnonymous||hasChild(ch)))}const nodeSizeCache=new WeakMap;function nodeSize(balanceType,node){if(!balanceType.isAnonymous||node instanceof TreeBuffer||node.type!=balanceType)return 1;let size=nodeSizeCache.get(node);if(null==size){size=1;for(let child of node.children){if(child.type!=balanceType||!(child instanceof Tree)){size=1;break}size+=nodeSize(balanceType,child)}nodeSizeCache.set(node,size)}return size}function balanceRange(balanceType,children,positions,from,to,start,length,mkTop,mkTree){let total=0;for(let i=from;i=maxChild)break;groupSize+=nextSize}if(i==groupFrom+1){if(groupSize>maxChild){let only=children[groupFrom];divide(only.children,only.positions,0,only.children.length,positions[groupFrom]+offset);continue}localChildren.push(children[groupFrom])}else{let length=positions[i-1]+children[i-1].length-groupStart;localChildren.push(balanceRange(balanceType,children,positions,groupFrom,i,groupStart,length,null,mkTree))}localPositions.push(groupStart+offset-start)}}(children,positions,from,to,0),(mkTop||mkTree)(localChildren,localPositions,length)}class NodeWeakMap{constructor(){this.map=new WeakMap}setBuffer(buffer,index,value){let inner=this.map.get(buffer);inner||this.map.set(buffer,inner=new Map),inner.set(index,value)}getBuffer(buffer,index){let inner=this.map.get(buffer);return inner&&inner.get(index)}set(node,value){node instanceof BufferNode?this.setBuffer(node.context.buffer,node.index,value):node instanceof TreeNode&&this.map.set(node.tree,value)}get(node){return node instanceof BufferNode?this.getBuffer(node.context.buffer,node.index):node instanceof TreeNode?this.map.get(node.tree):void 0}cursorSet(cursor,value){cursor.buffer?this.setBuffer(cursor.buffer.buffer,cursor.index,value):this.map.set(cursor.tree,value)}cursorGet(cursor){return cursor.buffer?this.getBuffer(cursor.buffer.buffer,cursor.index):this.map.get(cursor.tree)}}class TreeFragment{constructor(from,to,tree,offset){let openStart=arguments.length>4&&void 0!==arguments[4]&&arguments[4],openEnd=arguments.length>5&&void 0!==arguments[5]&&arguments[5];this.from=from,this.to=to,this.tree=tree,this.offset=offset,this.open=(openStart?1:0)|(openEnd?2:0)}get openStart(){return(1&this.open)>0}get openEnd(){return(2&this.open)>0}static addTree(tree){let fragments=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],partial=arguments.length>2&&void 0!==arguments[2]&&arguments[2],result=[new TreeFragment(0,tree.length,tree,0,!1,partial)];for(let f of fragments)f.to>tree.length&&result.push(f);return result}static applyChanges(fragments,changes){let minGap=arguments.length>2&&void 0!==arguments[2]?arguments[2]:128;if(!changes.length)return fragments;let result=[],fI=1,nextF=fragments.length?fragments[0]:null;for(let cI=0,pos=0,off=0;;cI++){let nextC=cI=minGap)for(;nextF&&nextF.from=cut.from||nextPos<=cut.to||off){let fFrom=Math.max(cut.from,pos)-off,fTo=Math.min(cut.to,nextPos)-off;cut=fFrom>=fTo?null:new TreeFragment(fFrom,fTo,cut.tree,cut.offset+off,cI>0,!!nextC)}if(cut&&result.push(cut),nextF.to>nextPos)break;nextF=fInew Range(r.from,r.to))):[new Range(0,0)]:[new Range(0,input.length)],this.createParse(input,fragments||[],ranges)}parse(input,fragments,ranges){let parse=this.startParse(input,fragments,ranges);for(;;){let done=parse.advance();if(done)return done}}}class StringInput{constructor(string){this.string=string}get length(){return this.string.length}chunk(from){return this.string.slice(from)}get lineChunks(){return!1}read(from,to){return this.string.slice(from,to)}}function parseMixed(nest){return(parse,input,fragments,ranges)=>new MixedParse(parse,nest,input,fragments,ranges)}class InnerParse{constructor(parser,parse,overlay,target,ranges){if(this.parser=parser,this.parse=parse,this.overlay=overlay,this.target=target,this.ranges=ranges,!ranges.length||ranges.some((r=>r.from>=r.to)))throw new RangeError("Invalid inner parse ranges given: "+JSON.stringify(ranges))}}class ActiveOverlay{constructor(parser,predicate,mounts,index,start,target,prev){this.parser=parser,this.predicate=predicate,this.mounts=mounts,this.index=index,this.start=start,this.target=target,this.prev=prev,this.depth=0,this.ranges=[]}}const stoppedInner=new NodeProp({perNode:!0});class MixedParse{constructor(base,nest,input,fragments,ranges){this.nest=nest,this.input=input,this.fragments=fragments,this.ranges=ranges,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=base}advance(){if(this.baseParse){let done=this.baseParse.advance();if(!done)return null;if(this.baseParse=null,this.baseTree=done,this.startInner(),null!=this.stoppedAt)for(let inner of this.inner)inner.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let result=this.baseTree;return null!=this.stoppedAt&&(result=new Tree(result.type,result.children,result.positions,result.length,result.propValues.concat([[stoppedInner,this.stoppedAt]]))),result}let inner=this.inner[this.innerDone],done=inner.parse.advance();if(done){this.innerDone++;let props=Object.assign(Object.create(null),inner.target.props);props[NodeProp.mounted.id]=new MountedTree(done,inner.overlay,inner.parser),inner.target.props=props}return null}get parsedPos(){if(this.baseParse)return 0;let pos=this.input.length;for(let i=this.innerDone;im.frag.from<=cursor.from&&m.frag.to>=cursor.to&&m.mount.overlay));if(match)for(let r of match.mount.overlay){let from=r.from+match.pos,to=r.to+match.pos;from>=cursor.from&&to<=cursor.to&&!overlay.ranges.some((r=>r.fromfrom))&&overlay.ranges.push({from:from,to:to})}}enter=!1}else if(covered&&(isCovered=checkCover(covered.ranges,cursor.from,cursor.to)))enter=2!=isCovered;else if(!cursor.type.isAnonymous&&cursor.fromnew Range(r.from-cursor.from,r.to-cursor.from))):null,cursor.tree,ranges)),nest.overlay?ranges.length&&(covered={ranges:ranges,depth:0,prev:covered}):enter=!1}}else overlay&&(range=overlay.predicate(cursor))&&(!0===range&&(range=new Range(cursor.from,cursor.to)),range.fromnew Range(r.from-overlay.start,r.to-overlay.start))),overlay.target,ranges)),overlay=overlay.prev}covered&&!--covered.depth&&(covered=covered.prev)}}}}function checkCover(covered,from,to){for(let range of covered){if(range.from>=to)break;if(range.to>from)return range.from<=from&&range.to>=to?2:1}return 0}function sliceBuf(buf,startI,endI,nodes,positions,off){if(startI=node.to);i++);let buf=base.children[i],b=buf.buffer;base.children[i]=function split(startI,endI,type,innerOffset,length){let i=startI;for(;b[i+2]+off<=node.from;)i=b[i+3];let children=[],positions=[];sliceBuf(buf,startI,i,children,positions,innerOffset);let from=b[i+1],to=b[i+2],isTarget=from+off==node.from&&to+off==node.to&&b[i]==node.type.id;return children.push(isTarget?node.toTree():split(i+4,b[i+3],buf.set.types[b[i]],from,to-from)),positions.push(from-innerOffset),sliceBuf(buf,b[i+3],endI,children,positions,innerOffset),new Tree(type,children,positions,length)}(0,b.length,NodeType.none,0,buf.length);for(let d=0;d<=depth;d++)cursor.childAfter(node.from)}class StructureCursor{constructor(root,offset){this.offset=offset,this.done=!1,this.cursor=root.cursor(IterMode.IncludeAnonymous|IterMode.IgnoreMounts)}moveTo(pos){let{cursor:cursor}=this,p=pos-this.offset;for(;!this.done&&cursor.from=pos&&cursor.enter(p,1,IterMode.IgnoreOverlays|IterMode.ExcludeBuffers)||cursor.next(!1)||(this.done=!0)}hasNode(cursor){if(this.moveTo(cursor.from),!this.done&&this.cursor.from+this.offset==cursor.from&&this.cursor.tree)for(let tree=this.cursor.tree;;){if(tree==cursor.tree)return!0;if(!(tree.children.length&&0==tree.positions[0]&&tree.children[0]instanceof Tree))break;tree=tree.children[0]}return!1}}let FragmentCursor$1=class{constructor(fragments){var _a;if(this.fragments=fragments,this.curTo=0,this.fragI=0,fragments.length){let first=this.curFrag=fragments[0];this.curTo=null!==(_a=first.tree.prop(stoppedInner))&&void 0!==_a?_a:first.to,this.inner=new StructureCursor(first.tree,-first.offset)}else this.curFrag=this.inner=null}hasNode(node){for(;this.curFrag&&node.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=node.from&&this.curTo>=node.to&&this.inner.hasNode(node)}nextFrag(){var _a;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let frag=this.curFrag=this.fragments[this.fragI];this.curTo=null!==(_a=frag.tree.prop(stoppedInner))&&void 0!==_a?_a:frag.to,this.inner=new StructureCursor(frag.tree,-frag.offset)}}findMounts(pos,parser){var _a;let result=[];if(this.inner){this.inner.cursor.moveTo(pos,1);for(let pos=this.inner.cursor.node;pos;pos=pos.parent){let mount=null===(_a=pos.tree)||void 0===_a?void 0:_a.prop(NodeProp.mounted);if(mount&&mount.parser==parser)for(let i=this.fragI;i=pos.to)break;frag.tree==this.curFrag.tree&&result.push({frag:frag,pos:pos.from-frag.offset,mount:mount})}}}return result}};function punchRanges(outer,ranges){let copy=null,current=ranges;for(let i=1,j=0;i=gapTo)break;r.to<=gapFrom||(copy||(current=copy=ranges.slice()),r.fromgapTo&©.splice(j+1,0,new Range(gapTo,r.to))):r.to>gapTo?copy[j--]=new Range(gapTo,r.to):copy.splice(j--,1))}}return current}function findCoverChanges(a,b,from,to){let iA=0,iB=0,inA=!1,inB=!1,pos=-1e9,result=[];for(;;){let nextA=iA==a.length?1e9:inA?a[iA].to:a[iA].from,nextB=iB==b.length?1e9:inB?b[iB].to:b[iB].from;if(inA!=inB){let start=Math.max(pos,from),end=Math.min(nextA,nextB,to);startnew Range(r.from+pos,r.to+pos))),from,to);for(let i=0,pos=from;;i++){let last=i==changes.length,end=last?to:changes[i].from;if(end>pos&&result.push(new TreeFragment(pos,end,mount.tree,-startPos,frag.from>=pos||frag.openStart,frag.to<=end||frag.openEnd)),last)break;pos=changes[i].to}}else result.push(new TreeFragment(from,to,mount.tree,-startPos,frag.from>=startPos||frag.openStart,frag.to<=endPos||frag.openEnd))}return result}let nextTagID=0;class Tag{constructor(set,base,modified){this.set=set,this.base=base,this.modified=modified,this.id=nextTagID++}static define(parent){if(null==parent?void 0:parent.base)throw new Error("Can not derive from a modified tag");let tag=new Tag([],null,[]);if(tag.set.push(tag),parent)for(let t of parent.set)tag.set.push(t);return tag}static defineModifier(){let mod=new Modifier;return tag=>tag.modified.indexOf(mod)>-1?tag:Modifier.get(tag.base||tag,tag.modified.concat(mod).sort(((a,b)=>a.id-b.id)))}}let nextModifierID=0;class Modifier{constructor(){this.instances=[],this.id=nextModifierID++}static get(base,mods){if(!mods.length)return base;let exists=mods[0].instances.find((t=>{return t.base==base&&(a=mods,b=t.modified,a.length==b.length&&a.every(((x,i)=>x==b[i])));var a,b}));if(exists)return exists;let set=[],tag=new Tag(set,base,mods);for(let m of mods)m.instances.push(tag);let configs=function(array){let sets=[[]];for(let i=0;ib.length-a.length))}(mods);for(let parent of base.set)if(!parent.modified.length)for(let config of configs)set.push(Modifier.get(parent,config));return tag}}function styleTags(spec){let byName=Object.create(null);for(let prop in spec){let tags=spec[prop];Array.isArray(tags)||(tags=[tags]);for(let part of prop.split(" "))if(part){let pieces=[],mode=2,rest=part;for(let pos=0;;){if("..."==rest&&pos>0&&pos+3==part.length){mode=1;break}let m=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);if(!m)throw new RangeError("Invalid path: "+part);if(pieces.push("*"==m[0]?"":'"'==m[0][0]?JSON.parse(m[0]):m[0]),pos+=m[0].length,pos==part.length)break;let next=part[pos++];if(pos==part.length&&"!"==next){mode=0;break}if("/"!=next)throw new RangeError("Invalid path: "+part);rest=part.slice(pos)}let last=pieces.length-1,inner=pieces[last];if(!inner)throw new RangeError("Invalid path: "+part);let rule=new Rule(tags,mode,last>0?pieces.slice(0,last):null);byName[inner]=rule.sort(byName[inner])}}return ruleNodeProp.add(byName)}const ruleNodeProp=new NodeProp;class Rule{constructor(tags,mode,context,next){this.tags=tags,this.mode=mode,this.context=context,this.next=next}get opaque(){return 0==this.mode}get inherit(){return 1==this.mode}sort(other){return!other||other.depth{let cls=all;for(let tag of tags)for(let sub of tag.set){let tagClass=map[sub.id];if(tagClass){cls=cls?cls+" "+tagClass:tagClass;break}}return cls},scope:scope}}function highlightTree(tree,highlighter,putStyle){let from=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,to=arguments.length>4&&void 0!==arguments[4]?arguments[4]:tree.length,builder=new HighlightBuilder(from,Array.isArray(highlighter)?highlighter:[highlighter],putStyle);builder.highlightRange(tree.cursor(),from,to,"",builder.highlighters),builder.flush(to)}Rule.empty=new Rule([],2,null);class HighlightBuilder{constructor(at,highlighters,span){this.at=at,this.highlighters=highlighters,this.span=span,this.class=""}startSpan(at,cls){cls!=this.class&&(this.flush(at),at>this.at&&(this.at=at),this.class=cls)}flush(to){to>this.at&&this.class&&this.span(this.at,to,this.class)}highlightRange(cursor,from,to,inheritedClass,highlighters){let{type:type,from:start,to:end}=cursor;if(start>=to||end<=from)return;type.isTop&&(highlighters=this.highlighters.filter((h=>!h.scope||h.scope(type))));let cls=inheritedClass,rule=function(node){let rule=node.type.prop(ruleNodeProp);for(;rule&&rule.context&&!node.matchContext(rule.context);)rule=rule.next;return rule||null}(cursor)||Rule.empty,tagCls=function(highlighters,tags){let result=null;for(let highlighter of highlighters){let value=highlighter.style(tags);value&&(result=result?result+" "+value:value)}return result}(highlighters,rule.tags);if(tagCls&&(cls&&(cls+=" "),cls+=tagCls,1==rule.mode&&(inheritedClass+=(inheritedClass?" ":"")+tagCls)),this.startSpan(Math.max(from,start),cls),rule.opaque)return;let mounted=cursor.tree&&cursor.tree.prop(NodeProp.mounted);if(mounted&&mounted.overlay){let inner=cursor.node.enter(mounted.overlay[0].from+start,1),innerHighlighters=this.highlighters.filter((h=>!h.scope||h.scope(mounted.tree.type))),hasChild=cursor.firstChild();for(let i=0,pos=start;;i++){let next=i=nextPos)&&cursor.nextSibling()););if(!next||nextPos>to)break;pos=next.to+start,pos>from&&(this.highlightRange(inner.cursor(),Math.max(from,next.from+start),Math.min(to,pos),"",innerHighlighters),this.startSpan(Math.min(to,pos),cls))}hasChild&&cursor.parent()}else if(cursor.firstChild()){mounted&&(inheritedClass="");do{if(!(cursor.to<=from)){if(cursor.from>=to)break;this.highlightRange(cursor,from,to,inheritedClass,highlighters),this.startSpan(Math.min(to,cursor.to),cls)}}while(cursor.nextSibling());cursor.parent()}}}const t=Tag.define,comment$1=t(),name=t(),typeName=t(name),propertyName=t(name),literal=t(),string=t(literal),number=t(literal),content=t(),heading=t(content),keyword=t(),operator=t(),punctuation=t(),bracket=t(punctuation),meta=t(),tags$1={comment:comment$1,lineComment:t(comment$1),blockComment:t(comment$1),docComment:t(comment$1),name:name,variableName:t(name),typeName:typeName,tagName:t(typeName),propertyName:propertyName,attributeName:t(propertyName),className:t(name),labelName:t(name),namespace:t(name),macroName:t(name),literal:literal,string:string,docString:t(string),character:t(string),attributeValue:t(string),number:number,integer:t(number),float:t(number),bool:t(literal),regexp:t(literal),escape:t(literal),color:t(literal),url:t(literal),keyword:keyword,self:t(keyword),null:t(keyword),atom:t(keyword),unit:t(keyword),modifier:t(keyword),operatorKeyword:t(keyword),controlKeyword:t(keyword),definitionKeyword:t(keyword),moduleKeyword:t(keyword),operator:operator,derefOperator:t(operator),arithmeticOperator:t(operator),logicOperator:t(operator),bitwiseOperator:t(operator),compareOperator:t(operator),updateOperator:t(operator),definitionOperator:t(operator),typeOperator:t(operator),controlOperator:t(operator),punctuation:punctuation,separator:t(punctuation),bracket:bracket,angleBracket:t(bracket),squareBracket:t(bracket),paren:t(bracket),brace:t(bracket),content:content,heading:heading,heading1:t(heading),heading2:t(heading),heading3:t(heading),heading4:t(heading),heading5:t(heading),heading6:t(heading),contentSeparator:t(content),list:t(content),quote:t(content),emphasis:t(content),strong:t(content),link:t(content),monospace:t(content),strikethrough:t(content),inserted:t(),deleted:t(),changed:t(),invalid:t(),meta:meta,documentMeta:t(meta),annotation:t(meta),processingInstruction:t(meta),definition:Tag.defineModifier(),constant:Tag.defineModifier(),function:Tag.defineModifier(),standard:Tag.defineModifier(),local:Tag.defineModifier(),special:Tag.defineModifier()};var _a;tagHighlighter([{tag:tags$1.link,class:"tok-link"},{tag:tags$1.heading,class:"tok-heading"},{tag:tags$1.emphasis,class:"tok-emphasis"},{tag:tags$1.strong,class:"tok-strong"},{tag:tags$1.keyword,class:"tok-keyword"},{tag:tags$1.atom,class:"tok-atom"},{tag:tags$1.bool,class:"tok-bool"},{tag:tags$1.url,class:"tok-url"},{tag:tags$1.labelName,class:"tok-labelName"},{tag:tags$1.inserted,class:"tok-inserted"},{tag:tags$1.deleted,class:"tok-deleted"},{tag:tags$1.literal,class:"tok-literal"},{tag:tags$1.string,class:"tok-string"},{tag:tags$1.number,class:"tok-number"},{tag:[tags$1.regexp,tags$1.escape,tags$1.special(tags$1.string)],class:"tok-string2"},{tag:tags$1.variableName,class:"tok-variableName"},{tag:tags$1.local(tags$1.variableName),class:"tok-variableName tok-local"},{tag:tags$1.definition(tags$1.variableName),class:"tok-variableName tok-definition"},{tag:tags$1.special(tags$1.variableName),class:"tok-variableName2"},{tag:tags$1.definition(tags$1.propertyName),class:"tok-propertyName tok-definition"},{tag:tags$1.typeName,class:"tok-typeName"},{tag:tags$1.namespace,class:"tok-namespace"},{tag:tags$1.className,class:"tok-className"},{tag:tags$1.macroName,class:"tok-macroName"},{tag:tags$1.propertyName,class:"tok-propertyName"},{tag:tags$1.operator,class:"tok-operator"},{tag:tags$1.comment,class:"tok-comment"},{tag:tags$1.meta,class:"tok-meta"},{tag:tags$1.invalid,class:"tok-invalid"},{tag:tags$1.punctuation,class:"tok-punctuation"}]);const languageDataProp=new NodeProp;function defineLanguageFacet(baseData){return Facet.define({combine:baseData?values=>values.concat(baseData):void 0})}const sublanguageProp=new NodeProp;class Language{constructor(data,parser){let extraExtensions=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],name=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"";this.data=data,this.name=name,EditorState.prototype.hasOwnProperty("tree")||Object.defineProperty(EditorState.prototype,"tree",{get(){return syntaxTree(this)}}),this.parser=parser,this.extension=[language.of(this),EditorState.languageData.of(((state,pos,side)=>{let top=topNodeAt(state,pos,side),data=top.type.prop(languageDataProp);if(!data)return[];let base=state.facet(data),sub=top.type.prop(sublanguageProp);if(sub){let innerNode=top.resolve(pos-top.from,side);for(let sublang of sub)if(sublang.test(innerNode,state)){let data=state.facet(sublang.facet);return"replace"==sublang.type?data:data.concat(base)}}return base}))].concat(extraExtensions)}isActiveAt(state,pos){return topNodeAt(state,pos,arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1).type.prop(languageDataProp)==this.data}findRegions(state){let lang=state.facet(language);if((null==lang?void 0:lang.data)==this.data)return[{from:0,to:state.doc.length}];if(!lang||!lang.allowsNesting)return[];let result=[],explore=(tree,from)=>{if(tree.prop(languageDataProp)==this.data)return void result.push({from:from,to:from+tree.length});let mount=tree.prop(NodeProp.mounted);if(mount){if(mount.tree.prop(languageDataProp)==this.data){if(mount.overlay)for(let r of mount.overlay)result.push({from:r.from+from,to:r.to+from});else result.push({from:from,to:from+tree.length});return}if(mount.overlay){let size=result.length;if(explore(mount.tree,mount.overlay[0].from+from),result.length>size)return}}for(let i=0;itype.isTop?data:void 0))]}),spec.name)}configure(options,name){return new LRLanguage(this.data,this.parser.configure(options),name||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function syntaxTree(state){let field=state.field(Language.state,!1);return field?field.tree:Tree.empty}class DocInput{constructor(doc){this.doc=doc,this.cursorPos=0,this.string="",this.cursor=doc.iter()}get length(){return this.doc.length}syncTo(pos){return this.string=this.cursor.next(pos-this.cursorPos).value,this.cursorPos=pos+this.string.length,this.cursorPos-this.string.length}chunk(pos){return this.syncTo(pos),this.string}get lineChunks(){return!0}read(from,to){let stringStart=this.cursorPos-this.string.length;return from=this.cursorPos?this.doc.sliceString(from,to):this.string.slice(from-stringStart,to-stringStart)}}let currentContext=null;class ParseContext{constructor(parser,state){let fragments=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],tree=arguments.length>3?arguments[3]:void 0,treeLen=arguments.length>4?arguments[4]:void 0,viewport=arguments.length>5?arguments[5]:void 0,skipped=arguments.length>6?arguments[6]:void 0,scheduleOn=arguments.length>7?arguments[7]:void 0;this.parser=parser,this.state=state,this.fragments=fragments,this.tree=tree,this.treeLen=treeLen,this.viewport=viewport,this.skipped=skipped,this.scheduleOn=scheduleOn,this.parse=null,this.tempSkipped=[]}static create(parser,state,viewport){return new ParseContext(parser,state,[],Tree.empty,0,viewport,[],null)}startParse(){return this.parser.startParse(new DocInput(this.state.doc),this.fragments)}work(until,upto){return null!=upto&&upto>=this.state.doc.length&&(upto=void 0),this.tree!=Tree.empty&&this.isDone(null!=upto?upto:this.state.doc.length)?(this.takeTree(),!0):this.withContext((()=>{var _a;if("number"==typeof until){let endTime=Date.now()+until;until=()=>Date.now()>endTime}for(this.parse||(this.parse=this.startParse()),null!=upto&&(null==this.parse.stoppedAt||this.parse.stoppedAt>upto)&&upto=this.treeLen&&((null==this.parse.stoppedAt||this.parse.stoppedAt>pos)&&this.parse.stopAt(pos),this.withContext((()=>{for(;!(tree=this.parse.advance()););})),this.treeLen=pos,this.tree=tree,this.fragments=this.withoutTempSkipped(TreeFragment.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(f){let prev=currentContext;currentContext=this;try{return f()}finally{currentContext=prev}}withoutTempSkipped(fragments){for(let r;r=this.tempSkipped.pop();)fragments=cutFragments(fragments,r.from,r.to);return fragments}changes(changes,newState){let{fragments:fragments,tree:tree,treeLen:treeLen,viewport:viewport,skipped:skipped}=this;if(this.takeTree(),!changes.empty){let ranges=[];if(changes.iterChangedRanges(((fromA,toA,fromB,toB)=>ranges.push({fromA:fromA,toA:toA,fromB:fromB,toB:toB}))),fragments=TreeFragment.applyChanges(fragments,ranges),tree=Tree.empty,treeLen=0,viewport={from:changes.mapPos(viewport.from,-1),to:changes.mapPos(viewport.to,1)},this.skipped.length){skipped=[];for(let r of this.skipped){let from=changes.mapPos(r.from,1),to=changes.mapPos(r.to,-1);fromviewport.from&&(this.fragments=cutFragments(this.fragments,from,to),this.skipped.splice(i--,1))}return!(this.skipped.length>=startLen)&&(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(from,to){this.skipped.push({from:from,to:to})}static getSkippingParser(until){return new class extends Parser{createParse(input,fragments,ranges){let from=ranges[0].from,to=ranges[ranges.length-1].to;return{parsedPos:from,advance(){let cx=currentContext;if(cx){for(let r of ranges)cx.tempSkipped.push(r);until&&(cx.scheduleOn=cx.scheduleOn?Promise.all([cx.scheduleOn,until]):until)}return this.parsedPos=to,new Tree(NodeType.none,[],[],to-from)},stoppedAt:null,stopAt(){}}}}}isDone(upto){upto=Math.min(upto,this.state.doc.length);let frags=this.fragments;return this.treeLen>=upto&&frags.length&&0==frags[0].from&&frags[0].to>=upto}static get(){return currentContext}}function cutFragments(fragments,from,to){return TreeFragment.applyChanges(fragments,[{fromA:from,toA:to,fromB:from,toB:to}])}class LanguageState{constructor(context){this.context=context,this.tree=context.tree}apply(tr){if(!tr.docChanged&&this.tree==this.context.tree)return this;let newCx=this.context.changes(tr.changes,tr.state),upto=this.context.treeLen==tr.startState.doc.length?void 0:Math.max(tr.changes.mapPos(this.context.treeLen),newCx.viewport.to);return newCx.work(20,upto)||newCx.takeTree(),new LanguageState(newCx)}static init(state){let vpTo=Math.min(3e3,state.doc.length),parseState=ParseContext.create(state.facet(language).parser,state,{from:0,to:vpTo});return parseState.work(20,vpTo)||parseState.takeTree(),new LanguageState(parseState)}}Language.state=StateField.define({create:LanguageState.init,update(value,tr){for(let e of tr.effects)if(e.is(Language.setState))return e.value;return tr.startState.facet(language)!=tr.state.facet(language)?LanguageState.init(tr.state):value.apply(tr)}});let requestIdle=callback=>{let timeout=setTimeout((()=>callback()),500);return()=>clearTimeout(timeout)};"undefined"!=typeof requestIdleCallback&&(requestIdle=callback=>{let idle=-1,timeout=setTimeout((()=>{idle=requestIdleCallback(callback,{timeout:400})}),100);return()=>idle<0?clearTimeout(timeout):cancelIdleCallback(idle)});const isInputPending="undefined"!=typeof navigator&&(null===(_a=navigator.scheduling)||void 0===_a?void 0:_a.isInputPending)?()=>navigator.scheduling.isInputPending():null,parseWorker=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(update){let cx=this.view.state.field(Language.state).context;(cx.updateViewport(update.view.viewport)||this.view.viewport.to>cx.treeLen)&&this.scheduleWork(),update.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(cx)}scheduleWork(){if(this.working)return;let{state:state}=this.view,field=state.field(Language.state);field.tree==field.context.tree&&field.context.isDone(state.doc.length)||(this.working=requestIdle(this.work))}work(deadline){this.working=null;let now=Date.now();if(this.chunkEndvpTo+1e3,done=field.context.work((()=>isInputPending&&isInputPending()||Date.now()>endTime),vpTo+(viewportFirst?0:1e5));this.chunkBudget-=Date.now()-now,(done||this.chunkBudget<=0)&&(field.context.takeTree(),this.view.dispatch({effects:Language.setState.of(new LanguageState(field.context))})),this.chunkBudget>0&&(!done||viewportFirst)&&this.scheduleWork(),this.checkAsyncSchedule(field.context)}checkAsyncSchedule(cx){cx.scheduleOn&&(this.workScheduled++,cx.scheduleOn.then((()=>this.scheduleWork())).catch((err=>logException(this.view.state,err))).then((()=>this.workScheduled--)),cx.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),language=Facet.define({combine:languages=>languages.length?languages[0]:null,enables:language=>[Language.state,parseWorker,EditorView.contentAttributes.compute([language],(state=>{let lang=state.facet(language);return lang&&lang.name?{"data-language":lang.name}:{}}))]});class LanguageSupport{constructor(language){let support=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];this.language=language,this.support=support,this.extension=[language,support]}}const indentService=Facet.define(),indentUnit=Facet.define({combine:values=>{if(!values.length)return" ";let unit=values[0];if(!unit||/\S/.test(unit)||Array.from(unit).some((e=>e!=unit[0])))throw new Error("Invalid indent unit: "+JSON.stringify(values[0]));return unit}});function getIndentUnit(state){let unit=state.facet(indentUnit);return 9==unit.charCodeAt(0)?state.tabSize*unit.length:unit.length}function indentString(state,cols){let result="",ts=state.tabSize,ch=state.facet(indentUnit)[0];if("\t"==ch){for(;cols>=ts;)result+="\t",cols-=ts;ch=" "}for(let i=0;i1&&void 0!==arguments[1]?arguments[1]:{};this.state=state,this.options=options,this.unit=getIndentUnit(state)}lineAt(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,line=this.state.doc.lineAt(pos),{simulateBreak:simulateBreak,simulateDoubleBreak:simulateDoubleBreak}=this.options;return null!=simulateBreak&&simulateBreak>=line.from&&simulateBreak<=line.to?simulateDoubleBreak&&simulateBreak==pos?{text:"",from:pos}:(bias<0?simulateBreak1&&void 0!==arguments[1]?arguments[1]:1;if(this.options.simulateDoubleBreak&&pos==this.options.simulateBreak)return"";let{text:text,from:from}=this.lineAt(pos,bias);return text.slice(pos-from,Math.min(text.length,pos+100-from))}column(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,{text:text,from:from}=this.lineAt(pos,bias),result=this.countColumn(text,pos-from),override=this.options.overrideIndentation?this.options.overrideIndentation(from):-1;return override>-1&&(result+=override-this.countColumn(text,text.search(/\S|$/))),result}countColumn(line){let pos=arguments.length>1&&void 0!==arguments[1]?arguments[1]:line.length;return countColumn(line,this.state.tabSize,pos)}lineIndent(pos){let bias=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,{text:text,from:from}=this.lineAt(pos,bias),override=this.options.overrideIndentation;if(override){let overriden=override(from);if(overriden>-1)return overriden}return this.countColumn(text,text.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const indentNodeProp=new NodeProp;function indentStrategy(tree){let strategy=tree.type.prop(indentNodeProp);if(strategy)return strategy;let close,first=tree.firstChild;if(first&&(close=first.type.prop(NodeProp.closedBy))){let last=tree.lastChild,closed=last&&close.indexOf(last.name)>-1;return cx=>delimitedStrategy(cx,!0,1,void 0,closed&&!function(cx){return cx.pos==cx.options.simulateBreak&&cx.options.simulateDoubleBreak}(cx)?last.from:void 0)}return null==tree.parent?topIndent:null}function indentFrom(node,pos,base){for(;node;node=node.parent){let strategy=indentStrategy(node);if(strategy)return strategy(TreeIndentContext.create(base,pos,node))}return null}function topIndent(){return 0}class TreeIndentContext extends IndentContext{constructor(base,pos,node){super(base.state,base.options),this.base=base,this.pos=pos,this.node=node}static create(base,pos,node){return new TreeIndentContext(base,pos,node)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(node){let line=this.state.doc.lineAt(node.from);for(;;){let atBreak=node.resolve(line.from);for(;atBreak.parent&&atBreak.parent.from==atBreak.from;)atBreak=atBreak.parent;if(isParent(atBreak,node))break;line=this.state.doc.lineAt(atBreak.from)}return this.lineIndent(line.from)}continue(){let parent=this.node.parent;return parent?indentFrom(parent,this.pos,this.base):0}}function isParent(parent,of){for(let cur=of;cur;cur=cur.parent)if(parent==cur)return!0;return!1}function delimitedStrategy(context,align,units,closing,closedAt){let after=context.textAfter,space=after.match(/^\s*/)[0].length,closed=closing&&after.slice(space,space+closing.length)==closing||closedAt==context.pos+space,aligned=align?function(context){let tree=context.node,openToken=tree.childAfter(tree.from),last=tree.lastChild;if(!openToken)return null;let sim=context.options.simulateBreak,openLine=context.state.doc.lineAt(openToken.from),lineEnd=null==sim||sim<=openLine.from?openLine.to:Math.min(openLine.to,sim);for(let pos=openToken.to;;){let next=tree.childAfter(pos);if(!next||next==last)return null;if(!next.type.isSkipped)return next.from0&&void 0!==arguments[0]?arguments[0]:{};return context=>{let matchExcept=except&&except.test(context.textAfter);return context.baseIndent+(matchExcept?0:units*context.unit)}}const foldService=Facet.define(),foldNodeProp=new NodeProp;function foldInside(node){let first=node.firstChild,last=node.lastChild;return first&&first.toend)continue;if(found&&cur.from=start&&value.to>end&&(found=value)}}return found}(state,lineStart,lineEnd)}function mapRange(range,mapping){let from=mapping.mapPos(range.from,1),to=mapping.mapPos(range.to,-1);return from>=to?void 0:{from:from,to:to}}const foldEffect=StateEffect.define({map:mapRange}),unfoldEffect=StateEffect.define({map:mapRange});function selectedLines(view){let lines=[];for(let{head:head}of view.state.selection.ranges)lines.some((l=>l.from<=head&&l.to>=head))||lines.push(view.lineBlockAt(head));return lines}const foldState=StateField.define({create:()=>Decoration.none,update(folded,tr){folded=folded.map(tr.changes);for(let e of tr.effects)e.is(foldEffect)&&!foldExists(folded,e.value.from,e.value.to)?folded=folded.update({add:[foldWidget.range(e.value.from,e.value.to)]}):e.is(unfoldEffect)&&(folded=folded.update({filter:(from,to)=>e.value.from!=from||e.value.to!=to,filterFrom:e.value.from,filterTo:e.value.to}));if(tr.selection){let onSelection=!1,{head:head}=tr.selection.main;folded.between(head,head,((a,b)=>{ahead&&(onSelection=!0)})),onSelection&&(folded=folded.update({filterFrom:head,filterTo:head,filter:(a,b)=>b<=head||a>=head}))}return folded},provide:f=>EditorView.decorations.from(f),toJSON(folded,state){let ranges=[];return folded.between(0,state.doc.length,((from,to)=>{ranges.push(from,to)})),ranges},fromJSON(value){if(!Array.isArray(value)||value.length%2)throw new RangeError("Invalid JSON for fold state");let ranges=[];for(let i=0;i{(!found||found.from>from)&&(found={from:from,to:to})})),found}function foldExists(folded,from,to){let found=!1;return folded.between(from,from,((a,b)=>{a==from&&b==to&&(found=!0)})),found}function maybeEnable(state,other){return state.field(foldState,!1)?other:other.concat(StateEffect.appendConfig.of(codeFolding()))}function announceFold(view,range){let fold=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],lineFrom=view.state.doc.lineAt(range.from).number,lineTo=view.state.doc.lineAt(range.to).number;return EditorView.announce.of("".concat(view.state.phrase(fold?"Folded lines":"Unfolded lines")," ").concat(lineFrom," ").concat(view.state.phrase("to")," ").concat(lineTo,"."))}const foldKeymap=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:view=>{for(let line of selectedLines(view)){let range=foldable(view.state,line.from,line.to);if(range)return view.dispatch({effects:maybeEnable(view.state,[foldEffect.of(range),announceFold(view,range)])}),!0}return!1}},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:view=>{if(!view.state.field(foldState,!1))return!1;let effects=[];for(let line of selectedLines(view)){let folded=findFold(view.state,line.from,line.to);folded&&effects.push(unfoldEffect.of(folded),announceFold(view,folded,!1))}return effects.length&&view.dispatch({effects:effects}),effects.length>0}},{key:"Ctrl-Alt-[",run:view=>{let{state:state}=view,effects=[];for(let pos=0;pos{let field=view.state.field(foldState,!1);if(!field||!field.size)return!1;let effects=[];return field.between(0,view.state.doc.length,((from,to)=>{effects.push(unfoldEffect.of({from:from,to:to}))})),view.dispatch({effects:effects}),!0}}],defaultConfig={placeholderDOM:null,placeholderText:"…"},foldConfig=Facet.define({combine:values=>combineConfig(values,defaultConfig)});function codeFolding(config){let result=[foldState,baseTheme$1$2];return config&&result.push(foldConfig.of(config)),result}const foldWidget=Decoration.replace({widget:new class extends WidgetType{toDOM(view){let{state:state}=view,conf=state.facet(foldConfig),onclick=event=>{let line=view.lineBlockAt(view.posAtDOM(event.target)),folded=findFold(view.state,line.from,line.to);folded&&view.dispatch({effects:unfoldEffect.of(folded)}),event.preventDefault()};if(conf.placeholderDOM)return conf.placeholderDOM(view,onclick);let element=document.createElement("span");return element.textContent=conf.placeholderText,element.setAttribute("aria-label",state.phrase("folded code")),element.title=state.phrase("unfold"),element.className="cm-foldPlaceholder",element.onclick=onclick,element}}}),foldGutterDefaults={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class FoldMarker extends GutterMarker{constructor(config,open){super(),this.config=config,this.open=open}eq(other){return this.config==other.config&&this.open==other.open}toDOM(view){if(this.config.markerDOM)return this.config.markerDOM(this.open);let span=document.createElement("span");return span.textContent=this.open?this.config.openText:this.config.closedText,span.title=view.state.phrase(this.open?"Fold line":"Unfold line"),span}}function foldGutter(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},fullConfig=Object.assign(Object.assign({},foldGutterDefaults),config),canFold=new FoldMarker(fullConfig,!0),canUnfold=new FoldMarker(fullConfig,!1),markers=ViewPlugin.fromClass(class{constructor(view){this.from=view.viewport.from,this.markers=this.buildMarkers(view)}update(update){(update.docChanged||update.viewportChanged||update.startState.facet(language)!=update.state.facet(language)||update.startState.field(foldState,!1)!=update.state.field(foldState,!1)||syntaxTree(update.startState)!=syntaxTree(update.state)||fullConfig.foldingChanged(update))&&(this.markers=this.buildMarkers(update.view))}buildMarkers(view){let builder=new RangeSetBuilder;for(let line of view.viewportLineBlocks){let mark=findFold(view.state,line.from,line.to)?canUnfold:foldable(view.state,line.from,line.to)?canFold:null;mark&&builder.add(line.from,line.from,mark)}return builder.finish()}}),{domEventHandlers:domEventHandlers}=fullConfig;return[markers,gutter({class:"cm-foldGutter",markers(view){var _a;return(null===(_a=view.plugin(markers))||void 0===_a?void 0:_a.markers)||RangeSet.empty},initialSpacer:()=>new FoldMarker(fullConfig,!1),domEventHandlers:Object.assign(Object.assign({},domEventHandlers),{click:(view,line,event)=>{if(domEventHandlers.click&&domEventHandlers.click(view,line,event))return!0;let folded=findFold(view.state,line.from,line.to);if(folded)return view.dispatch({effects:unfoldEffect.of(folded)}),!0;let range=foldable(view.state,line.from,line.to);return!!range&&(view.dispatch({effects:foldEffect.of(range)}),!0)}})}),codeFolding()]}const baseTheme$1$2=EditorView.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class HighlightStyle{constructor(specs,options){let modSpec;function def(spec){let cls=StyleModule.newName();return(modSpec||(modSpec=Object.create(null)))["."+cls]=spec,cls}this.specs=specs;const all="string"==typeof options.all?options.all:options.all?def(options.all):void 0,scopeOpt=options.scope;this.scope=scopeOpt instanceof Language?type=>type.prop(languageDataProp)==scopeOpt.data:scopeOpt?type=>type==scopeOpt:void 0,this.style=tagHighlighter(specs.map((style=>({tag:style.tag,class:style.class||def(Object.assign({},style,{tag:null}))}))),{all:all}).style,this.module=modSpec?new StyleModule(modSpec):null,this.themeType=options.themeType}static define(specs,options){return new HighlightStyle(specs,options||{})}}const highlighterFacet=Facet.define(),fallbackHighlighter=Facet.define({combine:values=>values.length?[values[0]]:null});function getHighlighters(state){let main=state.facet(highlighterFacet);return main.length?main:state.facet(fallbackHighlighter)}function syntaxHighlighting(highlighter,options){let themeType,ext=[treeHighlighter];return highlighter instanceof HighlightStyle&&(highlighter.module&&ext.push(EditorView.styleModule.of(highlighter.module)),themeType=highlighter.themeType),(null==options?void 0:options.fallback)?ext.push(fallbackHighlighter.of(highlighter)):themeType?ext.push(highlighterFacet.computeN([EditorView.darkTheme],(state=>state.facet(EditorView.darkTheme)==("dark"==themeType)?[highlighter]:[]))):ext.push(highlighterFacet.of(highlighter)),ext}const treeHighlighter=Prec.high(ViewPlugin.fromClass(class{constructor(view){this.markCache=Object.create(null),this.tree=syntaxTree(view.state),this.decorations=this.buildDeco(view,getHighlighters(view.state))}update(update){let tree=syntaxTree(update.state),highlighters=getHighlighters(update.state),styleChange=highlighters!=getHighlighters(update.startState);tree.length{builder.add(from,to,this.markCache[style]||(this.markCache[style]=Decoration.mark({class:style})))}),from,to);return builder.finish()}},{decorations:v=>v.decorations})),defaultHighlightStyle=HighlightStyle.define([{tag:tags$1.meta,color:"#404740"},{tag:tags$1.link,textDecoration:"underline"},{tag:tags$1.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tags$1.emphasis,fontStyle:"italic"},{tag:tags$1.strong,fontWeight:"bold"},{tag:tags$1.strikethrough,textDecoration:"line-through"},{tag:tags$1.keyword,color:"#708"},{tag:[tags$1.atom,tags$1.bool,tags$1.url,tags$1.contentSeparator,tags$1.labelName],color:"#219"},{tag:[tags$1.literal,tags$1.inserted],color:"#164"},{tag:[tags$1.string,tags$1.deleted],color:"#a11"},{tag:[tags$1.regexp,tags$1.escape,tags$1.special(tags$1.string)],color:"#e40"},{tag:tags$1.definition(tags$1.variableName),color:"#00f"},{tag:tags$1.local(tags$1.variableName),color:"#30a"},{tag:[tags$1.typeName,tags$1.namespace],color:"#085"},{tag:tags$1.className,color:"#167"},{tag:[tags$1.special(tags$1.variableName),tags$1.macroName],color:"#256"},{tag:tags$1.definition(tags$1.propertyName),color:"#00c"},{tag:tags$1.comment,color:"#940"},{tag:tags$1.invalid,color:"#f00"}]),baseTheme$3=EditorView.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),bracketMatchingConfig=Facet.define({combine:configs=>combineConfig(configs,{afterCursor:!0,brackets:"()[]{}",maxScanDistance:1e4,renderMatch:defaultRenderMatch})}),matchingMark=Decoration.mark({class:"cm-matchingBracket"}),nonmatchingMark=Decoration.mark({class:"cm-nonmatchingBracket"});function defaultRenderMatch(match){let decorations=[],mark=match.matched?matchingMark:nonmatchingMark;return decorations.push(mark.range(match.start.from,match.start.to)),match.end&&decorations.push(mark.range(match.end.from,match.end.to)),decorations}const bracketMatchingState=StateField.define({create:()=>Decoration.none,update(deco,tr){if(!tr.docChanged&&!tr.selection)return deco;let decorations=[],config=tr.state.facet(bracketMatchingConfig);for(let range of tr.state.selection.ranges){if(!range.empty)continue;let match=matchBrackets(tr.state,range.head,-1,config)||range.head>0&&matchBrackets(tr.state,range.head-1,1,config)||config.afterCursor&&(matchBrackets(tr.state,range.head,1,config)||range.headEditorView.decorations.from(f)}),bracketMatchingUnique=[bracketMatchingState,baseTheme$3];function bracketMatching(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[bracketMatchingConfig.of(config),bracketMatchingUnique]}const bracketMatchingHandle=new NodeProp;function matchingNodes(node,dir,brackets){let byProp=node.prop(dir<0?NodeProp.openedBy:NodeProp.closedBy);if(byProp)return byProp;if(1==node.name.length){let index=brackets.indexOf(node.name);if(index>-1&&index%2==(dir<0?1:0))return[brackets[index+dir]]}return null}function findHandle(node){let hasHandle=node.type.prop(bracketMatchingHandle);return hasHandle?hasHandle(node.node):node}function matchBrackets(state,pos,dir){let config=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},maxScanDistance=config.maxScanDistance||1e4,brackets=config.brackets||"()[]{}",tree=syntaxTree(state),node=tree.resolveInner(pos,dir);for(let cur=node;cur;cur=cur.parent){let matches=matchingNodes(cur.type,dir,brackets);if(matches&&cur.from0?pos>=handle.from&&poshandle.from&&pos<=handle.to))return matchMarkedBrackets(state,pos,dir,cur,handle,matches,brackets)}}return matchPlainBrackets(state,pos,dir,tree,node.type,maxScanDistance,brackets)}function matchMarkedBrackets(_state,_pos,dir,token,handle,matching,brackets){let parent=token.parent,firstToken={from:handle.from,to:handle.to},depth=0,cursor=null==parent?void 0:parent.cursor();if(cursor&&(dir<0?cursor.childBefore(token.from):cursor.childAfter(token.to)))do{if(dir<0?cursor.to<=token.from:cursor.from>=token.to){if(0==depth&&matching.indexOf(cursor.type.name)>-1&&cursor.from0)return null;let startToken={from:dir<0?pos-1:pos,to:dir>0?pos+1:pos},iter=state.doc.iterRange(pos,dir>0?state.doc.length:0),depth=0;for(let distance=0;!iter.next().done&&distance<=maxScanDistance;){let text=iter.value;dir<0&&(distance+=text.length);let basePos=pos+distance*dir;for(let pos=dir>0?0:text.length-1,end=dir>0?text.length:-1;pos!=end;pos+=dir){let found=brackets.indexOf(text[pos]);if(!(found<0||tree.resolveInner(basePos+pos,1).type!=tokenType))if(found%2==0==dir>0)depth++;else{if(1==depth)return{start:startToken,end:{from:basePos+pos,to:basePos+pos+1},matched:found>>1==bracket>>1};depth--}}dir>0&&(distance+=text.length)}return iter.done?{start:startToken,matched:!1}:null}const noTokens=Object.create(null),typeArray=[NodeType.none],warned=[],defaultTable=Object.create(null);for(let[legacyName,name]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])defaultTable[legacyName]=createTokenType(noTokens,name);function warnForPart(part,msg){warned.indexOf(part)>-1||(warned.push(part),console.warn(msg))}function createTokenType(extra,tagStr){let tag=null;for(let part of tagStr.split(".")){let value=extra[part]||tags$1[part];value?"function"==typeof value?tag?tag=value(tag):warnForPart(part,"Modifier ".concat(part," used at start of tag")):tag?warnForPart(part,"Tag ".concat(part," used as modifier")):tag=value:warnForPart(part,"Unknown highlighting tag ".concat(part))}if(!tag)return 0;let name=tagStr.replace(/ /g,"_"),type=NodeType.define({id:typeArray.length,name:name,props:[styleTags({[name]:tag})]});return typeArray.push(type),type.id}function command(f,option){return _ref9=>{let{state:state,dispatch:dispatch}=_ref9;if(state.readOnly)return!1;let tr=f(option,state);return!!tr&&(dispatch(state.update(tr)),!0)}}const toggleLineComment=command((function(option,state){let ranges=arguments.length>2&&void 0!==arguments[2]?arguments[2]:state.selection.ranges,lines=[],prevLine=-1;for(let{from:from,to:to}of ranges){let startI=lines.length,minIndent=1e9,token=getConfig(state,from).line;if(token){for(let pos=from;pos<=to;){let line=state.doc.lineAt(pos);if(line.from>prevLine&&(from==to||to>line.from)){prevLine=line.from;let indent=/^\s*/.exec(line.text)[0].length,empty=indent==line.length,comment=line.text.slice(indent,indent+token.length)==token?indent:-1;indentl.comment<0&&(!l.empty||l.single)))){let changes=[];for(let{line:line,token:token,indent:indent,empty:empty,single:single}of lines)!single&&empty||changes.push({from:line.from+indent,insert:token+" "});let changeSet=state.changes(changes);return{changes:changeSet,selection:state.selection.map(changeSet,1)}}if(1!=option&&lines.some((l=>l.comment>=0))){let changes=[];for(let{line:line,comment:comment,token:token}of lines)if(comment>=0){let from=line.from+comment,to=from+token.length;" "==line.text[to-line.from]&&to++,changes.push({from:from,to:to})}return{changes:changes}}return null}),0),toggleBlockComment=command(changeBlockComment,0),toggleBlockCommentByLine=command(((o,s)=>changeBlockComment(o,s,function(state){let ranges=[];for(let r of state.selection.ranges){let fromLine=state.doc.lineAt(r.from),toLine=r.to<=fromLine.to?fromLine:state.doc.lineAt(r.to),last=ranges.length-1;last>=0&&ranges[last].to>fromLine.from?ranges[last].to=toLine.to:ranges.push({from:fromLine.from+/^\s*/.exec(fromLine.text)[0].length,to:toLine.to})}return ranges}(s))),0);function getConfig(state,pos){let data=state.languageDataAt("commentTokens",pos);return data.length?data[0]:{}}function findBlockComment(state,_ref10,from,to){let startText,endText,{open:open,close:close}=_ref10,textBefore=state.sliceDoc(from-50,from),textAfter=state.sliceDoc(to,to+50),spaceBefore=/\s*$/.exec(textBefore)[0].length,spaceAfter=/^\s*/.exec(textAfter)[0].length,beforeOff=textBefore.length-spaceBefore;if(textBefore.slice(beforeOff-open.length,beforeOff)==open&&textAfter.slice(spaceAfter,spaceAfter+close.length)==close)return{open:{pos:from-spaceBefore,margin:spaceBefore&&1},close:{pos:to+spaceAfter,margin:spaceAfter&&1}};to-from<=100?startText=endText=state.sliceDoc(from,to):(startText=state.sliceDoc(from,from+50),endText=state.sliceDoc(to-50,to));let startSpace=/^\s*/.exec(startText)[0].length,endSpace=/\s*$/.exec(endText)[0].length,endOff=endText.length-endSpace-close.length;return startText.slice(startSpace,startSpace+open.length)==open&&endText.slice(endOff,endOff+close.length)==close?{open:{pos:from+startSpace+open.length,margin:/\s/.test(startText.charAt(startSpace+open.length))?1:0},close:{pos:to-endSpace-close.length,margin:/\s/.test(endText.charAt(endOff-1))?1:0}}:null}function changeBlockComment(option,state){let ranges=arguments.length>2&&void 0!==arguments[2]?arguments[2]:state.selection.ranges,tokens=ranges.map((r=>getConfig(state,r.from).block));if(!tokens.every((c=>c)))return null;let comments=ranges.map(((r,i)=>findBlockComment(state,tokens[i],r.from,r.to)));if(2!=option&&!comments.every((c=>c)))return{changes:state.changes(ranges.map(((range,i)=>comments[i]?[]:[{from:range.from,insert:tokens[i].open+" "},{from:range.to,insert:" "+tokens[i].close}])))};if(1!=option&&comments.some((c=>c))){let changes=[];for(let comment,i=0;icombineConfig(configs,{minDepth:100,newGroupDelay:500,joinToEvent:(_t,isAdjacent)=>isAdjacent},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(a,b)=>(tr,adj)=>a(tr,adj)||b(tr,adj)})});const historyField_=StateField.define({create:()=>HistoryState.empty,update(state,tr){let config=tr.state.facet(historyConfig),fromHist=tr.annotation(fromHistory);if(fromHist){let selection=tr.docChanged?EditorSelection.single(function(changes){let end=0;return changes.iterChangedRanges(((_,to)=>end=to)),end}(tr.changes)):void 0,item=HistEvent.fromTransaction(tr,selection),from=fromHist.side,other=0==from?state.undone:state.done;return other=item?updateBranch(other,other.length,config.minDepth,item):addSelection(other,tr.startState.selection),new HistoryState(0==from?fromHist.rest:other,0==from?other:fromHist.rest)}let isolate=tr.annotation(isolateHistory);if("full"!=isolate&&"before"!=isolate||(state=state.isolate()),!1===tr.annotation(Transaction.addToHistory))return tr.changes.empty?state:state.addMapping(tr.changes.desc);let event=HistEvent.fromTransaction(tr),time=tr.annotation(Transaction.time),userEvent=tr.annotation(Transaction.userEvent);return event?state=state.addChanges(event,time,userEvent,config,tr):tr.selection&&(state=state.addSelection(tr.startState.selection,time,userEvent,config.newGroupDelay)),"full"!=isolate&&"after"!=isolate||(state=state.isolate()),state},toJSON:value=>({done:value.done.map((e=>e.toJSON())),undone:value.undone.map((e=>e.toJSON()))}),fromJSON:json=>new HistoryState(json.done.map(HistEvent.fromJSON),json.undone.map(HistEvent.fromJSON))});function history(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[historyField_,historyConfig.of(config),EditorView.domEventHandlers({beforeinput(e,view){let command="historyUndo"==e.inputType?undo:"historyRedo"==e.inputType?redo:null;return!!command&&(e.preventDefault(),command(view))}})]}function cmd(side,selection){return function(_ref11){let{state:state,dispatch:dispatch}=_ref11;if(!selection&&state.readOnly)return!1;let historyState=state.field(historyField_,!1);if(!historyState)return!1;let tr=historyState.pop(side,state,selection);return!!tr&&(dispatch(tr),!0)}}const undo=cmd(0,!1),redo=cmd(1,!1),undoSelection=cmd(0,!0),redoSelection=cmd(1,!0);class HistEvent{constructor(changes,effects,mapped,startSelection,selectionsAfter){this.changes=changes,this.effects=effects,this.mapped=mapped,this.startSelection=startSelection,this.selectionsAfter=selectionsAfter}setSelAfter(after){return new HistEvent(this.changes,this.effects,this.mapped,this.startSelection,after)}toJSON(){var _a,_b,_c;return{changes:null===(_a=this.changes)||void 0===_a?void 0:_a.toJSON(),mapped:null===(_b=this.mapped)||void 0===_b?void 0:_b.toJSON(),startSelection:null===(_c=this.startSelection)||void 0===_c?void 0:_c.toJSON(),selectionsAfter:this.selectionsAfter.map((s=>s.toJSON()))}}static fromJSON(json){return new HistEvent(json.changes&&ChangeSet.fromJSON(json.changes),[],json.mapped&&ChangeDesc.fromJSON(json.mapped),json.startSelection&&EditorSelection.fromJSON(json.startSelection),json.selectionsAfter.map(EditorSelection.fromJSON))}static fromTransaction(tr,selection){let effects=none$1;for(let invert of tr.startState.facet(invertedEffects)){let result=invert(tr);result.length&&(effects=effects.concat(result))}return!effects.length&&tr.changes.empty?null:new HistEvent(tr.changes.invert(tr.startState.doc),effects,void 0,selection||tr.startState.selection,none$1)}static selection(selections){return new HistEvent(void 0,none$1,void 0,void 0,selections)}}function updateBranch(branch,to,maxLen,newEvent){let start=to+1>maxLen+20?to-maxLen-1:0,newBranch=branch.slice(start,to);return newBranch.push(newEvent),newBranch}function conc(a,b){return a.length?b.length?a.concat(b):a:b}const none$1=[];function addSelection(branch,selection){if(branch.length){let lastEvent=branch[branch.length-1],sels=lastEvent.selectionsAfter.slice(Math.max(0,lastEvent.selectionsAfter.length-200));return sels.length&&sels[sels.length-1].eq(selection)?branch:(sels.push(selection),updateBranch(branch,branch.length-1,1e9,lastEvent.setSelAfter(sels)))}return[HistEvent.selection([selection])]}function popSelection(branch){let last=branch[branch.length-1],newBranch=branch.slice();return newBranch[branch.length-1]=last.setSelAfter(last.selectionsAfter.slice(0,last.selectionsAfter.length-1)),newBranch}function addMappingToBranch(branch,mapping){if(!branch.length)return branch;let length=branch.length,selections=none$1;for(;length;){let event=mapEvent(branch[length-1],mapping,selections);if(event.changes&&!event.changes.empty||event.effects.length){let result=branch.slice(0,length);return result[length-1]=event,result}mapping=event.mapped,length--,selections=event.selectionsAfter}return selections.length?[HistEvent.selection(selections)]:none$1}function mapEvent(event,mapping,extraSelections){let selections=conc(event.selectionsAfter.length?event.selectionsAfter.map((s=>s.map(mapping))):none$1,extraSelections);if(!event.changes)return HistEvent.selection(selections);let mappedChanges=event.changes.map(mapping),before=mapping.mapDesc(event.changes,!0),fullMapping=event.mapped?event.mapped.composeDesc(before):before;return new HistEvent(mappedChanges,StateEffect.mapEffects(event.effects,mapping),fullMapping,event.startSelection.map(before),selections)}const joinableUserEvent=/^(input\.type|delete)($|\.)/;class HistoryState{constructor(done,undone){let prevTime=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,prevUserEvent=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;this.done=done,this.undone=undone,this.prevTime=prevTime,this.prevUserEvent=prevUserEvent}isolate(){return this.prevTime?new HistoryState(this.done,this.undone):this}addChanges(event,time,userEvent,config,tr){let done=this.done,lastEvent=done[done.length-1];return done=lastEvent&&lastEvent.changes&&!lastEvent.changes.empty&&event.changes&&(!userEvent||joinableUserEvent.test(userEvent))&&(!lastEvent.selectionsAfter.length&&time-this.prevTimeranges.push(f,t))),b.iterChangedRanges(((_f,_t,f,t)=>{for(let i=0;i=from&&f<=to&&(isAdjacent=!0)}})),isAdjacent}(lastEvent.changes,event.changes))||"input.type.compose"==userEvent)?updateBranch(done,done.length-1,config.minDepth,new HistEvent(event.changes.compose(lastEvent.changes),conc(event.effects,lastEvent.effects),lastEvent.mapped,lastEvent.startSelection,none$1)):updateBranch(done,done.length,config.minDepth,event),new HistoryState(done,none$1,time,userEvent)}addSelection(selection,time,userEvent,newGroupDelay){let last=this.done.length?this.done[this.done.length-1].selectionsAfter:none$1;return last.length>0&&time-this.prevTimer.empty!=b.ranges[i].empty)).length)?this:new HistoryState(addSelection(this.done,selection),this.undone,time,userEvent);var a,b}addMapping(mapping){return new HistoryState(addMappingToBranch(this.done,mapping),addMappingToBranch(this.undone,mapping),this.prevTime,this.prevUserEvent)}pop(side,state,selection){let branch=0==side?this.done:this.undone;if(0==branch.length)return null;let event=branch[branch.length-1];if(selection&&event.selectionsAfter.length)return state.update({selection:event.selectionsAfter[event.selectionsAfter.length-1],annotations:fromHistory.of({side:side,rest:popSelection(branch)}),userEvent:0==side?"select.undo":"select.redo",scrollIntoView:!0});if(event.changes){let rest=1==branch.length?none$1:branch.slice(0,branch.length-1);return event.mapped&&(rest=addMappingToBranch(rest,event.mapped)),state.update({changes:event.changes,selection:event.startSelection,effects:event.effects,annotations:fromHistory.of({side:side,rest:rest}),filter:!1,userEvent:0==side?"undo":"redo",scrollIntoView:!0})}return null}}HistoryState.empty=new HistoryState(none$1,none$1);const historyKeymap=[{key:"Mod-z",run:undo,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:redo,preventDefault:!0},{linux:"Ctrl-Shift-z",run:redo,preventDefault:!0},{key:"Mod-u",run:undoSelection,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:redoSelection,preventDefault:!0}];function updateSel(sel,by){return EditorSelection.create(sel.ranges.map(by),sel.mainIndex)}function setSel(state,selection){return state.update({selection:selection,scrollIntoView:!0,userEvent:"select"})}function moveSel(_ref12,how){let{state:state,dispatch:dispatch}=_ref12,selection=updateSel(state.selection,how);return!selection.eq(state.selection)&&(dispatch(setSel(state,selection)),!0)}function rangeEnd(range,forward){return EditorSelection.cursor(forward?range.to:range.from)}function cursorByChar(view,forward){return moveSel(view,(range=>range.empty?view.moveByChar(range,forward):rangeEnd(range,forward)))}function ltrAtCursor(view){return view.textDirectionAt(view.state.selection.main.head)==Direction.LTR}const cursorCharLeft=view=>cursorByChar(view,!ltrAtCursor(view)),cursorCharRight=view=>cursorByChar(view,ltrAtCursor(view));function cursorByGroup(view,forward){return moveSel(view,(range=>range.empty?view.moveByGroup(range,forward):rangeEnd(range,forward)))}function interestingNode(state,node,bracketProp){if(node.type.prop(bracketProp))return!0;let len=node.to-node.from;return len&&(len>2||/[^\s,.;:]/.test(state.sliceDoc(node.from,node.to)))||node.firstChild}function moveBySyntax(state,start,forward){let match,newPos,pos=syntaxTree(state).resolveInner(start.head),bracketProp=forward?NodeProp.closedBy:NodeProp.openedBy;for(let at=start.head;;){let next=forward?pos.childAfter(at):pos.childBefore(at);if(!next)break;interestingNode(state,next,bracketProp)?pos=next:at=forward?next.to:next.from}return newPos=pos.type.prop(bracketProp)&&(match=forward?matchBrackets(state,pos.from,1):matchBrackets(state,pos.to,-1))&&match.matched?forward?match.end.to:match.end.from:forward?pos.to:pos.from,EditorSelection.cursor(newPos,forward?-1:1)}function cursorByLine(view,forward){return moveSel(view,(range=>{if(!range.empty)return rangeEnd(range,forward);let moved=view.moveVertically(range,forward);return moved.head!=range.head?moved:view.moveToLineBoundary(range,forward)}))}const cursorLineUp=view=>cursorByLine(view,!1),cursorLineDown=view=>cursorByLine(view,!0);function pageInfo(view){let height,selfScroll=view.scrollDOM.clientHeightrange.empty?view.moveVertically(range,forward,page.height):rangeEnd(range,forward)));if(selection.eq(state.selection))return!1;if(page.selfScroll){let startPos=view.coordsAtPos(state.selection.main.head),scrollRect=view.scrollDOM.getBoundingClientRect(),scrollTop=scrollRect.top+page.marginTop,scrollBottom=scrollRect.bottom-page.marginBottom;startPos&&startPos.top>scrollTop&&startPos.bottomcursorByPage(view,!1),cursorPageDown=view=>cursorByPage(view,!0);function moveByLineBoundary(view,start,forward){let line=view.lineBlockAt(start.head),moved=view.moveToLineBoundary(start,forward);if(moved.head==start.head&&moved.head!=(forward?line.to:line.from)&&(moved=view.moveToLineBoundary(start,forward,!1)),!forward&&moved.head==line.from&&line.length){let space=/^\s*/.exec(view.state.sliceDoc(line.from,Math.min(line.from+100,line.to)))[0].length;space&&start.head!=line.from+space&&(moved=EditorSelection.cursor(line.from+space))}return moved}function extendSel(view,how){let selection=updateSel(view.state.selection,(range=>{let head=how(range);return EditorSelection.range(range.anchor,head.head,head.goalColumn,head.bidiLevel||void 0)}));return!selection.eq(view.state.selection)&&(view.dispatch(setSel(view.state,selection)),!0)}function selectByChar(view,forward){return extendSel(view,(range=>view.moveByChar(range,forward)))}const selectCharLeft=view=>selectByChar(view,!ltrAtCursor(view)),selectCharRight=view=>selectByChar(view,ltrAtCursor(view));function selectByGroup(view,forward){return extendSel(view,(range=>view.moveByGroup(range,forward)))}function selectByLine(view,forward){return extendSel(view,(range=>view.moveVertically(range,forward)))}const selectLineUp=view=>selectByLine(view,!1),selectLineDown=view=>selectByLine(view,!0);function selectByPage(view,forward){return extendSel(view,(range=>view.moveVertically(range,forward,pageInfo(view).height)))}const selectPageUp=view=>selectByPage(view,!1),selectPageDown=view=>selectByPage(view,!0),cursorDocStart=_ref14=>{let{state:state,dispatch:dispatch}=_ref14;return dispatch(setSel(state,{anchor:0})),!0},cursorDocEnd=_ref15=>{let{state:state,dispatch:dispatch}=_ref15;return dispatch(setSel(state,{anchor:state.doc.length})),!0},selectDocStart=_ref16=>{let{state:state,dispatch:dispatch}=_ref16;return dispatch(setSel(state,{anchor:state.selection.main.anchor,head:0})),!0},selectDocEnd=_ref17=>{let{state:state,dispatch:dispatch}=_ref17;return dispatch(setSel(state,{anchor:state.selection.main.anchor,head:state.doc.length})),!0};function deleteBy(target,by){if(target.state.readOnly)return!1;let event="delete.selection",{state:state}=target,changes=state.changeByRange((range=>{let{from:from,to:to}=range;if(from==to){let towards=by(from);towardsfrom&&(event="delete.forward",towards=skipAtomic(target,towards,!0)),from=Math.min(from,towards),to=Math.max(to,towards)}else from=skipAtomic(target,from,!1),to=skipAtomic(target,to,!0);return from==to?{range:range}:{changes:{from:from,to:to},range:EditorSelection.cursor(from)}}));return!changes.changes.empty&&(target.dispatch(state.update(changes,{scrollIntoView:!0,userEvent:event,effects:"delete.selection"==event?EditorView.announce.of(state.phrase("Selection deleted")):void 0})),!0)}function skipAtomic(target,pos,forward){if(target instanceof EditorView)for(let ranges of target.state.facet(EditorView.atomicRanges).map((f=>f(target))))ranges.between(pos,pos,((from,to)=>{frompos&&(pos=forward?to:from)}));return pos}const deleteByChar=(target,forward)=>deleteBy(target,(pos=>{let before,targetPos,{state:state}=target,line=state.doc.lineAt(pos);if(!forward&&pos>line.from&&posdeleteByChar(view,!1),deleteCharForward=view=>deleteByChar(view,!0),deleteByGroup=(target,forward)=>deleteBy(target,(start=>{let pos=start,{state:state}=target,line=state.doc.lineAt(pos),categorize=state.charCategorizer(pos);for(let cat=null;;){if(pos==(forward?line.to:line.from)){pos==start&&line.number!=(forward?state.doc.lines:1)&&(pos+=forward?1:-1);break}let next=findClusterBreak(line.text,pos-line.from,forward)+line.from,nextChar=line.text.slice(Math.min(pos,next)-line.from,Math.max(pos,next)-line.from),nextCat=categorize(nextChar);if(null!=cat&&nextCat!=cat)break;" "==nextChar&&pos==start||(cat=nextCat),pos=next}return pos})),deleteGroupBackward=target=>deleteByGroup(target,!1),deleteToLineEnd=view=>deleteBy(view,(pos=>{let lineEnd=view.lineBlockAt(pos).to;return pos=startLine.number){let prev=blocks[blocks.length-1];prev.to=endLine.to,prev.ranges.push(range)}else blocks.push({from:startLine.from,to:endLine.to,ranges:[range]});upto=endLine.number+1}return blocks}function moveLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[],ranges=[];for(let block of selectedLineBlocks(state)){if(forward?block.to==state.doc.length:0==block.from)continue;let nextLine=state.doc.lineAt(forward?block.to+1:block.from-1),size=nextLine.length+1;if(forward){changes.push({from:block.to,to:nextLine.to},{from:block.from,insert:nextLine.text+state.lineBreak});for(let r of block.ranges)ranges.push(EditorSelection.range(Math.min(state.doc.length,r.anchor+size),Math.min(state.doc.length,r.head+size)))}else{changes.push({from:nextLine.from,to:block.from},{from:block.to,insert:state.lineBreak+nextLine.text});for(let r of block.ranges)ranges.push(EditorSelection.range(r.anchor-size,r.head-size))}}return!!changes.length&&(dispatch(state.update({changes:changes,scrollIntoView:!0,selection:EditorSelection.create(ranges,state.selection.mainIndex),userEvent:"move.line"})),!0)}function copyLine(state,dispatch,forward){if(state.readOnly)return!1;let changes=[];for(let block of selectedLineBlocks(state))forward?changes.push({from:block.from,insert:state.doc.slice(block.from,block.to)+state.lineBreak}):changes.push({from:block.to,insert:state.lineBreak+state.doc.slice(block.from,block.to)});return dispatch(state.update({changes:changes,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const insertNewlineAndIndent=newlineAndIndent(!1),insertBlankLine=newlineAndIndent(!0);function newlineAndIndent(atEof){return _ref30=>{let{state:state,dispatch:dispatch}=_ref30;if(state.readOnly)return!1;let changes=state.changeByRange((range=>{let{from:from,to:to}=range,line=state.doc.lineAt(from),explode=!atEof&&from==to&&function(state,pos){if(/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos-1,pos+1)))return{from:pos,to:pos};let closedBy,context=syntaxTree(state).resolveInner(pos),before=context.childBefore(pos),after=context.childAfter(pos);return before&&after&&before.to<=pos&&after.from>=pos&&(closedBy=before.type.prop(NodeProp.closedBy))&&closedBy.indexOf(after.name)>-1&&state.doc.lineAt(before.to).from==state.doc.lineAt(after.from).from?{from:before.to,to:after.from}:null}(state,from);atEof&&(from=to=(to<=line.to?line:state.doc.lineAt(to)).to);let cx=new IndentContext(state,{simulateBreak:from,simulateDoubleBreak:!!explode}),indent=getIndentation(cx,from);for(null==indent&&(indent=/^\s*/.exec(state.doc.lineAt(from).text)[0].length);toline.from&&from{let changes=[];for(let pos=range.from;pos<=range.to;){let line=state.doc.lineAt(pos);line.number>atLine&&(range.empty||range.to>line.from)&&(f(line,changes,range),atLine=line.number),pos=line.to+1}let changeSet=state.changes(changes);return{changes:changes,range:EditorSelection.range(changeSet.mapPos(range.anchor,1),changeSet.mapPos(range.head,1))}}))}const standardKeymap=[{key:"ArrowLeft",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:view=>cursorByGroup(view,!ltrAtCursor(view)),shift:view=>selectByGroup(view,!ltrAtCursor(view)),preventDefault:!0},{mac:"Cmd-ArrowLeft",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!ltrAtCursor(view)))),preventDefault:!0},{key:"ArrowRight",run:cursorCharRight,shift:selectCharRight,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:view=>cursorByGroup(view,ltrAtCursor(view)),shift:view=>selectByGroup(view,ltrAtCursor(view)),preventDefault:!0},{mac:"Cmd-ArrowRight",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,ltrAtCursor(view)))),preventDefault:!0},{key:"ArrowUp",run:cursorLineUp,shift:selectLineUp,preventDefault:!0},{mac:"Cmd-ArrowUp",run:cursorDocStart,shift:selectDocStart},{mac:"Ctrl-ArrowUp",run:cursorPageUp,shift:selectPageUp},{key:"ArrowDown",run:cursorLineDown,shift:selectLineDown,preventDefault:!0},{mac:"Cmd-ArrowDown",run:cursorDocEnd,shift:selectDocEnd},{mac:"Ctrl-ArrowDown",run:cursorPageDown,shift:selectPageDown},{key:"PageUp",run:cursorPageUp,shift:selectPageUp},{key:"PageDown",run:cursorPageDown,shift:selectPageDown},{key:"Home",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!1))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!1))),preventDefault:!0},{key:"Mod-Home",run:cursorDocStart,shift:selectDocStart},{key:"End",run:view=>moveSel(view,(range=>moveByLineBoundary(view,range,!0))),shift:view=>extendSel(view,(range=>moveByLineBoundary(view,range,!0))),preventDefault:!0},{key:"Mod-End",run:cursorDocEnd,shift:selectDocEnd},{key:"Enter",run:insertNewlineAndIndent},{key:"Mod-a",run:_ref18=>{let{state:state,dispatch:dispatch}=_ref18;return dispatch(state.update({selection:{anchor:0,head:state.doc.length},userEvent:"select"})),!0}},{key:"Backspace",run:deleteCharBackward,shift:deleteCharBackward},{key:"Delete",run:deleteCharForward},{key:"Mod-Backspace",mac:"Alt-Backspace",run:deleteGroupBackward},{key:"Mod-Delete",mac:"Alt-Delete",run:target=>deleteByGroup(target,!0)},{mac:"Mod-Backspace",run:view=>deleteBy(view,(pos=>{let lineStart=view.lineBlockAt(pos).from;return pos>lineStart?lineStart:Math.max(0,pos-1)}))},{mac:"Mod-Delete",run:deleteToLineEnd}].concat([{key:"Ctrl-b",run:cursorCharLeft,shift:selectCharLeft,preventDefault:!0},{key:"Ctrl-f",run:cursorCharRight,shift:selectCharRight},{key:"Ctrl-p",run:cursorLineUp,shift:selectLineUp},{key:"Ctrl-n",run:cursorLineDown,shift:selectLineDown},{key:"Ctrl-a",run:view=>moveSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).from,1))),shift:view=>extendSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).from)))},{key:"Ctrl-e",run:view=>moveSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).to,-1))),shift:view=>extendSel(view,(range=>EditorSelection.cursor(view.lineBlockAt(range.head).to)))},{key:"Ctrl-d",run:deleteCharForward},{key:"Ctrl-h",run:deleteCharBackward},{key:"Ctrl-k",run:deleteToLineEnd},{key:"Ctrl-Alt-h",run:deleteGroupBackward},{key:"Ctrl-o",run:_ref23=>{let{state:state,dispatch:dispatch}=_ref23;if(state.readOnly)return!1;let changes=state.changeByRange((range=>({changes:{from:range.from,to:range.to,insert:Text.of(["",""])},range:EditorSelection.cursor(range.from)})));return dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"input"})),!0}},{key:"Ctrl-t",run:_ref24=>{let{state:state,dispatch:dispatch}=_ref24;if(state.readOnly)return!1;let changes=state.changeByRange((range=>{if(!range.empty||0==range.from||range.from==state.doc.length)return{range:range};let pos=range.from,line=state.doc.lineAt(pos),from=pos==line.from?pos-1:findClusterBreak(line.text,pos-line.from,!1)+line.from,to=pos==line.to?pos+1:findClusterBreak(line.text,pos-line.from,!0)+line.from;return{changes:{from:from,to:to,insert:state.doc.slice(pos,to).append(state.doc.slice(from,pos))},range:EditorSelection.cursor(to)}}));return!changes.changes.empty&&(dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"move.character"})),!0)}},{key:"Ctrl-v",run:cursorPageDown}].map((b=>({mac:b.key,run:b.run,shift:b.shift})))),defaultKeymap=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:view=>moveSel(view,(range=>moveBySyntax(view.state,range,!ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveBySyntax(view.state,range,!ltrAtCursor(view))))},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:view=>moveSel(view,(range=>moveBySyntax(view.state,range,ltrAtCursor(view)))),shift:view=>extendSel(view,(range=>moveBySyntax(view.state,range,ltrAtCursor(view))))},{key:"Alt-ArrowUp",run:_ref25=>{let{state:state,dispatch:dispatch}=_ref25;return moveLine(state,dispatch,!1)}},{key:"Shift-Alt-ArrowUp",run:_ref27=>{let{state:state,dispatch:dispatch}=_ref27;return copyLine(state,dispatch,!1)}},{key:"Alt-ArrowDown",run:_ref26=>{let{state:state,dispatch:dispatch}=_ref26;return moveLine(state,dispatch,!0)}},{key:"Shift-Alt-ArrowDown",run:_ref28=>{let{state:state,dispatch:dispatch}=_ref28;return copyLine(state,dispatch,!0)}},{key:"Escape",run:_ref22=>{let{state:state,dispatch:dispatch}=_ref22,cur=state.selection,selection=null;return cur.ranges.length>1?selection=EditorSelection.create([cur.main]):cur.main.empty||(selection=EditorSelection.create([EditorSelection.cursor(cur.main.head)])),!!selection&&(dispatch(setSel(state,selection)),!0)}},{key:"Mod-Enter",run:insertBlankLine},{key:"Alt-l",mac:"Ctrl-l",run:_ref19=>{let{state:state,dispatch:dispatch}=_ref19,ranges=selectedLineBlocks(state).map((_ref20=>{let{from:from,to:to}=_ref20;return EditorSelection.range(from,Math.min(to+1,state.doc.length))}));return dispatch(state.update({selection:EditorSelection.create(ranges),userEvent:"select"})),!0}},{key:"Mod-i",run:_ref21=>{let{state:state,dispatch:dispatch}=_ref21,selection=updateSel(state.selection,(range=>{var _a;let context=syntaxTree(state).resolveInner(range.head,1);for(;!(context.from=range.to||context.to>range.to&&context.from<=range.from)&&(null===(_a=context.parent)||void 0===_a?void 0:_a.parent);)context=context.parent;return EditorSelection.range(context.to,context.from)}));return dispatch(setSel(state,selection)),!0},preventDefault:!0},{key:"Mod-[",run:_ref33=>{let{state:state,dispatch:dispatch}=_ref33;return!state.readOnly&&(dispatch(state.update(changeBySelectedLine(state,((line,changes)=>{let space=/^\s*/.exec(line.text)[0];if(!space)return;let col=countColumn(space,state.tabSize),keep=0,insert=indentString(state,Math.max(0,col-getIndentUnit(state)));for(;keep{let{state:state,dispatch:dispatch}=_ref32;return!state.readOnly&&(dispatch(state.update(changeBySelectedLine(state,((line,changes)=>{changes.push({from:line.from,insert:state.facet(indentUnit)})})),{userEvent:"input.indent"})),!0)}},{key:"Mod-Alt-\\",run:_ref31=>{let{state:state,dispatch:dispatch}=_ref31;if(state.readOnly)return!1;let updated=Object.create(null),context=new IndentContext(state,{overrideIndentation:start=>{let found=updated[start];return null==found?-1:found}}),changes=changeBySelectedLine(state,((line,changes,range)=>{let indent=getIndentation(context,line.from);if(null==indent)return;/\S/.test(line.text)||(indent=0);let cur=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);(cur!=norm||range.from{if(view.state.readOnly)return!1;let{state:state}=view,changes=state.changes(selectedLineBlocks(state).map((_ref29=>{let{from:from,to:to}=_ref29;return from>0?from--:toview.moveVertically(range,!0))).map(changes);return view.dispatch({changes:changes,selection:selection,scrollIntoView:!0,userEvent:"delete.line"}),!0}},{key:"Shift-Mod-\\",run:_ref13=>{let{state:state,dispatch:dispatch}=_ref13;return function(state,dispatch,extend){let found=!1,selection=updateSel(state.selection,(range=>{let matching=matchBrackets(state,range.head,-1)||matchBrackets(state,range.head,1)||range.head>0&&matchBrackets(state,range.head-1,1)||range.head{let{state:state}=target,line=state.doc.lineAt(state.selection.main.from),config=getConfig(target.state,line.from);return config.line?toggleLineComment(target):!!config.block&&toggleBlockCommentByLine(target)}},{key:"Alt-A",run:toggleBlockComment}].concat(standardKeymap);function crelt(){var elt=arguments[0];"string"==typeof elt&&(elt=document.createElement(elt));var i=1,next=arguments[1];if(next&&"object"==typeof next&&null==next.nodeType&&!Array.isArray(next)){for(var name in next)if(Object.prototype.hasOwnProperty.call(next,name)){var value=next[name];"string"==typeof value?elt.setAttribute(name,value):null!=value&&(elt[name]=value)}i++}for(;ix.normalize("NFKD"):x=>x;class SearchCursor{constructor(text,query){let from=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,to=arguments.length>3&&void 0!==arguments[3]?arguments[3]:text.length,normalize=arguments.length>4?arguments[4]:void 0,test=arguments.length>5?arguments[5]:void 0;this.test=test,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=text.iterRange(from,to),this.bufferStart=from,this.normalize=normalize?x=>normalize(basicNormalize(x)):basicNormalize,this.query=this.normalize(query)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return codePointAt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let next=this.peek();if(next<0)return this.done=!0,this;let str=fromCodePoint(next),start=this.bufferStart+this.bufferPos;this.bufferPos+=codePointSize(next);let norm=this.normalize(str);for(let i=0,pos=start;;i++){let code=norm.charCodeAt(i),match=this.match(code,pos);if(match)return this.value=match,this;if(i==norm.length-1)break;pos==start&&i3&&void 0!==arguments[3]?arguments[3]:0,to=arguments.length>4&&void 0!==arguments[4]?arguments[4]:text.length;if(this.text=text,this.to=to,this.curLine="",this.done=!1,this.value=empty,/\\[sWDnr]|\n|\r|\[\^/.test(query))return new MultilineRegExpCursor(text,query,options,from,to);this.re=new RegExp(query,baseFlags+((null==options?void 0:options.ignoreCase)?"i":"")),this.test=null==options?void 0:options.test,this.iter=text.iter();let startLine=text.lineAt(from);this.curLineStart=startLine.from,this.matchPos=toCharEnd(text,from),this.getLine(this.curLineStart)}getLine(skip){this.iter.next(skip),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let off=this.matchPos-this.curLineStart;;){this.re.lastIndex=off;let match=this.matchPos<=this.to&&this.re.exec(this.curLine);if(match){let from=this.curLineStart+match.index,to=from+match[0].length;if(this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),from==this.curLineStart+this.curLine.length&&this.nextLine(),(fromthis.value.to)&&(!this.test||this.test(from,to,match)))return this.value={from:from,to:to,match:match},this;off=this.matchPos-this.curLineStart}else{if(!(this.curLineStart+this.curLine.length=to||cached.to<=from){let flat=new FlattenedDoc(from,doc.sliceString(from,to));return flattened.set(doc,flat),flat}if(cached.from==from&&cached.to==to)return cached;let{text:text,from:cachedFrom}=cached;return cachedFrom>from&&(text=doc.sliceString(from,cachedFrom)+text,cachedFrom=from),cached.to=this.to?this.to:this.text.lineAt(pos).to}next(){for(;;){let off=this.re.lastIndex=this.matchPos-this.flat.from,match=this.re.exec(this.flat.text);if(match&&!match[0]&&match.index==off&&(this.re.lastIndex=off+1,match=this.re.exec(this.flat.text)),match){let from=this.flat.from+match.index,to=from+match[0].length;if((this.flat.to>=this.to||match.index+match[0].length<=this.flat.text.length-10)&&(!this.test||this.test(from,to,match)))return this.value={from:from,to:to,match:match},this.matchPos=toCharEnd(this.text,to+(from==to?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=FlattenedDoc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+2*this.flat.text.length))}}}function toCharEnd(text,pos){if(pos>=text.length)return pos;let next,line=text.lineAt(pos);for(;pos=56320&&next<57344;)pos++;return pos}function createLineDialog(view){let input=crelt("input",{class:"cm-textfield",name:"line"});function go(){let match=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);if(!match)return;let{state:state}=view,startLine=state.doc.lineAt(state.selection.main.head),[,sign,ln,cl,percent]=match,col=cl?+cl.slice(1):0,line=ln?+ln:startLine.number;if(ln&&percent){let pc=line/100;sign&&(pc=pc*("-"==sign?-1:1)+startLine.number/state.doc.lines),line=Math.round(state.doc.lines*pc)}else ln&&sign&&(line=line*("-"==sign?-1:1)+startLine.number);let docLine=state.doc.line(Math.max(1,Math.min(state.doc.lines,line)));view.dispatch({effects:dialogEffect.of(!1),selection:EditorSelection.cursor(docLine.from+Math.max(0,Math.min(col,docLine.length))),scrollIntoView:!0}),view.focus()}return{dom:crelt("form",{class:"cm-gotoLine",onkeydown:event=>{27==event.keyCode?(event.preventDefault(),view.dispatch({effects:dialogEffect.of(!1)}),view.focus()):13==event.keyCode&&(event.preventDefault(),go())},onsubmit:event=>{event.preventDefault(),go()}},crelt("label",view.state.phrase("Go to line"),": ",input)," ",crelt("button",{class:"cm-button",type:"submit"},view.state.phrase("go")))}}"undefined"!=typeof Symbol&&(RegExpCursor.prototype[Symbol.iterator]=MultilineRegExpCursor.prototype[Symbol.iterator]=function(){return this});const dialogEffect=StateEffect.define(),dialogField=StateField.define({create:()=>!0,update(value,tr){for(let e of tr.effects)e.is(dialogEffect)&&(value=e.value);return value},provide:f=>showPanel.from(f,(val=>val?createLineDialog:null))}),baseTheme$1$1=EditorView.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),defaultHighlightOptions={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},highlightConfig=Facet.define({combine:options=>combineConfig(options,defaultHighlightOptions,{highlightWordAroundCursor:(a,b)=>a||b,minSelectionLength:Math.min,maxMatches:Math.min})});function highlightSelectionMatches(options){let ext=[defaultTheme,matchHighlighter];return options&&ext.push(highlightConfig.of(options)),ext}const matchDeco=Decoration.mark({class:"cm-selectionMatch"}),mainMatchDeco=Decoration.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function insideWordBoundaries(check,state,from,to){return!(0!=from&&check(state.sliceDoc(from-1,from))==CharCategory.Word||to!=state.doc.length&&check(state.sliceDoc(to,to+1))==CharCategory.Word)}const matchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.decorations=this.getDeco(view)}update(update){(update.selectionSet||update.docChanged||update.viewportChanged)&&(this.decorations=this.getDeco(update.view))}getDeco(view){let conf=view.state.facet(highlightConfig),{state:state}=view,sel=state.selection;if(sel.ranges.length>1)return Decoration.none;let query,range=sel.main,check=null;if(range.empty){if(!conf.highlightWordAroundCursor)return Decoration.none;let word=state.wordAt(range.head);if(!word)return Decoration.none;check=state.charCategorizer(range.head),query=state.sliceDoc(word.from,word.to)}else{let len=range.to-range.from;if(len200)return Decoration.none;if(conf.wholeWords){if(query=state.sliceDoc(range.from,range.to),check=state.charCategorizer(range.head),!insideWordBoundaries(check,state,range.from,range.to)||!function(check,state,from,to){return check(state.sliceDoc(from,from+1))==CharCategory.Word&&check(state.sliceDoc(to-1,to))==CharCategory.Word}(check,state,range.from,range.to))return Decoration.none}else if(query=state.sliceDoc(range.from,range.to).trim(),!query)return Decoration.none}let deco=[];for(let part of view.visibleRanges){let cursor=new SearchCursor(state.doc,query,part.from,part.to);for(;!cursor.next().done;){let{from:from,to:to}=cursor.value;if((!check||insideWordBoundaries(check,state,from,to))&&(range.empty&&from<=range.from&&to>=range.to?deco.push(mainMatchDeco.range(from,to)):(from>=range.to||to<=range.from)&&deco.push(matchDeco.range(from,to)),deco.length>conf.maxMatches))return Decoration.none}}return Decoration.set(deco)}},{decorations:v=>v.decorations}),defaultTheme=EditorView.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const searchConfigFacet=Facet.define({combine:configs=>combineConfig(configs,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:view=>new SearchPanel(view),scrollToMatch:range=>EditorView.scrollIntoView(range)})});class SearchQuery{constructor(config){this.search=config.search,this.caseSensitive=!!config.caseSensitive,this.literal=!!config.literal,this.regexp=!!config.regexp,this.replace=config.replace||"",this.valid=!!this.search&&(!this.regexp||function(source){try{return new RegExp(source,baseFlags),!0}catch(_a){return!1}}(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!config.wholeWord}unquote(text){return this.literal?text:text.replace(/\\([nrt\\])/g,((_,ch)=>"n"==ch?"\n":"r"==ch?"\r":"t"==ch?"\t":"\\"))}eq(other){return this.search==other.search&&this.replace==other.replace&&this.caseSensitive==other.caseSensitive&&this.regexp==other.regexp&&this.wholeWord==other.wholeWord}create(){return this.regexp?new RegExpQuery(this):new StringQuery(this)}getCursor(state){let from=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,to=arguments.length>2?arguments[2]:void 0,st=state.doc?state:EditorState.create({doc:state});return null==to&&(to=st.doc.length),this.regexp?regexpCursor(this,st,from,to):stringCursor(this,st,from,to)}}class QueryType{constructor(spec){this.spec=spec}}function stringCursor(spec,state,from,to){return new SearchCursor(state.doc,spec.unquoted,from,to,spec.caseSensitive?void 0:x=>x.toLowerCase(),spec.wholeWord?function(doc,categorizer){return(from,to,buf,bufPos)=>((bufPos>from||bufPos+buf.length=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=stringCursor(this.spec,state,Math.max(0,from-this.spec.unquoted.length),Math.min(to+this.spec.unquoted.length,state.doc.length));for(;!cursor.next().done;)add(cursor.value.from,cursor.value.to)}}function regexpCursor(spec,state,from,to){return new RegExpCursor(state.doc,spec.search,{ignoreCase:!spec.caseSensitive,test:spec.wholeWord?(categorizer=state.charCategorizer(state.selection.main.head),(_from,_to,match)=>!match[0].length||(categorizer(charBefore(match.input,match.index))!=CharCategory.Word||categorizer(charAfter(match.input,match.index))!=CharCategory.Word)&&(categorizer(charAfter(match.input,match.index+match[0].length))!=CharCategory.Word||categorizer(charBefore(match.input,match.index+match[0].length))!=CharCategory.Word)):void 0},from,to);var categorizer}function charBefore(str,index){return str.slice(findClusterBreak(str,index,!1),index)}function charAfter(str,index){return str.slice(index,findClusterBreak(str,index))}class RegExpQuery extends QueryType{nextMatch(state,curFrom,curTo){let cursor=regexpCursor(this.spec,state,curTo,state.doc.length).next();return cursor.done&&(cursor=regexpCursor(this.spec,state,0,curFrom).next()),cursor.done?null:cursor.value}prevMatchInRange(state,from,to){for(let size=1;;size++){let start=Math.max(from,to-1e4*size),cursor=regexpCursor(this.spec,state,start,to),range=null;for(;!cursor.next().done;)range=cursor.value;if(range&&(start==from||range.from>start+10))return range;if(start==from)return null}}prevMatch(state,curFrom,curTo){return this.prevMatchInRange(state,0,curFrom)||this.prevMatchInRange(state,curTo,state.doc.length)}getReplacement(result){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,((m,i)=>"$"==i?"$":"&"==i?result.match[0]:"0"!=i&&+i=limit)return null;ranges.push(cursor.value)}return ranges}highlight(state,from,to,add){let cursor=regexpCursor(this.spec,state,Math.max(0,from-250),Math.min(to+250,state.doc.length));for(;!cursor.next().done;)add(cursor.value.from,cursor.value.to)}}const setSearchQuery=StateEffect.define(),togglePanel$1=StateEffect.define(),searchState=StateField.define({create:state=>new SearchState(defaultQuery(state).create(),null),update(value,tr){for(let effect of tr.effects)effect.is(setSearchQuery)?value=new SearchState(effect.value.create(),value.panel):effect.is(togglePanel$1)&&(value=new SearchState(value.query,effect.value?createSearchPanel:null));return value},provide:f=>showPanel.from(f,(val=>val.panel))});class SearchState{constructor(query,panel){this.query=query,this.panel=panel}}const matchMark=Decoration.mark({class:"cm-searchMatch"}),selectedMatchMark=Decoration.mark({class:"cm-searchMatch cm-searchMatch-selected"}),searchHighlighter=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.decorations=this.highlight(view.state.field(searchState))}update(update){let state=update.state.field(searchState);(state!=update.startState.field(searchState)||update.docChanged||update.selectionSet||update.viewportChanged)&&(this.decorations=this.highlight(state))}highlight(_ref36){let{query:query,panel:panel}=_ref36;if(!panel||!query.spec.valid)return Decoration.none;let{view:view}=this,builder=new RangeSetBuilder;for(let i=0,ranges=view.visibleRanges,l=ranges.length;iranges[i+1].from-500;)to=ranges[++i].to;query.highlight(view.state,from,to,((from,to)=>{let selected=view.state.selection.ranges.some((r=>r.from==from&&r.to==to));builder.add(from,to,selected?selectedMatchMark:matchMark)}))}return builder.finish()}},{decorations:v=>v.decorations});function searchCommand(f){return view=>{let state=view.state.field(searchState,!1);return state&&state.query.spec.valid?f(view,state):openSearchPanel(view)}}const findNext=searchCommand(((view,_ref37)=>{let{query:query}=_ref37,{to:to}=view.state.selection.main,next=query.nextMatch(view.state,to,to);if(!next)return!1;let selection=EditorSelection.single(next.from,next.to),config=view.state.facet(searchConfigFacet);return view.dispatch({selection:selection,effects:[announceMatch(view,next),config.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0})),findPrevious=searchCommand(((view,_ref38)=>{let{query:query}=_ref38,{state:state}=view,{from:from}=state.selection.main,prev=query.prevMatch(state,from,from);if(!prev)return!1;let selection=EditorSelection.single(prev.from,prev.to),config=view.state.facet(searchConfigFacet);return view.dispatch({selection:selection,effects:[announceMatch(view,prev),config.scrollToMatch(selection.main,view)],userEvent:"select.search"}),selectSearchInput(view),!0})),selectMatches=searchCommand(((view,_ref39)=>{let{query:query}=_ref39,ranges=query.matchAll(view.state,1e3);return!(!ranges||!ranges.length)&&(view.dispatch({selection:EditorSelection.create(ranges.map((r=>EditorSelection.range(r.from,r.to)))),userEvent:"select.search.matches"}),!0)})),replaceNext=searchCommand(((view,_ref41)=>{let{query:query}=_ref41,{state:state}=view,{from:from,to:to}=state.selection.main;if(state.readOnly)return!1;let next=query.nextMatch(state,from,from);if(!next)return!1;let selection,replacement,changes=[],effects=[];if(next.from==from&&next.to==to&&(replacement=state.toText(query.getReplacement(next)),changes.push({from:next.from,to:next.to,insert:replacement}),next=query.nextMatch(state,next.from,next.to),effects.push(EditorView.announce.of(state.phrase("replaced match on line $",state.doc.lineAt(from).number)+"."))),next){let off=0==changes.length||changes[0].from>=next.to?0:next.to-next.from-replacement.length;selection=EditorSelection.single(next.from-off,next.to-off),effects.push(announceMatch(view,next)),effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main,view))}return view.dispatch({changes:changes,selection:selection,effects:effects,userEvent:"input.replace"}),!0})),replaceAll=searchCommand(((view,_ref42)=>{let{query:query}=_ref42;if(view.state.readOnly)return!1;let changes=query.matchAll(view.state,1e9).map((match=>{let{from:from,to:to}=match;return{from:from,to:to,insert:query.getReplacement(match)}}));if(!changes.length)return!1;let announceText=view.state.phrase("replaced $ matches",changes.length)+".";return view.dispatch({changes:changes,effects:EditorView.announce.of(announceText),userEvent:"input.replace.all"}),!0}));function createSearchPanel(view){return view.state.facet(searchConfigFacet).createPanel(view)}function defaultQuery(state,fallback){var _a,_b,_c,_d,_e;let sel=state.selection.main,selText=sel.empty||sel.to>sel.from+100?"":state.sliceDoc(sel.from,sel.to);if(fallback&&!selText)return fallback;let config=state.facet(searchConfigFacet);return new SearchQuery({search:(null!==(_a=null==fallback?void 0:fallback.literal)&&void 0!==_a?_a:config.literal)?selText:selText.replace(/\n/g,"\\n"),caseSensitive:null!==(_b=null==fallback?void 0:fallback.caseSensitive)&&void 0!==_b?_b:config.caseSensitive,literal:null!==(_c=null==fallback?void 0:fallback.literal)&&void 0!==_c?_c:config.literal,regexp:null!==(_d=null==fallback?void 0:fallback.regexp)&&void 0!==_d?_d:config.regexp,wholeWord:null!==(_e=null==fallback?void 0:fallback.wholeWord)&&void 0!==_e?_e:config.wholeWord})}function getSearchInput(view){let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.querySelector("[main-field]")}function selectSearchInput(view){let input=getSearchInput(view);input&&input==view.root.activeElement&&input.select()}const openSearchPanel=view=>{let state=view.state.field(searchState,!1);if(state&&state.panel){let searchInput=getSearchInput(view);if(searchInput&&searchInput!=view.root.activeElement){let query=defaultQuery(view.state,state.query.spec);query.valid&&view.dispatch({effects:setSearchQuery.of(query)}),searchInput.focus(),searchInput.select()}}else view.dispatch({effects:[togglePanel$1.of(!0),state?setSearchQuery.of(defaultQuery(view.state,state.query.spec)):StateEffect.appendConfig.of(searchExtensions)]});return!0},closeSearchPanel=view=>{let state=view.state.field(searchState,!1);if(!state||!state.panel)return!1;let panel=getPanel(view,createSearchPanel);return panel&&panel.dom.contains(view.root.activeElement)&&view.focus(),view.dispatch({effects:togglePanel$1.of(!1)}),!0},searchKeymap=[{key:"Mod-f",run:openSearchPanel,scope:"editor search-panel"},{key:"F3",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:findNext,shift:findPrevious,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:closeSearchPanel,scope:"editor search-panel"},{key:"Mod-Shift-l",run:_ref40=>{let{state:state,dispatch:dispatch}=_ref40,sel=state.selection;if(sel.ranges.length>1||sel.main.empty)return!1;let{from:from,to:to}=sel.main,ranges=[],main=0;for(let cur=new SearchCursor(state.doc,state.sliceDoc(from,to));!cur.next().done;){if(ranges.length>1e3)return!1;cur.value.from==from&&(main=ranges.length),ranges.push(EditorSelection.range(cur.value.from,cur.value.to))}return dispatch(state.update({selection:EditorSelection.create(ranges,main),userEvent:"select.search.matches"})),!0}},{key:"Alt-g",run:view=>{let panel=getPanel(view,createLineDialog);if(!panel){let effects=[dialogEffect.of(!0)];null==view.state.field(dialogField,!1)&&effects.push(StateEffect.appendConfig.of([dialogField,baseTheme$1$1])),view.dispatch({effects:effects}),panel=getPanel(view,createLineDialog)}return panel&&panel.dom.querySelector("input").focus(),!0}},{key:"Mod-d",run:_ref35=>{let{state:state,dispatch:dispatch}=_ref35,{ranges:ranges}=state.selection;if(ranges.some((sel=>sel.from===sel.to)))return(_ref34=>{let{state:state,dispatch:dispatch}=_ref34,{selection:selection}=state,newSel=EditorSelection.create(selection.ranges.map((range=>state.wordAt(range.head)||EditorSelection.cursor(range.head))),selection.mainIndex);return!newSel.eq(selection)&&(dispatch(state.update({selection:newSel})),!0)})({state:state,dispatch:dispatch});let searchedText=state.sliceDoc(ranges[0].from,ranges[0].to);if(state.selection.ranges.some((r=>state.sliceDoc(r.from,r.to)!=searchedText)))return!1;let range=function(state,query){let{main:main,ranges:ranges}=state.selection,word=state.wordAt(main.head),fullWord=word&&word.from==main.from&&word.to==main.to;for(let cycled=!1,cursor=new SearchCursor(state.doc,query,ranges[ranges.length-1].to);;){if(cursor.next(),!cursor.done){if(cycled&&ranges.some((r=>r.from==cursor.value.from)))continue;if(fullWord){let word=state.wordAt(cursor.value.from);if(!word||word.from!=cursor.value.from||word.to!=cursor.value.to)continue}return cursor.value}if(cycled)return null;cursor=new SearchCursor(state.doc,query,0,Math.max(0,ranges[ranges.length-1].from-1)),cycled=!0}}(state,searchedText);return!!range&&(dispatch(state.update({selection:state.selection.addRange(EditorSelection.range(range.from,range.to),!1),effects:EditorView.scrollIntoView(range.to)})),!0)},preventDefault:!0}];class SearchPanel{constructor(view){this.view=view;let query=this.query=view.state.field(searchState).query.spec;function button(name,onclick,content){return crelt("button",{class:"cm-button",name:name,onclick:onclick,type:"button"},content)}this.commit=this.commit.bind(this),this.searchField=crelt("input",{value:query.search,placeholder:phrase(view,"Find"),"aria-label":phrase(view,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=crelt("input",{value:query.replace,placeholder:phrase(view,"Replace"),"aria-label":phrase(view,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=crelt("input",{type:"checkbox",name:"case",form:"",checked:query.caseSensitive,onchange:this.commit}),this.reField=crelt("input",{type:"checkbox",name:"re",form:"",checked:query.regexp,onchange:this.commit}),this.wordField=crelt("input",{type:"checkbox",name:"word",form:"",checked:query.wholeWord,onchange:this.commit}),this.dom=crelt("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,button("next",(()=>findNext(view)),[phrase(view,"next")]),button("prev",(()=>findPrevious(view)),[phrase(view,"previous")]),button("select",(()=>selectMatches(view)),[phrase(view,"all")]),crelt("label",null,[this.caseField,phrase(view,"match case")]),crelt("label",null,[this.reField,phrase(view,"regexp")]),crelt("label",null,[this.wordField,phrase(view,"by word")]),...view.state.readOnly?[]:[crelt("br"),this.replaceField,button("replace",(()=>replaceNext(view)),[phrase(view,"replace")]),button("replaceAll",(()=>replaceAll(view)),[phrase(view,"replace all")])],crelt("button",{name:"close",onclick:()=>closeSearchPanel(view),"aria-label":phrase(view,"close"),type:"button"},["×"])])}commit(){let query=new SearchQuery({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});query.eq(this.query)||(this.query=query,this.view.dispatch({effects:setSearchQuery.of(query)}))}keydown(e){var view,event,scope;view=this.view,event=e,scope="search-panel",runHandlers(getKeymap(view.state),event,view,scope)?e.preventDefault():13==e.keyCode&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?findPrevious:findNext)(this.view)):13==e.keyCode&&e.target==this.replaceField&&(e.preventDefault(),replaceNext(this.view))}update(update){for(let tr of update.transactions)for(let effect of tr.effects)effect.is(setSearchQuery)&&!effect.value.eq(this.query)&&this.setQuery(effect.value)}setQuery(query){this.query=query,this.searchField.value=query.search,this.replaceField.value=query.replace,this.caseField.checked=query.caseSensitive,this.reField.checked=query.regexp,this.wordField.checked=query.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(searchConfigFacet).top}}function phrase(view,phrase){return view.state.phrase(phrase)}const Break=/[\s\.,:;?!]/;function announceMatch(view,_ref43){let{from:from,to:to}=_ref43,line=view.state.doc.lineAt(from),lineEnd=view.state.doc.lineAt(to).to,start=Math.max(line.from,from-30),end=Math.min(lineEnd,to+30),text=view.state.sliceDoc(start,end);if(start!=line.from)for(let i=0;i<30;i++)if(!Break.test(text[i+1])&&Break.test(text[i])){text=text.slice(i);break}if(end!=lineEnd)for(let i=text.length-1;i>text.length-30;i--)if(!Break.test(text[i-1])&&Break.test(text[i])){text=text.slice(0,i);break}return EditorView.announce.of("".concat(view.state.phrase("current match"),". ").concat(text," ").concat(view.state.phrase("on line")," ").concat(line.number,"."))}const baseTheme$2=EditorView.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),searchExtensions=[searchState,Prec.lowest(searchHighlighter),baseTheme$2];class CompletionContext{constructor(state,pos,explicit){this.state=state,this.pos=pos,this.explicit=explicit,this.abortListeners=[]}tokenBefore(types){let token=syntaxTree(this.state).resolveInner(this.pos,-1);for(;token&&types.indexOf(token.name)<0;)token=token.parent;return token?{from:token.from,to:this.pos,text:this.state.sliceDoc(token.from,this.pos),type:token.type}:null}matchBefore(expr){let line=this.state.doc.lineAt(this.pos),start=Math.max(line.from,this.pos-250),str=line.text.slice(start-line.from,this.pos-line.from),found=str.search(ensureAnchor(expr,!1));return found<0?null:{from:start+found,to:this.pos,text:str.slice(found)}}get aborted(){return null==this.abortListeners}addEventListener(type,listener){"abort"==type&&this.abortListeners&&this.abortListeners.push(listener)}}function toSet(chars){let flat=Object.keys(chars).join(""),words=/\w/.test(flat);return words&&(flat=flat.replace(/\w/g,"")),"[".concat(words?"\\w":"").concat(flat.replace(/[^\w\s]/g,"\\$&"),"]")}function completeFromList(list){let options=list.map((o=>"string"==typeof o?{label:o}:o)),[validFor,match]=options.every((o=>/^\w+$/.test(o.label)))?[/\w*$/,/\w+$/]:function(options){let first=Object.create(null),rest=Object.create(null);for(let{label:label}of options){first[label[0]]=!0;for(let i=1;i{let token=context.matchBefore(match);return token||context.explicit?{from:token?token.from:context.pos,options:options,validFor:validFor}:null}}function ifNotIn(nodes,source){return context=>{for(let pos=syntaxTree(context.state).resolveInner(context.pos,-1);pos;pos=pos.parent){if(nodes.indexOf(pos.name)>-1)return null;if(pos.type.isTop)break}return source(context)}}class Option{constructor(completion,source,match,score){this.completion=completion,this.source=source,this.match=match,this.score=score}}function cur(state){return state.selection.main.from}function ensureAnchor(expr,start){var _a;let{source:source}=expr,addStart=start&&"^"!=source[0],addEnd="$"!=source[source.length-1];return addStart||addEnd?new RegExp("".concat(addStart?"^":"","(?:").concat(source,")").concat(addEnd?"$":""),null!==(_a=expr.flags)&&void 0!==_a?_a:expr.ignoreCase?"i":""):expr}const pickedCompletion=Annotation.define();const SourceCache=new WeakMap;function asSource(source){if(!Array.isArray(source))return source;let known=SourceCache.get(source);return known||SourceCache.set(source,known=completeFromList(source)),known}const startCompletionEffect=StateEffect.define(),closeCompletionEffect=StateEffect.define();class FuzzyMatcher{constructor(pattern){this.pattern=pattern,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[];for(let p=0;p=48&&next<=57||next>=97&&next<=122?2:next>=65&&next<=90?1:0:(ch=fromCodePoint(next))!=ch.toLowerCase()?1:ch!=ch.toUpperCase()?2:0;(!i||1==type&&hasLower||0==prevType&&0!=type)&&(chars[byWordTo]==next||folded[byWordTo]==next&&(byWordFolded=!0)?byWord[byWordTo++]=i:byWord.length&&(wordAdjacent=!1)),prevType=type,i+=codePointSize(next)}return byWordTo==len&&0==byWord[0]&&wordAdjacent?this.result((byWordFolded?-200:0)-100,byWord,word):adjacentTo==len&&0==adjacentStart?[-200-word.length+(adjacentEnd==word.length?0:-100),0,adjacentEnd]:direct>-1?[-700-word.length,direct,direct+this.pattern.length]:adjacentTo==len?[-900-word.length,adjacentStart,adjacentEnd]:byWordTo==len?this.result((byWordFolded?-200:0)-100-700+(wordAdjacent?0:-1100),byWord,word):2==chars.length?null:this.result((any[0]?-700:0)-200-1100,any,word)}result(score,positions,word){let result=[score-word.length],i=1;for(let pos of positions){let to=pos+(this.astral?codePointSize(codePointAt(word,pos)):1);i>1&&result[i-1]==pos?result[i-1]=to:(result[i++]=pos,result[i++]=to)}return result}}const completionConfig=Facet.define({combine:configs=>combineConfig(configs,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:defaultPositionInfo,compareCompletions:(a,b)=>a.label.localeCompare(b.label),interactionDelay:75},{defaultKeymap:(a,b)=>a&&b,closeOnBlur:(a,b)=>a&&b,icons:(a,b)=>a&&b,tooltipClass:(a,b)=>c=>joinClass(a(c),b(c)),optionClass:(a,b)=>c=>joinClass(a(c),b(c)),addToOptions:(a,b)=>a.concat(b)})});function joinClass(a,b){return a?b?a+" "+b:a:b}function defaultPositionInfo(view,list,option,info,space){let offset,maxWidth,rtl=view.textDirection==Direction.RTL,left=rtl,narrow=!1,side="top",spaceLeft=list.left-space.left,spaceRight=space.right-list.right,infoWidth=info.right-info.left,infoHeight=info.bottom-info.top;if(left&&spaceLeft=infoHeight||spaceBelow>list.top?offset=option.bottom-list.top:(side="bottom",offset=list.bottom-option.top)}return{style:"".concat(side,": ").concat(offset,"px; max-width: ").concat(maxWidth,"px"),class:"cm-completionInfo-"+(narrow?rtl?"left-narrow":"right-narrow":left?"left":"right")}}function rangeAroundSelected(total,selected,max){if(total<=max)return{from:0,to:total};if(selected<0&&(selected=0),selected<=total>>1){let off=Math.floor(selected/max);return{from:off*max,to:(off+1)*max}}let off=Math.floor((total-selected)/max);return{from:total-(off+1)*max,to:total-off*max}}class CompletionTooltip{constructor(view,stateField,applyCompletion){this.view=view,this.stateField=stateField,this.applyCompletion=applyCompletion,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:pos=>this.placeInfo(pos),key:this},this.space=null,this.currentClass="";let cState=view.state.field(stateField),{options:options,selected:selected}=cState.open,config=view.state.facet(completionConfig);this.optionContent=function(config){let content=config.addToOptions.slice();return config.icons&&content.push({render(completion){let icon=document.createElement("div");return icon.classList.add("cm-completionIcon"),completion.type&&icon.classList.add(...completion.type.split(/\s+/g).map((cls=>"cm-completionIcon-"+cls))),icon.setAttribute("aria-hidden","true"),icon},position:20}),content.push({render(completion,_s,match){let labelElt=document.createElement("span");labelElt.className="cm-completionLabel";let{label:label}=completion,off=0;for(let j=1;joff&&labelElt.appendChild(document.createTextNode(label.slice(off,from)));let span=labelElt.appendChild(document.createElement("span"));span.appendChild(document.createTextNode(label.slice(from,to))),span.className="cm-completionMatchedText",off=to}return offa.position-b.position)).map((a=>a.render))}(config),this.optionClass=config.optionClass,this.tooltipClass=config.tooltipClass,this.range=rangeAroundSelected(options.length,selected,config.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(view.state),this.dom.addEventListener("mousedown",(e=>{for(let match,dom=e.target;dom&&dom!=this.dom;dom=dom.parentNode)if("LI"==dom.nodeName&&(match=/-(\d+)$/.exec(dom.id))&&+match[1]{let state=view.state.field(this.stateField,!1);state&&state.tooltip&&view.state.facet(completionConfig).closeOnBlur&&e.relatedTarget!=view.contentDOM&&view.dispatch({effects:closeCompletionEffect.of(null)})})),this.list=this.dom.appendChild(this.createListBox(options,cState.id,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))}mount(){this.updateSel()}update(update){var _a,_b,_c;let cState=update.state.field(this.stateField),prevState=update.startState.field(this.stateField);this.updateTooltipClass(update.state),cState!=prevState&&(this.updateSel(),(null===(_a=cState.open)||void 0===_a?void 0:_a.disabled)!=(null===(_b=prevState.open)||void 0===_b?void 0:_b.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!(null===(_c=cState.open)||void 0===_c?void 0:_c.disabled)))}updateTooltipClass(state){let cls=this.tooltipClass(state);if(cls!=this.currentClass){for(let c of this.currentClass.split(" "))c&&this.dom.classList.remove(c);for(let c of cls.split(" "))c&&this.dom.classList.add(c);this.currentClass=cls}}positioned(space){this.space=space,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let cState=this.view.state.field(this.stateField),open=cState.open;if((open.selected>-1&&open.selected=this.range.to)&&(this.range=rangeAroundSelected(open.options.length,open.selected,this.view.state.facet(completionConfig).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(open.options,cState.id,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))),this.updateSelectedOption(open.selected)){this.destroyInfo();let{completion:completion}=open.options[open.selected],{info:info}=completion;if(!info)return;let infoResult="string"==typeof info?document.createTextNode(info):info(completion);if(!infoResult)return;"then"in infoResult?infoResult.then((obj=>{obj&&this.view.state.field(this.stateField,!1)==cState&&this.addInfoPane(obj,completion)})).catch((e=>logException(this.view.state,e,"completion info"))):this.addInfoPane(infoResult,completion)}}addInfoPane(content,completion){this.destroyInfo();let wrap=this.info=document.createElement("div");if(wrap.className="cm-tooltip cm-completionInfo",null!=content.nodeType)wrap.appendChild(content),this.infoDestroy=null;else{let{dom:dom,destroy:destroy}=content;wrap.appendChild(dom),this.infoDestroy=destroy||null}this.dom.appendChild(wrap),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(selected){let set=null;for(let opt=this.list.firstChild,i=this.range.from;opt;opt=opt.nextSibling,i++)"LI"==opt.nodeName&&opt.id?i==selected?opt.hasAttribute("aria-selected")||(opt.setAttribute("aria-selected","true"),set=opt):opt.hasAttribute("aria-selected")&&opt.removeAttribute("aria-selected"):i--;return set&&function(container,element){let parent=container.getBoundingClientRect(),self=element.getBoundingClientRect();self.topparent.bottom&&(container.scrollTop+=self.bottom-parent.bottom)}(this.list,set),set}measureInfo(){let sel=this.dom.querySelector("[aria-selected]");if(!sel||!this.info)return null;let listRect=this.dom.getBoundingClientRect(),infoRect=this.info.getBoundingClientRect(),selRect=sel.getBoundingClientRect(),space=this.space;if(!space){let win=this.dom.ownerDocument.defaultView||window;space={left:0,top:0,right:win.innerWidth,bottom:win.innerHeight}}return selRect.top>Math.min(space.bottom,listRect.bottom)-10||selRect.bottomrange.from||0==range.from))if(curSection=name,"string"!=typeof section&§ion.header)ul.appendChild(section.header(section));else{ul.appendChild(document.createElement("completion-section")).textContent=name}}const li=ul.appendChild(document.createElement("li"));li.id=id+"-"+i,li.setAttribute("role","option");let cls=this.optionClass(completion);cls&&(li.className=cls);for(let source of this.optionContent){let node=source(completion,this.view.state,match);node&&li.appendChild(node)}}return range.from&&ul.classList.add("cm-completionListIncompleteTop"),range.tonew CompletionTooltip(view,stateField,applyCompletion)}function score(option){return 100*(option.boost||0)+(option.apply?10:0)+(option.info?5:0)+(option.type?1:0)}class CompletionDialog{constructor(options,attrs,tooltip,timestamp,selected,disabled){this.options=options,this.attrs=attrs,this.tooltip=tooltip,this.timestamp=timestamp,this.selected=selected,this.disabled=disabled}setSelected(selected,id){return selected==this.selected||selected>=this.options.length?this:new CompletionDialog(this.options,makeAttrs(id,selected),this.tooltip,this.timestamp,selected,this.disabled)}static build(active,state,id,prev,conf){let options=function(active,state){let options=[],sections=null,addOption=option=>{options.push(option);let{section:section}=option.completion;if(section){sections||(sections=[]);let name="string"==typeof section?section:section.name;sections.some((s=>s.name==name))||sections.push("string"==typeof section?{name:name}:section)}};for(let a of active)if(a.hasResult())if(!1===a.result.filter){let getMatch=a.result.getMatch;for(let option of a.result.options){let match=[1e9-options.length];if(getMatch)for(let n of getMatch(option))match.push(n);addOption(new Option(option,a.source,match,match[0]))}}else{let match,matcher=new FuzzyMatcher(state.sliceDoc(a.from,a.to));for(let option of a.result.options)(match=matcher.match(option.label))&&addOption(new Option(option,a.source,match,match[0]+(option.boost||0)))}if(sections){let sectionOrder=Object.create(null),pos=0,cmp=(a,b)=>{var _a,_b;return(null!==(_a=a.rank)&&void 0!==_a?_a:1e9)-(null!==(_b=b.rank)&&void 0!==_b?_b:1e9)||(a.nameb.score-a.score||compare(a.completion,b.completion)))){let cur=opt.completion;!prev||prev.label!=cur.label||prev.detail!=cur.detail||null!=prev.type&&null!=cur.type&&prev.type!=cur.type||prev.apply!=cur.apply||prev.boost!=cur.boost?result.push(opt):score(opt.completion)>score(prev)&&(result[result.length-1]=opt),prev=opt.completion}return result}(active,state);if(!options.length)return prev&&active.some((a=>1==a.state))?new CompletionDialog(prev.options,prev.attrs,prev.tooltip,prev.timestamp,prev.selected,!0):null;let selected=state.facet(completionConfig).selectOnOpen?0:-1;if(prev&&prev.selected!=selected&&-1!=prev.selected){let selectedValue=prev.options[prev.selected].completion;for(let i=0;ib.hasResult()?Math.min(a,b.from):a),1e8),create:completionTooltip(completionState,applyCompletion),above:conf.aboveCursor},prev?prev.timestamp:Date.now(),selected,!1)}map(changes){return new CompletionDialog(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:changes.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}}class CompletionState{constructor(active,id,open){this.active=active,this.id=id,this.open=open}static start(){return new CompletionState(none,"cm-ac-"+Math.floor(2e6*Math.random()).toString(36),null)}update(tr){let{state:state}=tr,conf=state.facet(completionConfig),active=(conf.override||state.languageDataAt("autocomplete",cur(state)).map(asSource)).map((source=>(this.active.find((s=>s.source==source))||new ActiveSource(source,this.active.some((a=>0!=a.state))?1:0)).update(tr,conf)));active.length==this.active.length&&active.every(((a,i)=>a==this.active[i]))&&(active=this.active);let open=this.open;open&&tr.docChanged&&(open=open.map(tr.changes)),tr.selection||active.some((a=>a.hasResult()&&tr.changes.touchesRange(a.from,a.to)))||!function(a,b){if(a==b)return!0;for(let iA=0,iB=0;;){for(;iA1==a.state))&&(open=null),!open&&active.every((a=>1!=a.state))&&active.some((a=>a.hasResult()))&&(active=active.map((a=>a.hasResult()?new ActiveSource(a.source,0):a)));for(let effect of tr.effects)effect.is(setSelectedEffect)&&(open=open&&open.setSelected(effect.value,this.id));return active==this.active&&open==this.open?this:new CompletionState(active,this.id,open)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:baseAttrs}}const baseAttrs={"aria-autocomplete":"list"};function makeAttrs(id,selected){let result={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":id};return selected>-1&&(result["aria-activedescendant"]=id+"-"+selected),result}const none=[];function getUserEvent(tr){return tr.isUserEvent("input.type")?"input":tr.isUserEvent("delete.backward")?"delete":null}class ActiveSource{constructor(source,state){let explicitPos=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;this.source=source,this.state=state,this.explicitPos=explicitPos}hasResult(){return!1}update(tr,conf){let event=getUserEvent(tr),value=this;event?value=value.handleUserEvent(tr,event,conf):tr.docChanged?value=value.handleChange(tr):tr.selection&&0!=value.state&&(value=new ActiveSource(value.source,0));for(let effect of tr.effects)if(effect.is(startCompletionEffect))value=new ActiveSource(value.source,1,effect.value?cur(tr.state):-1);else if(effect.is(closeCompletionEffect))value=new ActiveSource(value.source,0);else if(effect.is(setActiveEffect))for(let active of effect.value)active.source==value.source&&(value=active);return value}handleUserEvent(tr,type,conf){return"delete"!=type&&conf.activateOnTyping?new ActiveSource(this.source,1):this.map(tr.changes)}handleChange(tr){return tr.changes.touchesRange(cur(tr.startState))?new ActiveSource(this.source,0):this.map(tr.changes)}map(changes){return changes.empty||this.explicitPos<0?this:new ActiveSource(this.source,this.state,changes.mapPos(this.explicitPos))}}class ActiveResult extends ActiveSource{constructor(source,explicitPos,result,from,to){super(source,2,explicitPos),this.result=result,this.from=from,this.to=to}hasResult(){return!0}handleUserEvent(tr,type,conf){var _a;let from=tr.changes.mapPos(this.from),to=tr.changes.mapPos(this.to,1),pos=cur(tr.state);if((this.explicitPos<0?pos<=from:posto||"delete"==type&&cur(tr.startState)==this.from)return new ActiveSource(this.source,"input"==type&&conf.activateOnTyping?1:0);let updated,explicitPos=this.explicitPos<0?-1:tr.changes.mapPos(this.explicitPos);return function(validFor,state,from,to){if(!validFor)return!1;let text=state.sliceDoc(from,to);return"function"==typeof validFor?validFor(text,from,to,state):ensureAnchor(validFor,!0).test(text)}(this.result.validFor,tr.state,from,to)?new ActiveResult(this.source,explicitPos,this.result,from,to):this.result.update&&(updated=this.result.update(this.result,from,to,new CompletionContext(tr.state,pos,explicitPos>=0)))?new ActiveResult(this.source,explicitPos,updated,updated.from,null!==(_a=updated.to)&&void 0!==_a?_a:cur(tr.state)):new ActiveSource(this.source,1,explicitPos)}handleChange(tr){return tr.changes.touchesRange(this.from,this.to)?new ActiveSource(this.source,0):this.map(tr.changes)}map(mapping){return mapping.empty?this:new ActiveResult(this.source,this.explicitPos<0?-1:mapping.mapPos(this.explicitPos),this.result,mapping.mapPos(this.from),mapping.mapPos(this.to,1))}}const setActiveEffect=StateEffect.define({map:(sources,mapping)=>sources.map((s=>s.map(mapping)))}),setSelectedEffect=StateEffect.define(),completionState=StateField.define({create:()=>CompletionState.start(),update:(value,tr)=>value.update(tr),provide:f=>[showTooltip.from(f,(val=>val.tooltip)),EditorView.contentAttributes.from(f,(state=>state.attrs))]});function applyCompletion(view,option){const apply=option.completion.apply||option.completion.label;let result=view.state.field(completionState).active.find((a=>a.source==option.source));return result instanceof ActiveResult&&("string"==typeof apply?view.dispatch(Object.assign(Object.assign({},function(state,text,from,to){let{main:main}=state.selection,fromOff=from-main.from,toOff=to-main.from;return Object.assign(Object.assign({},state.changeByRange((range=>range!=main&&from!=to&&state.sliceDoc(range.from+fromOff,range.from+toOff)!=state.sliceDoc(from,to)?{range:range}:{changes:{from:range.from+fromOff,to:to==main.from?range.to:range.from+toOff,insert:text},range:EditorSelection.cursor(range.from+fromOff+text.length)}))),{userEvent:"input.complete"})}(view.state,apply,result.from,result.to)),{annotations:pickedCompletion.of(option.completion)})):apply(view,option.completion,result.from,result.to),!0)}function moveCompletionSelection(forward){let by=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"option";return view=>{let cState=view.state.field(completionState,!1);if(!cState||!cState.open||cState.open.disabled||Date.now()-cState.open.timestamp-1?cState.open.selected+step*(forward?1:-1):forward?0:length-1;return selected<0?selected="page"==by?0:length-1:selected>=length&&(selected="page"==by?length-1:0),view.dispatch({effects:setSelectedEffect.of(selected)}),!0}}class RunningQuery{constructor(active,context){this.active=active,this.context=context,this.time=Date.now(),this.updates=[],this.done=void 0}}const completionPlugin=ViewPlugin.fromClass(class{constructor(view){this.view=view,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let active of view.state.field(completionState).active)1==active.state&&this.startQuery(active)}update(update){let cState=update.state.field(completionState);if(!update.selectionSet&&!update.docChanged&&update.startState.field(completionState)==cState)return;let doesReset=update.transactions.some((tr=>(tr.selection||tr.docChanged)&&!getUserEvent(tr)));for(let i=0;i50&&Date.now()-query.time>1e3){for(let handler of query.context.abortListeners)try{handler()}catch(e){logException(this.view.state,e)}query.context.abortListeners=null,this.running.splice(i--,1)}else query.updates.push(...update.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=cState.active.some((a=>1==a.state&&!this.running.some((q=>q.active.source==a.source))))?setTimeout((()=>this.startUpdate()),50):-1,0!=this.composing)for(let tr of update.transactions)"input"==getUserEvent(tr)?this.composing=2:2==this.composing&&tr.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state:state}=this.view,cState=state.field(completionState);for(let active of cState.active)1!=active.state||this.running.some((r=>r.active.source==active.source))||this.startQuery(active)}startQuery(active){let{state:state}=this.view,pos=cur(state),context=new CompletionContext(state,pos,active.explicitPos==pos),pending=new RunningQuery(active,context);this.running.push(pending),Promise.resolve(active.source(context)).then((result=>{pending.context.aborted||(pending.done=result||null,this.scheduleAccept())}),(err=>{this.view.dispatch({effects:closeCompletionEffect.of(null)}),logException(this.view.state,err)}))}scheduleAccept(){this.running.every((q=>void 0!==q.done))?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout((()=>this.accept()),50))}accept(){var _a;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let updated=[],conf=this.view.state.facet(completionConfig);for(let i=0;ia.source==query.active.source));if(current&&1==current.state)if(null==query.done){let active=new ActiveSource(query.active.source,0);for(let tr of query.updates)active=active.update(tr,conf);1!=active.state&&updated.push(active)}else this.startQuery(current)}updated.length&&this.view.dispatch({effects:setActiveEffect.of(updated)})}},{eventHandlers:{blur(event){let state=this.view.state.field(completionState,!1);if(state&&state.tooltip&&this.view.state.facet(completionConfig).closeOnBlur){let dialog=state.open&&getTooltip(this.view,state.open.tooltip);dialog&&dialog.dom.contains(event.relatedTarget)||this.view.dispatch({effects:closeCompletionEffect.of(null)})}},compositionstart(){this.composing=1},compositionend(){3==this.composing&&setTimeout((()=>this.view.dispatch({effects:startCompletionEffect.of(!1)})),20),this.composing=0}}}),baseTheme$1=EditorView.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"".concat(400,"px"),boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"".concat(30,"px")},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"".concat(30,"px")},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class FieldPos{constructor(field,line,from,to){this.field=field,this.line=line,this.from=from,this.to=to}}class FieldRange{constructor(field,from,to){this.field=field,this.from=from,this.to=to}map(changes){let from=changes.mapPos(this.from,-1,MapMode.TrackDel),to=changes.mapPos(this.to,1,MapMode.TrackDel);return null==from||null==to?null:new FieldRange(this.field,from,to)}}class Snippet{constructor(lines,fieldPositions){this.lines=lines,this.fieldPositions=fieldPositions}instantiate(state,pos){let text=[],lineStart=[pos],lineObj=state.doc.lineAt(pos),baseIndent=/^\s*/.exec(lineObj.text)[0];for(let line of this.lines){if(text.length){let indent=baseIndent,tabs=/^\t*/.exec(line)[0].length;for(let i=0;inew FieldRange(pos.field,lineStart[pos.line]+pos.from,lineStart[pos.line]+pos.to)));return{text:text,ranges:ranges}}static parse(template){let m,fields=[],lines=[],positions=[];for(let line of template.split(/\r\n?|\n/)){for(;m=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line);){let seq=m[1]?+m[1]:null,name=m[2]||m[3]||"",found=-1;for(let i=0;i=found&&pos.field++}positions.push(new FieldPos(found,lines.length,m.index,m.index+name.length)),line=line.slice(0,m.index)+name+line.slice(m.index+m[0].length)}for(let esc;esc=/\\([{}])/.exec(line);){line=line.slice(0,esc.index)+esc[1]+line.slice(esc.index+esc[0].length);for(let pos of positions)pos.line==lines.length&&pos.from>esc.index&&(pos.from--,pos.to--)}lines.push(line)}return new Snippet(lines,positions)}}let fieldMarker=Decoration.widget({widget:new class extends WidgetType{toDOM(){let span=document.createElement("span");return span.className="cm-snippetFieldPosition",span}ignoreEvent(){return!1}}}),fieldRange=Decoration.mark({class:"cm-snippetField"});class ActiveSnippet{constructor(ranges,active){this.ranges=ranges,this.active=active,this.deco=Decoration.set(ranges.map((r=>(r.from==r.to?fieldMarker:fieldRange).range(r.from,r.to))))}map(changes){let ranges=[];for(let r of this.ranges){let mapped=r.map(changes);if(!mapped)return null;ranges.push(mapped)}return new ActiveSnippet(ranges,this.active)}selectionInsideField(sel){return sel.ranges.every((range=>this.ranges.some((r=>r.field==this.active&&r.from<=range.from&&r.to>=range.to))))}}const setActive=StateEffect.define({map:(value,changes)=>value&&value.map(changes)}),moveToField=StateEffect.define(),snippetState=StateField.define({create:()=>null,update(value,tr){for(let effect of tr.effects){if(effect.is(setActive))return effect.value;if(effect.is(moveToField)&&value)return new ActiveSnippet(value.ranges,effect.value)}return value&&tr.docChanged&&(value=value.map(tr.changes)),value&&tr.selection&&!value.selectionInsideField(tr.selection)&&(value=null),value},provide:f=>EditorView.decorations.from(f,(val=>val?val.deco:Decoration.none))});function fieldSelection(ranges,field){return EditorSelection.create(ranges.filter((r=>r.field==field)).map((r=>EditorSelection.range(r.from,r.to))))}function snippet(template){let snippet=Snippet.parse(template);return(editor,completion,from,to)=>{let{text:text,ranges:ranges}=snippet.instantiate(editor.state,from),spec={changes:{from:from,to:to,insert:Text.of(text)},scrollIntoView:!0,annotations:completion?pickedCompletion.of(completion):void 0};if(ranges.length&&(spec.selection=fieldSelection(ranges,0)),ranges.length>1){let active=new ActiveSnippet(ranges,0),effects=spec.effects=[setActive.of(active)];void 0===editor.state.field(snippetState,!1)&&effects.push(StateEffect.appendConfig.of([snippetState,addSnippetKeymap,snippetPointerHandler,baseTheme$1]))}editor.dispatch(editor.state.update(spec))}}function moveField(dir){return _ref44=>{let{state:state,dispatch:dispatch}=_ref44,active=state.field(snippetState,!1);if(!active||dir<0&&0==active.active)return!1;let next=active.active+dir,last=dir>0&&!active.ranges.some((r=>r.field==next+dir));return dispatch(state.update({selection:fieldSelection(active.ranges,next),effects:setActive.of(last?null:new ActiveSnippet(active.ranges,next))})),!0}}const defaultSnippetKeymap=[{key:"Tab",run:moveField(1),shift:moveField(-1)},{key:"Escape",run:_ref45=>{let{state:state,dispatch:dispatch}=_ref45;return!!state.field(snippetState,!1)&&(dispatch(state.update({effects:setActive.of(null)})),!0)}}],snippetKeymap=Facet.define({combine:maps=>maps.length?maps[0]:defaultSnippetKeymap}),addSnippetKeymap=Prec.highest(keymap.compute([snippetKeymap],(state=>state.facet(snippetKeymap))));function snippetCompletion(template,completion){return Object.assign(Object.assign({},completion),{apply:snippet(template)})}const snippetPointerHandler=EditorView.domEventHandlers({mousedown(event,view){let pos,active=view.state.field(snippetState,!1);if(!active||null==(pos=view.posAtCoords({x:event.clientX,y:event.clientY})))return!1;let match=active.ranges.find((r=>r.from<=pos&&r.to>=pos));return!(!match||match.field==active.active)&&(view.dispatch({selection:fieldSelection(active.ranges,match.field),effects:setActive.of(active.ranges.some((r=>r.field>match.field))?new ActiveSnippet(active.ranges,match.field):null)}),!0)}}),defaults={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},closeBracketEffect=StateEffect.define({map(value,mapping){let mapped=mapping.mapPos(value,-1,MapMode.TrackAfter);return null==mapped?void 0:mapped}}),closedBracket=new class extends RangeValue{};closedBracket.startSide=1,closedBracket.endSide=-1;const bracketState=StateField.define({create:()=>RangeSet.empty,update(value,tr){if(tr.selection){let lineStart=tr.state.doc.lineAt(tr.selection.main.head).from,prevLineStart=tr.startState.doc.lineAt(tr.startState.selection.main.head).from;lineStart!=tr.changes.mapPos(prevLineStart,-1)&&(value=RangeSet.empty)}value=value.map(tr.changes);for(let effect of tr.effects)effect.is(closeBracketEffect)&&(value=value.update({add:[closedBracket.range(effect.value,effect.value+1)]}));return value}});function closing(ch){for(let i=0;i<"()[]{}<>".length;i+=2)if("()[]{}<>".charCodeAt(i)==ch)return"()[]{}<>".charAt(i+1);return fromCodePoint(ch<128?ch:ch+1)}function config(state,pos){return state.languageDataAt("closeBrackets",pos)[0]||defaults}const android$1="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),inputHandler=EditorView.inputHandler.of(((view,from,to,insert)=>{if((android$1?view.composing:view.compositionStarted)||view.state.readOnly)return!1;let sel=view.state.selection.main;if(insert.length>2||2==insert.length&&1==codePointSize(codePointAt(insert,0))||from!=sel.from||to!=sel.to)return!1;let tr=function(state,bracket){let conf=config(state,state.selection.main.head),tokens=conf.brackets||defaults.brackets;for(let tok of tokens){let closed=closing(codePointAt(tok,0));if(bracket==tok)return closed==tok?handleSame(state,tok,tokens.indexOf(tok+tok+tok)>-1,conf):handleOpen(state,tok,closed,conf.before||defaults.before);if(bracket==closed&&closedBracketAt(state,state.selection.main.from))return handleClose(state,tok,closed)}return null}(view.state,insert);return!!tr&&(view.dispatch(tr),!0)})),closeBracketsKeymap=[{key:"Backspace",run:_ref46=>{let{state:state,dispatch:dispatch}=_ref46;if(state.readOnly)return!1;let tokens=config(state,state.selection.main.head).brackets||defaults.brackets,dont=null,changes=state.changeByRange((range=>{if(range.empty){let before=function(doc,pos){let prev=doc.sliceString(pos-2,pos);return codePointSize(codePointAt(prev,0))==prev.length?prev:prev.slice(1)}(state.doc,range.head);for(let token of tokens)if(token==before&&nextChar(state.doc,range.head)==closing(codePointAt(token,0)))return{changes:{from:range.head-token.length,to:range.head+token.length},range:EditorSelection.cursor(range.head-token.length)}}return{range:dont=range}}));return dont||dispatch(state.update(changes,{scrollIntoView:!0,userEvent:"delete.backward"})),!dont}}];function closedBracketAt(state,pos){let found=!1;return state.field(bracketState).between(0,state.doc.length,(from=>{from==pos&&(found=!0)})),found}function nextChar(doc,pos){let next=doc.sliceString(pos,pos+2);return next.slice(0,codePointSize(codePointAt(next,0)))}function handleOpen(state,open,close,closeBefore){let dont=null,changes=state.changeByRange((range=>{if(!range.empty)return{changes:[{insert:open,from:range.from},{insert:close,from:range.to}],effects:closeBracketEffect.of(range.to+open.length),range:EditorSelection.range(range.anchor+open.length,range.head+open.length)};let next=nextChar(state.doc,range.head);return!next||/\s/.test(next)||closeBefore.indexOf(next)>-1?{changes:{insert:open+close,from:range.head},effects:closeBracketEffect.of(range.head+open.length),range:EditorSelection.cursor(range.head+open.length)}:{range:dont=range}}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function handleClose(state,_open,close){let dont=null,changes=state.changeByRange((range=>range.empty&&nextChar(state.doc,range.head)==close?{changes:{from:range.head,to:range.head+close.length,insert:close},range:EditorSelection.cursor(range.head+close.length)}:dont={range:range}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function handleSame(state,token,allowTriple,config){let stringPrefixes=config.stringPrefixes||defaults.stringPrefixes,dont=null,changes=state.changeByRange((range=>{if(!range.empty)return{changes:[{insert:token,from:range.from},{insert:token,from:range.to}],effects:closeBracketEffect.of(range.to+token.length),range:EditorSelection.range(range.anchor+token.length,range.head+token.length)};let start,pos=range.head,next=nextChar(state.doc,pos);if(next==token){if(nodeStart(state,pos))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(closedBracketAt(state,pos)){let content=allowTriple&&state.sliceDoc(pos,pos+3*token.length)==token+token+token?token+token+token:token;return{changes:{from:pos,to:pos+content.length,insert:content},range:EditorSelection.cursor(pos+content.length)}}}else{if(allowTriple&&state.sliceDoc(pos-2*token.length,pos)==token+token&&(start=canStartStringAt(state,pos-2*token.length,stringPrefixes))>-1&&nodeStart(state,start))return{changes:{insert:token+token+token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)};if(state.charCategorizer(pos)(next)!=CharCategory.Word&&canStartStringAt(state,pos,stringPrefixes)>-1&&!function(state,pos,quoteToken,prefixes){let node=syntaxTree(state).resolveInner(pos,-1),maxPrefix=prefixes.reduce(((m,p)=>Math.max(m,p.length)),0);for(let i=0;i<5;i++){let start=state.sliceDoc(node.from,Math.min(node.to,node.from+quoteToken.length+maxPrefix)),quotePos=start.indexOf(quoteToken);if(!quotePos||quotePos>-1&&prefixes.indexOf(start.slice(0,quotePos))>-1){let first=node.firstChild;for(;first&&first.from==node.from&&first.to-first.from>quoteToken.length+quotePos;){if(state.sliceDoc(first.to-quoteToken.length,first.to)==quoteToken)return!1;first=first.firstChild}return!0}let parent=node.to==pos&&node.parent;if(!parent)break;node=parent}return!1}(state,pos,token,stringPrefixes))return{changes:{insert:token+token,from:pos},effects:closeBracketEffect.of(pos+token.length),range:EditorSelection.cursor(pos+token.length)}}return{range:dont=range}}));return dont?null:state.update(changes,{scrollIntoView:!0,userEvent:"input.type"})}function nodeStart(state,pos){let tree=syntaxTree(state).resolveInner(pos+1);return tree.parent&&tree.from==pos}function canStartStringAt(state,pos,prefixes){let charCat=state.charCategorizer(pos);if(charCat(state.sliceDoc(pos-1,pos))!=CharCategory.Word)return pos;for(let prefix of prefixes){let start=pos-prefix.length;if(state.sliceDoc(start,pos)==prefix&&charCat(state.sliceDoc(start-1,start))!=CharCategory.Word)return start}return-1}function autocompletion(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return[completionState,completionConfig.of(config),completionPlugin,completionKeymapExt,baseTheme$1]}const completionKeymap=[{key:"Ctrl-Space",run:view=>!!view.state.field(completionState,!1)&&(view.dispatch({effects:startCompletionEffect.of(!0)}),!0)},{key:"Escape",run:view=>{let cState=view.state.field(completionState,!1);return!(!cState||!cState.active.some((a=>0!=a.state)))&&(view.dispatch({effects:closeCompletionEffect.of(null)}),!0)}},{key:"ArrowDown",run:moveCompletionSelection(!0)},{key:"ArrowUp",run:moveCompletionSelection(!1)},{key:"PageDown",run:moveCompletionSelection(!0,"page")},{key:"PageUp",run:moveCompletionSelection(!1,"page")},{key:"Enter",run:view=>{let cState=view.state.field(completionState,!1);return!(view.state.readOnly||!cState||!cState.open||cState.open.selected<0||cState.open.disabled||Date.now()-cState.open.timestampstate.facet(completionConfig).defaultKeymap?[completionKeymap]:[])));class SelectedDiagnostic{constructor(from,to,diagnostic){this.from=from,this.to=to,this.diagnostic=diagnostic}}class LintState{constructor(diagnostics,panel,selected){this.diagnostics=diagnostics,this.panel=panel,this.selected=selected}static init(diagnostics,panel,state){let markedDiagnostics=diagnostics,diagnosticFilter=state.facet(lintConfig).markerFilter;diagnosticFilter&&(markedDiagnostics=diagnosticFilter(markedDiagnostics));let ranges=Decoration.set(markedDiagnostics.map((d=>d.from==d.to||d.from==d.to-1&&state.doc.lineAt(d.from).to==d.from?Decoration.widget({widget:new DiagnosticWidget(d),diagnostic:d}).range(d.from):Decoration.mark({attributes:{class:"cm-lintRange cm-lintRange-"+d.severity+(d.markClass?" "+d.markClass:"")},diagnostic:d}).range(d.from,d.to))),!0);return new LintState(ranges,panel,findDiagnostic(ranges))}}function findDiagnostic(diagnostics){let diagnostic=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,after=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,found=null;return diagnostics.between(after,1e9,((from,to,_ref47)=>{let{spec:spec}=_ref47;if(!diagnostic||spec.diagnostic==diagnostic)return found=new SelectedDiagnostic(from,to,spec.diagnostic),!1})),found}const setDiagnosticsEffect=StateEffect.define(),togglePanel=StateEffect.define(),movePanelSelection=StateEffect.define(),lintState=StateField.define({create:()=>new LintState(Decoration.none,null,null),update(value,tr){if(tr.docChanged){let mapped=value.diagnostics.map(tr.changes),selected=null;if(value.selected){let selPos=tr.changes.mapPos(value.selected.from,1);selected=findDiagnostic(mapped,value.selected.diagnostic,selPos)||findDiagnostic(mapped,null,selPos)}value=new LintState(mapped,value.panel,selected)}for(let effect of tr.effects)effect.is(setDiagnosticsEffect)?value=LintState.init(effect.value,value.panel,tr.state):effect.is(togglePanel)?value=new LintState(value.diagnostics,effect.value?LintPanel.open:null,value.selected):effect.is(movePanelSelection)&&(value=new LintState(value.diagnostics,value.panel,effect.value));return value},provide:f=>[showPanel.from(f,(val=>val.panel)),EditorView.decorations.from(f,(s=>s.diagnostics))]}),activeMark=Decoration.mark({class:"cm-lintRange cm-lintRange-active"});function diagnosticsTooltip(view,diagnostics){return crelt("ul",{class:"cm-tooltip-lint"},diagnostics.map((d=>renderDiagnostic(view,d,!1))))}const closeLintPanel=view=>{let field=view.state.field(lintState,!1);return!(!field||!field.panel)&&(view.dispatch({effects:togglePanel.of(!1)}),!0)},lintKeymap=[{key:"Mod-Shift-m",run:view=>{let field=view.state.field(lintState,!1);var state,effects;field&&field.panel||view.dispatch({effects:(state=view.state,effects=[togglePanel.of(!0)],state.field(lintState,!1)?effects:effects.concat(StateEffect.appendConfig.of(lintExtensions)))});let panel=getPanel(view,LintPanel.open);return panel&&panel.dom.querySelector(".cm-panel-lint ul").focus(),!0},preventDefault:!0},{key:"F8",run:view=>{let field=view.state.field(lintState,!1);if(!field)return!1;let sel=view.state.selection.main,next=field.diagnostics.iter(sel.to+1);return!(!next.value&&(next=field.diagnostics.iter(0),!next.value||next.from==sel.from&&next.to==sel.to))&&(view.dispatch({selection:{anchor:next.from,head:next.to},scrollIntoView:!0}),!0)}}],lintConfig=Facet.define({combine:input=>Object.assign({sources:input.map((i=>i.source))},combineConfig(input.map((i=>i.config)),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(a,b)=>a?b?u=>a(u)||b(u):a:b}))});function assignKeys(actions){let assigned=[];if(actions)actions:for(let{name:name}of actions){for(let i=0;ic.toLowerCase()==ch.toLowerCase()))){assigned.push(ch);continue actions}}assigned.push("")}return assigned}function renderDiagnostic(view,diagnostic,inPanel){var _a;let keys=inPanel?assignKeys(diagnostic.actions):[];return crelt("li",{class:"cm-diagnostic cm-diagnostic-"+diagnostic.severity},crelt("span",{class:"cm-diagnosticText"},diagnostic.renderMessage?diagnostic.renderMessage():diagnostic.message),null===(_a=diagnostic.actions)||void 0===_a?void 0:_a.map(((action,i)=>{let fired=!1,click=e=>{if(e.preventDefault(),fired)return;fired=!0;let found=findDiagnostic(view.state.field(lintState).diagnostics,diagnostic);found&&action.apply(view,found.from,found.to)},{name:name}=action,keyIndex=keys[i]?name.indexOf(keys[i]):-1,nameElt=keyIndex<0?name:[name.slice(0,keyIndex),crelt("u",name.slice(keyIndex,keyIndex+1)),name.slice(keyIndex+1)];return crelt("button",{type:"button",class:"cm-diagnosticAction",onclick:click,onmousedown:click,"aria-label":" Action: ".concat(name).concat(keyIndex<0?"":' (access key "'.concat(keys[i],')"'),".")},nameElt)})),diagnostic.source&&crelt("div",{class:"cm-diagnosticSource"},diagnostic.source))}class DiagnosticWidget extends WidgetType{constructor(diagnostic){super(),this.diagnostic=diagnostic}eq(other){return other.diagnostic==this.diagnostic}toDOM(){return crelt("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class PanelItem{constructor(view,diagnostic){this.diagnostic=diagnostic,this.id="item_"+Math.floor(4294967295*Math.random()).toString(16),this.dom=renderDiagnostic(view,diagnostic,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class LintPanel{constructor(view){this.view=view,this.items=[];this.list=crelt("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:event=>{if(27==event.keyCode)closeLintPanel(this.view),this.view.focus();else if(38==event.keyCode||33==event.keyCode)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(40==event.keyCode||34==event.keyCode)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(36==event.keyCode)this.moveSelection(0);else if(35==event.keyCode)this.moveSelection(this.items.length-1);else if(13==event.keyCode)this.view.focus();else{if(!(event.keyCode>=65&&event.keyCode<=90&&this.selectedIndex>=0))return;{let{diagnostic:diagnostic}=this.items[this.selectedIndex],keys=assignKeys(diagnostic.actions);for(let i=0;i{for(let i=0;icloseLintPanel(this.view)},"×")),this.update()}get selectedIndex(){let selected=this.view.state.field(lintState).selected;if(!selected)return-1;for(let i=0;i{let item,{spec:spec}=_ref49,found=-1;for(let j=i;ji&&(this.items.splice(i,found-i),needsSync=!0)),selected&&item.diagnostic==selected.diagnostic?item.dom.hasAttribute("aria-selected")||(item.dom.setAttribute("aria-selected","true"),newSelectedItem=item):item.dom.hasAttribute("aria-selected")&&item.dom.removeAttribute("aria-selected"),i++}));i({sel:newSelectedItem.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:_ref50=>{let{sel:sel,panel:panel}=_ref50;sel.toppanel.bottom&&(this.list.scrollTop+=sel.bottom-panel.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),needsSync&&this.sync()}sync(){let domPos=this.list.firstChild;function rm(){let prev=domPos;domPos=prev.nextSibling,prev.remove()}for(let item of this.items)if(item.dom.parentNode==this.list){for(;domPos!=item.dom;)rm();domPos=item.dom.nextSibling}else this.list.insertBefore(item.dom,domPos);for(;domPos;)rm()}moveSelection(selectedIndex){if(this.selectedIndex<0)return;let selection=findDiagnostic(this.view.state.field(lintState).diagnostics,this.items[selectedIndex].diagnostic);selection&&this.view.dispatch({selection:{anchor:selection.from,head:selection.to},scrollIntoView:!0,effects:movePanelSelection.of(selection)})}static open(view){return new LintPanel(view)}}function underline(color){return function(content){return'url(\'data:image/svg+xml,1&&void 0!==arguments[1]?arguments[1]:'viewBox="0 0 40 40"',">").concat(encodeURIComponent(content),"')")}(''),'width="6" height="3"')}const baseTheme=EditorView.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:underline("#d11")},".cm-lintRange-warning":{backgroundImage:underline("orange")},".cm-lintRange-info":{backgroundImage:underline("#999")},".cm-lintRange-hint":{backgroundImage:underline("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),lintExtensions=[lintState,EditorView.decorations.compute([lintState],(state=>{let{selected:selected,panel:panel}=state.field(lintState);return selected&&panel&&selected.from!=selected.to?Decoration.set([activeMark.range(selected.from,selected.to)]):Decoration.none})),function(source){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},setHover=StateEffect.define(),hoverState=StateField.define({create:()=>[],update(value,tr){if(value.length&&(options.hideOnChange&&(tr.docChanged||tr.selection)?value=[]:options.hideOn&&(value=value.filter((v=>!options.hideOn(tr,v)))),tr.docChanged)){let mapped=[];for(let tooltip of value){let newPos=tr.changes.mapPos(tooltip.pos,-1,MapMode.TrackDel);if(null!=newPos){let copy=Object.assign(Object.create(null),tooltip);copy.pos=newPos,null!=copy.end&&(copy.end=tr.changes.mapPos(copy.end)),mapped.push(copy)}}value=mapped}for(let effect of tr.effects)effect.is(setHover)&&(value=effect.value),effect.is(closeHoverTooltipEffect)&&(value=[]);return value},provide:f=>showHoverTooltip.from(f)});return[hoverState,ViewPlugin.define((view=>new HoverPlugin(view,source,hoverState,setHover,options.hoverTime||300))),showHoverTooltipHost]}((function(view,pos,side){let{diagnostics:diagnostics}=view.state.field(lintState),found=[],stackStart=2e8,stackEnd=0;diagnostics.between(pos-(side<0?1:0),pos+(side>0?1:0),((from,to,_ref48)=>{let{spec:spec}=_ref48;pos>=from&&pos<=to&&(from==to||(pos>from||side>0)&&(pos({dom:diagnosticsTooltip(view,found)})}:null}),{hideOn:function(tr,tooltip){let line=tr.startState.doc.lineAt(tooltip.pos);return!(!tr.effects.some((e=>e.is(setDiagnosticsEffect)))&&!tr.changes.touchesRange(line.from,line.to))}}),baseTheme],basicSetup=[lineNumbers(),activeLineGutterHighlighter,highlightSpecialChars(),history(),foldGutter(),drawSelection(),[dropCursorPos,drawDropCursor],EditorState.allowMultipleSelections.of(!0),EditorState.transactionFilter.of((tr=>{if(!tr.docChanged||!tr.isUserEvent("input.type")&&!tr.isUserEvent("input.complete"))return tr;let rules=tr.startState.languageDataAt("indentOnInput",tr.startState.selection.main.head);if(!rules.length)return tr;let doc=tr.newDoc,{head:head}=tr.newSelection.main,line=doc.lineAt(head);if(head>line.from+200)return tr;let lineStart=doc.sliceString(line.from,head);if(!rules.some((r=>r.test(lineStart))))return tr;let{state:state}=tr,last=-1,changes=[];for(let{head:head}of state.selection.ranges){let line=state.doc.lineAt(head);if(line.from==last)continue;last=line.from;let indent=getIndentation(state,line.from);if(null==indent)continue;let cur=/^\s*/.exec(line.text)[0],norm=indentString(state,indent);cur!=norm&&changes.push({from:line.from,to:line.from+cur.length,insert:norm})}return changes.length?[tr,{changes:changes,sequential:!0}]:tr})),syntaxHighlighting(defaultHighlightStyle,{fallback:!0}),bracketMatching(),[inputHandler,bracketState],autocompletion(),rectangularSelection(),crosshairCursor(),activeLineHighlighter,highlightSelectionMatches(),keymap.of([...closeBracketsKeymap,...defaultKeymap,...searchKeymap,...historyKeymap,...foldKeymap,...completionKeymap,...lintKeymap])];class Stack{constructor(p,stack,state,reducePos,pos,score,buffer,bufferBase,curContext){let lookAhead=arguments.length>9&&void 0!==arguments[9]?arguments[9]:0,parent=arguments.length>10?arguments[10]:void 0;this.p=p,this.stack=stack,this.state=state,this.reducePos=reducePos,this.pos=pos,this.score=score,this.buffer=buffer,this.bufferBase=bufferBase,this.curContext=curContext,this.lookAhead=lookAhead,this.parent=parent}toString(){return"[".concat(this.stack.filter(((_,i)=>i%3==0)).concat(this.state),"]@").concat(this.pos).concat(this.score?"!"+this.score:"")}static start(p,state){let pos=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,cx=p.parser.context;return new Stack(p,[],state,pos,pos,0,[],0,cx?new StackContext(cx,cx.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(state,start){this.stack.push(this.state,start,this.bufferBase+this.buffer.length),this.state=state}reduce(action){var _a;let depth=action>>19,type=65535&action,{parser:parser}=this.p,dPrec=parser.dynamicPrecedence(type);if(dPrec&&(this.score+=dPrec),0==depth)return this.pushState(parser.getGoto(this.state,type,!0),this.reducePos),type=2e3&&!(null===(_a=this.p.parser.nodeSet.types[type])||void 0===_a?void 0:_a.isAnonymous)&&(start==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=size):this.p.lastBigReductionSizebase;)this.stack.pop();this.reduceContext(type,start)}storeNode(term,start,end){let size=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,isReduce=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(0==term&&(!this.stack.length||this.stack[this.stack.length-1]0&&0==cur.buffer[top-4]&&cur.buffer[top-1]>-1){if(start==end)return;if(cur.buffer[top-2]>=start)return void(cur.buffer[top-2]=end)}}if(isReduce&&this.pos!=end){let index=this.buffer.length;if(index>0&&0!=this.buffer[index-4])for(;index>0&&this.buffer[index-2]>end;)this.buffer[index]=this.buffer[index-4],this.buffer[index+1]=this.buffer[index-3],this.buffer[index+2]=this.buffer[index-2],this.buffer[index+3]=this.buffer[index-1],index-=4,size>4&&(size-=4);this.buffer[index]=term,this.buffer[index+1]=start,this.buffer[index+2]=end,this.buffer[index+3]=size}else this.buffer.push(term,start,end,size)}shift(action,next,nextEnd){let start=this.pos;if(131072&action)this.pushState(65535&action,this.pos);else if(0==(262144&action)){let nextState=action,{parser:parser}=this.p;(nextEnd>this.pos||next<=parser.maxNode)&&(this.pos=nextEnd,parser.stateFlag(nextState,1)||(this.reducePos=nextEnd)),this.pushState(nextState,start),this.shiftContext(next,start),next<=parser.maxNode&&this.buffer.push(next,start,nextEnd,4)}else this.pos=nextEnd,this.shiftContext(next,start),next<=this.p.parser.maxNode&&this.buffer.push(next,start,nextEnd,4)}apply(action,next,nextEnd){65536&action?this.reduce(action):this.shift(action,next,nextEnd)}useNode(value,next){let index=this.p.reused.length-1;(index<0||this.p.reused[index]!=value)&&(this.p.reused.push(value),index++);let start=this.pos;this.reducePos=this.pos=start+value.length,this.pushState(next,start),this.buffer.push(index,start,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,value,this,this.p.stream.reset(this.pos-value.length)))}split(){let parent=this,off=parent.buffer.length;for(;off>0&&parent.buffer[off-2]>parent.reducePos;)off-=4;let buffer=parent.buffer.slice(off),base=parent.bufferBase+off;for(;parent&&base==parent.bufferBase;)parent=parent.parent;return new Stack(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,buffer,base,this.curContext,this.lookAhead,parent)}recoverByDelete(next,nextEnd){let isNode=next<=this.p.parser.maxNode;isNode&&this.storeNode(next,this.pos,nextEnd,4),this.storeNode(0,this.pos,nextEnd,isNode?8:4),this.pos=this.reducePos=nextEnd,this.score-=190}canShift(term){for(let sim=new SimulatedStack(this);;){let action=this.p.parser.stateSlot(sim.state,4)||this.p.parser.hasAction(sim.state,term);if(0==action)return!1;if(0==(65536&action))return!0;sim.reduce(action)}}recoverByInsert(next){if(this.stack.length>=300)return[];let nextStates=this.p.parser.nextStates(this.state);if(nextStates.length>8||this.stack.length>=120){let best=[];for(let s,i=0;i1&i&&v==s))||best.push(nextStates[i],s)}nextStates=best}let result=[];for(let i=0;i>19,term=65535&reduce,target=this.stack.length-3*depth;if(target<0||parser.getGoto(this.stack[target],term,!1)<0){let backup=this.findForcedReduction();if(null==backup)return!1;reduce=backup}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(reduce),!0}findForcedReduction(){let{parser:parser}=this.p,seen=[],explore=(state,depth)=>{if(!seen.includes(state))return seen.push(state),parser.allActions(state,(action=>{if(393216&action);else if(65536&action){let rDepth=(action>>19)-depth;if(rDepth>1){let term=65535&action,target=this.stack.length-3*rDepth;if(target>=0&&parser.getGoto(this.stack[target],term,!1)>=0)return rDepth<<19|65536|term}}else{let found=explore(action,depth+1);if(null!=found)return found}}))};return explore(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:parser}=this.p;return 65535==parser.data[parser.stateSlot(this.state,1)]&&!parser.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(other){if(this.state!=other.state||this.stack.length!=other.stack.length)return!1;for(let i=0;ithis.lookAhead&&(this.emitLookAhead(),this.lookAhead=lookAhead)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(tracker,context){this.tracker=tracker,this.context=context,this.hash=tracker.strict?tracker.hash(context):0}}var Recover;!function(Recover){Recover[Recover.Insert=200]="Insert",Recover[Recover.Delete=190]="Delete",Recover[Recover.Reduce=100]="Reduce",Recover[Recover.MaxNext=4]="MaxNext",Recover[Recover.MaxInsertStackDepth=300]="MaxInsertStackDepth",Recover[Recover.DampenInsertStackDepth=120]="DampenInsertStackDepth",Recover[Recover.MinBigReduction=2e3]="MinBigReduction"}(Recover||(Recover={}));class SimulatedStack{constructor(start){this.start=start,this.state=start.state,this.stack=start.stack,this.base=this.stack.length}reduce(action){let term=65535&action,depth=action>>19;0==depth?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(depth-1);let goto=this.start.p.parser.getGoto(this.stack[this.base-3],term,!0);this.state=goto}}class StackBufferCursor{constructor(stack,pos,index){this.stack=stack,this.pos=pos,this.index=index,this.buffer=stack.buffer,0==this.index&&this.maybeNext()}static create(stack){let pos=arguments.length>1&&void 0!==arguments[1]?arguments[1]:stack.bufferBase+stack.buffer.length;return new StackBufferCursor(stack,pos,pos-stack.bufferBase)}maybeNext(){let next=this.stack.parent;null!=next&&(this.index=this.stack.bufferBase-next.bufferBase,this.stack=next,this.buffer=next.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}function decodeArray(input){let Type=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Uint16Array;if("string"!=typeof input)return input;let array=null;for(let pos=0,out=0;pos=92&&next--,next>=34&&next--;let digit=next-32;if(digit>=46&&(digit-=46,stop=!0),value+=digit,stop)break;value*=46}array?array[out++]=value:array=new Type(value)}return array}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(input,ranges){this.input=input,this.ranges=ranges,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=ranges[0].from,this.range=ranges[0],this.end=ranges[ranges.length-1].to,this.readNext()}resolveOffset(offset,assoc){let range=this.range,index=this.rangeIndex,pos=this.pos+offset;for(;posrange.to:pos>=range.to;){if(index==this.ranges.length-1)return null;let next=this.ranges[++index];pos+=next.from-range.to,range=next}return pos}clipPos(pos){if(pos>=this.range.from&&pospos)return Math.max(pos,range.from);return this.end}peek(offset){let pos,result,idx=this.chunkOff+offset;if(idx>=0&&idx=this.chunk2Pos&&posrange.to&&(this.chunk2=this.chunk2.slice(0,range.to-pos)),result=this.chunk2.charCodeAt(0)}}return pos>=this.token.lookAhead&&(this.token.lookAhead=pos+1),result}acceptToken(token){let endOffset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,end=endOffset?this.resolveOffset(endOffset,-1):this.pos;if(null==end||end=this.chunk2Pos&&this.posthis.range.to?nextChunk.slice(0,this.range.to-this.pos):nextChunk,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1;for(this.chunkOff+=n;this.pos+n>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();n-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=n,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(pos,token){if(token?(this.token=token,token.start=pos,token.lookAhead=pos+1,token.value=token.extended=-1):this.token=nullToken,this.pos!=pos){if(this.pos=pos,pos==this.end)return this.setDone(),this;for(;pos=this.range.to;)this.range=this.ranges[++this.rangeIndex];pos>=this.chunkPos&&pos=this.chunkPos&&to<=this.chunkPos+this.chunk.length)return this.chunk.slice(from-this.chunkPos,to-this.chunkPos);if(from>=this.chunk2Pos&&to<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(from-this.chunk2Pos,to-this.chunk2Pos);if(from>=this.range.from&&to<=this.range.to)return this.input.read(from,to);let result="";for(let r of this.ranges){if(r.from>=to)break;r.to>from&&(result+=this.input.read(Math.max(r.from,from),Math.min(r.to,to)))}return result}}class TokenGroup{constructor(data,id){this.data=data,this.id=id}token(input,stack){let{parser:parser}=stack.p;readToken(this.data,input,stack,this.id,parser.data,parser.tokenPrecTable)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class LocalTokenGroup{constructor(data,precTable,elseToken){this.precTable=precTable,this.elseToken=elseToken,this.data="string"==typeof data?decodeArray(data):data}token(input,stack){let start=input.pos,skipped=0;for(;;){let atEof=input.next<0,nextPos=input.resolveOffset(1,1);if(readToken(this.data,input,stack,0,this.data,this.precTable),input.token.value>-1)break;if(null==this.elseToken)return;if(atEof||skipped++,null==nextPos)break;input.reset(nextPos,input.token)}skipped&&(input.reset(start,input.token),input.acceptToken(this.elseToken,skipped))}}LocalTokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(token){let options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.token=token,this.contextual=!!options.contextual,this.fallback=!!options.fallback,this.extend=!!options.extend}}function readToken(data,input,stack,group,precTable,precOffset){let state=0,groupMask=1<0){let term=data[i];if(dialect.allows(term)&&(-1==input.token.value||input.token.value==term||overrides(term,input.token.value,precTable,precOffset))){input.acceptToken(term);break}}let next=input.next,low=0,high=data[state+2];if(!(input.next<0&&high>low&&65535==data[accEnd+3*high-3]&&65535==data[accEnd+3*high-3])){for(;low>1,index=accEnd+mid+(mid<<1),from=data[index],to=data[index+1]||65536;if(next=to)){state=data[index+2],input.advance();continue scan}low=mid+1}}break}state=data[accEnd+3*high-1]}}function findOffset(data,start,term){for(let next,i=start;65535!=(next=data[i]);i++)if(next==term)return i-start;return-1}function overrides(token,prev,tableData,tableOffset){let iPrev=findOffset(tableData,tableOffset,prev);return iPrev<0||findOffset(tableData,tableOffset,token)pos)&&!cursor.type.isError)return side<0?Math.max(0,Math.min(cursor.to-1,pos-25)):Math.min(tree.length,Math.max(cursor.from+1,pos+25));if(side<0?cursor.prevSibling():cursor.nextSibling())break;if(!cursor.parent())return side<0?0:tree.length}}!function(Safety){Safety[Safety.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(fragments,nodeSet){this.fragments=fragments,this.nodeSet=nodeSet,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let fr=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(fr){for(this.safeFrom=fr.openStart?cutAt(fr.tree,fr.from+fr.offset,1)-fr.offset:fr.from,this.safeTo=fr.openEnd?cutAt(fr.tree,fr.to+fr.offset,-1)-fr.offset:fr.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(fr.tree),this.start.push(-fr.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(pos){if(pospos)return this.nextStart=start,null;if(next instanceof Tree){if(start==pos){if(start=Math.max(this.safeFrom,pos)&&(this.trees.push(next),this.start.push(start),this.index.push(0))}else this.index[last]++,this.nextStart=start+next.length}}}class TokenCache{constructor(parser,stream){this.stream=stream,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=parser.tokenizers.map((_=>new CachedToken))}getActions(stack){let actionIndex=0,main=null,{parser:parser}=stack.p,{tokenizers:tokenizers}=parser,mask=parser.stateSlot(stack.state,3),context=stack.curContext?stack.curContext.hash:0,lookAhead=0;for(let i=0;itoken.end+25&&(lookAhead=Math.max(token.lookAhead,lookAhead)),0!=token.value)){let startIndex=actionIndex;if(token.extended>-1&&(actionIndex=this.addActions(stack,token.extended,token.end,actionIndex)),actionIndex=this.addActions(stack,token.value,token.end,actionIndex),!tokenizer.extend&&(main=token,actionIndex>startIndex))break}}for(;this.actions.length>actionIndex;)this.actions.pop();return lookAhead&&stack.setLookAhead(lookAhead),main||stack.pos!=this.stream.end||(main=new CachedToken,main.value=stack.p.parser.eofTerm,main.start=main.end=stack.pos,actionIndex=this.addActions(stack,main.value,main.end,actionIndex)),this.mainToken=main,this.actions}getMainToken(stack){if(this.mainToken)return this.mainToken;let main=new CachedToken,{pos:pos,p:p}=stack;return main.start=pos,main.end=Math.min(pos+1,p.stream.end),main.value=pos==p.stream.end?p.parser.eofTerm:0,main}updateCachedToken(token,tokenizer,stack){let start=this.stream.clipPos(stack.pos);if(tokenizer.token(this.stream.reset(start,token),stack),token.value>-1){let{parser:parser}=stack.p;for(let i=0;i=0&&stack.p.parser.dialect.allows(result>>1)){0==(1&result)?token.value=result>>1:token.extended=result>>1;break}}}else token.value=0,token.end=this.stream.clipPos(start+1)}putAction(action,token,end,index){for(let i=0;i4*parser.bufferLength?new FragmentCursor(fragments,parser.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let stopped,stoppedTokens,stacks=this.stacks,pos=this.minStackPos,newStacks=this.stacks=[];if(this.bigReductionCount>300&&1==stacks.length){let[s]=stacks;for(;s.forceReduce()&&s.stack.length&&s.stack[s.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let i=0;ipos)newStacks.push(stack);else{if(this.advanceStack(stack,newStacks,stacks))continue;{stopped||(stopped=[],stoppedTokens=[]),stopped.push(stack);let tok=this.tokens.getMainToken(stack);stoppedTokens.push(tok.value,tok.end)}}break}}if(!newStacks.length){let finished=stopped&&function(stacks){let best=null;for(let stack of stacks){let stopped=stack.p.stoppedAt;(stack.pos==stack.p.stream.end||null!=stopped&&stack.pos>stopped)&&stack.p.parser.stateFlag(stack.state,2)&&(!best||best.scorethis.stoppedAt?stopped[0]:this.runRecovery(stopped,stoppedTokens,newStacks);if(finished)return this.stackToTree(finished.forceAll())}if(this.recovering){let maxRemaining=1==this.recovering?1:3*this.recovering;if(newStacks.length>maxRemaining)for(newStacks.sort(((a,b)=>b.score-a.score));newStacks.length>maxRemaining;)newStacks.pop();newStacks.some((s=>s.reducePos>pos))&&this.recovering--}else if(newStacks.length>1){outer:for(let i=0;i500&&other.buffer.length>500){if(!((stack.score-other.score||stack.buffer.length-other.buffer.length)>0)){newStacks.splice(i--,1);continue outer}newStacks.splice(j--,1)}}}newStacks.length>12&&newStacks.splice(12,newStacks.length-12)}this.minStackPos=newStacks[0].pos;for(let i=1;i ":"";if(null!=this.stoppedAt&&start>this.stoppedAt)return stack.forceReduce()?stack:null;if(this.fragments){let strictCx=stack.curContext&&stack.curContext.tracker.strict,cxHash=strictCx?stack.curContext.hash:0;for(let cached=this.fragments.nodeAt(start);cached;){let match=this.parser.nodeSet.types[cached.type.id]==cached.type?parser.getGoto(stack.state,cached.type.id):-1;if(match>-1&&cached.length&&(!strictCx||(cached.prop(NodeProp.contextHash)||0)==cxHash))return stack.useNode(cached,match),verbose&&console.log(base+this.stackID(stack)+" (via reuse of ".concat(parser.getName(cached.type.id),")")),!0;if(!(cached instanceof Tree)||0==cached.children.length||cached.positions[0]>0)break;let inner=cached.children[0];if(!(inner instanceof Tree&&0==cached.positions[0]))break;cached=inner}}let defaultReduce=parser.stateSlot(stack.state,4);if(defaultReduce>0)return stack.reduce(defaultReduce),verbose&&console.log(base+this.stackID(stack)+" (via always-reduce ".concat(parser.getName(65535&defaultReduce),")")),!0;if(stack.stack.length>=15e3)for(;stack.stack.length>9e3&&stack.forceReduce(););let actions=this.tokens.getActions(stack);for(let i=0;istart?stacks.push(localStack):split.push(localStack)}return!1}advanceFully(stack,newStacks){let pos=stack.pos;for(;;){if(!this.advanceStack(stack,null,null))return!1;if(stack.pos>pos)return pushStackDedup(stack,newStacks),!0}}runRecovery(stacks,tokens,newStacks){let finished=null,restarted=!1;for(let i=0;i ":"";if(stack.deadEnd){if(restarted)continue;if(restarted=!0,stack.restart(),verbose&&console.log(base+this.stackID(stack)+" (restarted)"),this.advanceFully(stack,newStacks))continue}let force=stack.split(),forceBase=base;for(let j=0;force.forceReduce()&&j<10;j++){if(verbose&&console.log(forceBase+this.stackID(force)+" (via force-reduce)"),this.advanceFully(force,newStacks))break;verbose&&(forceBase=this.stackID(force)+" -> ")}for(let insert of stack.recoverByInsert(token))verbose&&console.log(base+this.stackID(insert)+" (via recover-insert)"),this.advanceFully(insert,newStacks);this.stream.end>stack.pos?(tokenEnd==stack.pos&&(tokenEnd++,token=0),stack.recoverByDelete(token,tokenEnd),verbose&&console.log(base+this.stackID(stack)+" (via recover-delete ".concat(this.parser.getName(token),")")),pushStackDedup(stack,newStacks)):(!finished||finished.scorex;class ContextTracker{constructor(spec){this.start=spec.start,this.shift=spec.shift||id,this.reduce=spec.reduce||id,this.reuse=spec.reuse||id,this.hash=spec.hash||(()=>0),this.strict=!1!==spec.strict}}class LRParser extends Parser{constructor(spec){if(super(),this.wrappers=[],14!=spec.version)throw new RangeError("Parser version (".concat(spec.version,") doesn't match runtime version (",14,")"));let nodeNames=spec.nodeNames.split(" ");this.minRepeatTerm=nodeNames.length;for(let i=0;ispec.topRules[r][1])),nodeProps=[];for(let i=0;i=0)setProp(next,prop,propSpec[i++]);else{let value=propSpec[i+-next];for(let j=-next;j>0;j--)setProp(propSpec[i++],prop,value);i++}}}this.nodeSet=new NodeSet(nodeNames.map(((name,i)=>NodeType.define({name:i>=this.minRepeatTerm?void 0:name,id:i,props:nodeProps[i],top:topTerms.indexOf(i)>-1,error:0==i,skipped:spec.skippedNodes&&spec.skippedNodes.indexOf(i)>-1})))),spec.propSources&&(this.nodeSet=this.nodeSet.extend(...spec.propSources)),this.strict=!1,this.bufferLength=DefaultBufferLength;let tokenArray=decodeArray(spec.tokenData);this.context=spec.context,this.specializerSpecs=spec.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let i=0;i"number"==typeof value?new TokenGroup(tokenArray,value):value)),this.topRules=spec.topRules,this.dialects=spec.dialects||{},this.dynamicPrecedences=spec.dynamicPrecedences||null,this.tokenPrecTable=spec.tokenPrec,this.termNames=spec.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(input,fragments,ranges){let parse=new Parse(this,input,fragments,ranges);for(let w of this.wrappers)parse=w(parse,input,fragments,ranges);return parse}getGoto(state,term){let loose=arguments.length>2&&void 0!==arguments[2]&&arguments[2],table=this.goto;if(term>=table[0])return-1;for(let pos=table[term+1];;){let groupTag=table[pos++],last=1&groupTag,target=table[pos++];if(last&&loose)return target;for(let end=pos+(groupTag>>1);pos0}validAction(state,action){return!!this.allActions(state,(a=>a==action||null))}allActions(state,action){let deflt=this.stateSlot(state,4),result=deflt?action(deflt):void 0;for(let i=this.stateSlot(state,1);null==result;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=pair(this.data,i+2)}result=action(pair(this.data,i+1))}return result}nextStates(state){let result=[];for(let i=this.stateSlot(state,1);;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=pair(this.data,i+2)}if(0==(1&this.data[i+2])){let value=this.data[i+1];result.some(((v,i)=>1&i&&v==value))||result.push(this.data[i],value)}}return result}configure(config){let copy=Object.assign(Object.create(LRParser.prototype),this);if(config.props&&(copy.nodeSet=this.nodeSet.extend(...config.props)),config.top){let info=this.topRules[config.top];if(!info)throw new RangeError("Invalid top rule name ".concat(config.top));copy.top=info}return config.tokenizers&&(copy.tokenizers=this.tokenizers.map((t=>{let found=config.tokenizers.find((r=>r.from==t));return found?found.to:t}))),config.specializers&&(copy.specializers=this.specializers.slice(),copy.specializerSpecs=this.specializerSpecs.map(((s,i)=>{let found=config.specializers.find((r=>r.from==s.external));if(!found)return s;let spec=Object.assign(Object.assign({},s),{external:found.to});return copy.specializers[i]=getSpecializer(spec),spec}))),config.contextTracker&&(copy.context=config.contextTracker),config.dialect&&(copy.dialect=this.parseDialect(config.dialect)),null!=config.strict&&(copy.strict=config.strict),config.wrap&&(copy.wrappers=copy.wrappers.concat(config.wrap)),null!=config.bufferLength&&(copy.bufferLength=config.bufferLength),copy}hasWrappers(){return this.wrappers.length>0}getName(term){return this.termNames?this.termNames[term]:String(term<=this.maxNode&&this.nodeSet.types[term].name||term)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(term){let prec=this.dynamicPrecedences;return null==prec?0:prec[term]||0}parseDialect(dialect){let values=Object.keys(this.dialects),flags=values.map((()=>!1));if(dialect)for(let part of dialect.split(" ")){let id=values.indexOf(part);id>=0&&(flags[id]=!0)}let disabled=null;for(let i=0;ispec.external(value,stack)<<1|mask}return spec.get}const selfClosers$1={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},closeOnOpen={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function isSpace(ch){return 9==ch||10==ch||13==ch||32==ch}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(input,offset){let pos=input.pos+offset;if(cachedPos==pos&&cachedInput==input)return cachedName;let next=input.peek(offset);for(;isSpace(next);)next=input.peek(++offset);let name="";for(;45==(ch=next)||46==ch||58==ch||ch>=65&&ch<=90||95==ch||ch>=97&&ch<=122||ch>=161;)name+=String.fromCharCode(next),next=input.peek(++offset);var ch;return cachedInput=input,cachedPos=pos,cachedName=name?name.toLowerCase():next==question||next==bang?void 0:null}const question=63,bang=33;function ElementContext(name,parent){this.name=name,this.parent=parent,this.hash=parent?parent.hash:0;for(let i=0;istartTagTerms.indexOf(term)>-1?new ElementContext(tagNameAfter(input,1)||"",context):context,reduce:(context,term)=>20==term&&context?context.parent:context,reuse(context,node,stack,input){let type=node.type.id;return 6==type||36==type?new ElementContext(tagNameAfter(input,1)||"",context):context},hash:context=>context?context.hash:0,strict:!1}),tagStart=new ExternalTokenizer(((input,stack)=>{if(60!=input.next)return void(input.next<0&&stack.context&&input.acceptToken(57));input.advance();let close=47==input.next;close&&input.advance();let name=tagNameAfter(input,0);if(void 0===name)return;if(!name)return input.acceptToken(close?14:6);let parent=stack.context?stack.context.name:null;if(close){if(name==parent)return input.acceptToken(11);if(parent&&implicitlyClosed[parent])return input.acceptToken(57,-2);if(stack.dialectEnabled(0))return input.acceptToken(12);for(let cx=stack.context;cx;cx=cx.parent)if(cx.name==name)return;input.acceptToken(13)}else{if("script"==name)return input.acceptToken(7);if("style"==name)return input.acceptToken(8);if("textarea"==name)return input.acceptToken(9);if(selfClosers$1.hasOwnProperty(name))return input.acceptToken(10);parent&&closeOnOpen[parent]&&closeOnOpen[parent][name]?input.acceptToken(57,-1):input.acceptToken(6)}}),{contextual:!0}),commentContent=new ExternalTokenizer((input=>{for(let dashes=0,i=0;;i++){if(input.next<0){i&&input.acceptToken(58);break}if(45==input.next)dashes++;else{if(62==input.next&&dashes>=2){i>3&&input.acceptToken(58,-2);break}dashes=0}input.advance()}}));const endTag=new ExternalTokenizer(((input,stack)=>{if(47==input.next&&62==input.peek(1)){let selfClosing=stack.dialectEnabled(1)||function(context){for(;context;context=context.parent)if("svg"==context.name||"math"==context.name)return!0;return!1}(stack.context);input.acceptToken(selfClosing?5:4,2)}else 62==input.next&&input.acceptToken(4,1)}));function contentTokenizer(tag,textToken,endToken){let lastState=2+tag.length;return new ExternalTokenizer((input=>{for(let state=0,matchedLen=0,i=0;;i++){if(input.next<0){i&&input.acceptToken(textToken);break}if(0==state&&60==input.next||1==state&&47==input.next||state>=2&&statematchedLen?input.acceptToken(textToken,-matchedLen):input.acceptToken(endToken,-(matchedLen-2));break}if((10==input.next||13==input.next)&&i){input.acceptToken(textToken,1);break}state=matchedLen=0}else matchedLen++;input.advance()}}))}const scriptTokens=contentTokenizer("script",54,1),styleTokens=contentTokenizer("style",55,2),textareaTokens=contentTokenizer("textarea",56,3),htmlHighlighting=styleTags({"Text RawText":tags$1.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":tags$1.angleBracket,TagName:tags$1.tagName,"MismatchedCloseTag/TagName":[tags$1.tagName,tags$1.invalid],AttributeName:tags$1.attributeName,"AttributeValue UnquotedAttributeValue":tags$1.attributeValue,Is:tags$1.definitionOperator,"EntityReference CharacterReference":tags$1.character,Comment:tags$1.blockComment,ProcessingInst:tags$1.processingInstruction,DoctypeDecl:tags$1.documentMeta}),parser$2=LRParser.deserialize({version:14,states:",xOVO!rOOO!WQ#tO'#CqO!]Q#tO'#CzO!bQ#tO'#C}O!gQ#tO'#DQO!lQ#tO'#DSO!qOaO'#CpO!|ObO'#CpO#XOdO'#CpO$eO!rO'#CpOOO`'#Cp'#CpO$lO$fO'#DTO$tQ#tO'#DVO$yQ#tO'#DWOOO`'#Dk'#DkOOO`'#DY'#DYQVO!rOOO%OQ&rO,59]O%WQ&rO,59fO%`Q&rO,59iO%hQ&rO,59lO%sQ&rO,59nOOOa'#D^'#D^O%{OaO'#CxO&WOaO,59[OOOb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!ZlX~OP!WO!Z!XO~O!XiOQoX!ZoX~OQ!ZO!Z!XO~O!YlORrX!ZrX~OR!]O!Z!XO~O!Z!XO~P#dOf!_O~O![sO!e!aO~OS!bO~OS!cO~Oi!dOSgXhgXTgX~OS!fOhyO~OS!gOhyO~OS!hOhyO~OS!iOT!jOhyO~OS!jOhyO~Of!kO~Of!lO~Of!mO~OS!nO~Ok!qO!`!oO!b!pO~OS!rO~OS!sO~OS!tO~Oa!uOb!uOc!uO!`!wO!a!uO~Oa!xOb!xOc!xO!b!wO!c!xO~Oa!uOb!uOc!uO!`!{O!a!uO~Oa!xOb!xOc!xO!b!{O!c!xO~OT~bac!dx{!d~",goto:"%p!`PPPPPPPPPPPPPPPPPPPP!a!gP!mPP!yP!|#P#S#Y#]#`#f#i#l#r#x!aP!a!aP$O$U$l$r$x%O%U%[%bPPPPPPPP%hX^OX`pXUOX`pezabcde{}!P!R!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ}bQ!PcQ!RdQ!UeZ!e{}!P!R!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag EndTag SelfClosingEndTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:67,context:elementContext,nodeProps:[["closedBy",-10,1,2,3,7,8,9,10,11,12,13,"EndTag",6,"EndTag SelfClosingEndTag",-4,21,30,33,36,"CloseTag"],["openedBy",4,"StartTag StartCloseTag",5,"StartTag",-4,29,32,35,37,"OpenTag"],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s!Hpsw!Ncwx!Hpx!P!Nc!P!Q!Hp!Q!_!Nc!_!a!Hp!a!b# p!b#s!Nc#s$f!Hp$f;'S!Nc;'S;=`#!}<%l?Ah!Nc?Ah?BY!Hp?BY?Mn!Nc?MnO!HpT# ubhSOq!Hpqr!Ncrs!Hpsw!Ncwx!Hpx!P!Nc!P!Q!Hp!Q!_!Nc!_!`!Hp!`!a!If!a#s!Nc#s$f!Hp$f;'S!Nc;'S;=`#!}<%l?Ah!Nc?Ah?BY!Hp?BY?Mn!Nc?MnO!HpT##QP;=`<%l!Nc!V##^chS!a`!cpOq!G_qr!Eyrs!HUsv!Eyvw!Ncwx!Jvx!P!Ey!P!Q!G_!Q!_!Ey!_!`!G_!`!a!Mm!a#s!Ey#s$f!G_$f;'S!Ey;'S;=`#$i<%l?Ah!Ey?Ah?BY!G_?BY?Mn!Ey?MnO!G_!V#$lP;=`<%l!Ey!V#$zXiS`P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X",tokenizers:[scriptTokens,styleTokens,textareaTokens,endTag,tagStart,commentContent,0,1,2,3,4,5],topRules:{Document:[0,15]},dialects:{noMatch:0,selfClosing:485},tokenPrec:487});function getAttrs(openTag,input){let attrs=Object.create(null);for(let att of openTag.getChildren(23)){let name=att.getChild(24),value=att.getChild(26)||att.getChild(27);name&&(attrs[input.read(name.from,name.to)]=value?26==value.type.id?input.read(value.from+1,value.to-1):input.read(value.from,value.to):"")}return attrs}function findTagName(openTag,input){let tagNameNode=openTag.getChild(22);return tagNameNode?input.read(tagNameNode.from,tagNameNode.to):" "}function maybeNest(node,input,tags){let attrs;for(let tag of tags)if(!tag.attrs||tag.attrs(attrs||(attrs=getAttrs(node.node.parent.firstChild,input))))return{parser:tag.parser};return null}function configureNesting(){let tags=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],attributes=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],script=[],style=[],textarea=[],other=[];for(let tag of tags){("script"==tag.tag?script:"style"==tag.tag?style:"textarea"==tag.tag?textarea:other).push(tag)}let attrs=attributes.length?Object.create(null):null;for(let attr of attributes)(attrs[attr.name]||(attrs[attr.name]=[])).push(attr);return parseMixed(((node,input)=>{let id=node.type.id;if(28==id)return maybeNest(node,input,script);if(31==id)return maybeNest(node,input,style);if(34==id)return maybeNest(node,input,textarea);if(20==id&&other.length){let attrs,n=node.node,open=n.firstChild,tagName=open&&findTagName(open,input);if(tagName)for(let tag of other)if(tag.tag==tagName&&(!tag.attrs||tag.attrs(attrs||(attrs=getAttrs(n,input))))){let close=n.lastChild;return{parser:tag.parser,overlay:[{from:open.to,to:37==close.type.id?close.from:n.to}]}}}if(attrs&&23==id){let nameNode,n=node.node;if(nameNode=n.firstChild){let matches=attrs[input.read(nameNode.from,nameNode.to)];if(matches)for(let attr of matches){if(attr.tagName&&attr.tagName!=findTagName(n.parent,input))continue;let value=n.lastChild;if(26==value.type.id){let from=value.from+1,last=value.lastChild,to=value.to-(last&&last.isError?0:1);if(to>from)return{parser:attr.parser,overlay:[{from:from,to:to}]}}else if(27==value.type.id)return{parser:attr.parser,overlay:[{from:value.from,to:value.to}]}}}}return null}))}const space$1=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288];function isAlpha(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=161}const identifiers=new ExternalTokenizer(((input,stack)=>{for(let inside=!1,dashes=0,i=0;;i++){let{next:next}=input;if(!(isAlpha(next)||45==next||95==next||inside&&(ch=next,ch>=48&&ch<=57))){inside&&input.acceptToken(40==next?97:2==dashes&&stack.canShift(2)?2:98);break}!inside&&(45!=next||i>0)&&(inside=!0),dashes===i&&45==next&&dashes++,input.advance()}var ch})),descendant=new ExternalTokenizer((input=>{if(space$1.includes(input.peek(-1))){let{next:next}=input;(isAlpha(next)||95==next||35==next||46==next||91==next||58==next||45==next)&&input.acceptToken(96)}})),unitToken=new ExternalTokenizer((input=>{if(!space$1.includes(input.peek(-1))){let{next:next}=input;if(37==next&&(input.advance(),input.acceptToken(1)),isAlpha(next)){do{input.advance()}while(isAlpha(input.next));input.acceptToken(1)}}})),cssHighlighting=styleTags({"AtKeyword import charset namespace keyframes media supports":tags$1.definitionKeyword,"from to selector":tags$1.keyword,NamespaceName:tags$1.namespace,KeyframeName:tags$1.labelName,KeyframeRangeName:tags$1.operatorKeyword,TagName:tags$1.tagName,ClassName:tags$1.className,PseudoClassName:tags$1.constant(tags$1.className),IdName:tags$1.labelName,"FeatureName PropertyName":tags$1.propertyName,AttributeName:tags$1.attributeName,NumberLiteral:tags$1.number,KeywordQuery:tags$1.keyword,UnaryQueryOp:tags$1.operatorKeyword,"CallTag ValueName":tags$1.atom,VariableName:tags$1.variableName,Callee:tags$1.operatorKeyword,Unit:tags$1.unit,"UniversalSelector NestingSelector":tags$1.definitionOperator,MatchOp:tags$1.compareOperator,"ChildOp SiblingOp, LogicOp":tags$1.logicOperator,BinOp:tags$1.arithmeticOperator,Important:tags$1.modifier,Comment:tags$1.blockComment,ColorLiteral:tags$1.color,"ParenthesizedContent StringLiteral":tags$1.string,":":tags$1.punctuation,"PseudoOp #":tags$1.derefOperator,"; ,":tags$1.separator,"( )":tags$1.paren,"[ ]":tags$1.squareBracket,"{ }":tags$1.brace}),spec_callee={__proto__:null,lang:32,"nth-child":32,"nth-last-child":32,"nth-of-type":32,"nth-last-of-type":32,dir:32,"host-context":32,url:60,"url-prefix":60,domain:60,regexp:60,selector:134},spec_AtKeyword={__proto__:null,"@import":114,"@media":138,"@charset":142,"@namespace":146,"@keyframes":152,"@supports":164},spec_identifier$1={__proto__:null,not:128,only:128},parser$1=LRParser.deserialize({version:14,states:"9bQYQ[OOO#_Q[OOP#fOWOOOOQP'#Cd'#CdOOQP'#Cc'#CcO#kQ[O'#CfO$_QXO'#CaO$fQ[O'#ChO$qQ[O'#DPO$vQ[O'#DTOOQP'#Ej'#EjO${QdO'#DeO%gQ[O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X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^bBbU]QOy%^z![%^![!]Bt!];'S%^;'S;=`%o<%lO%^bB{S^Qo`Oy%^z;'S%^;'S;=`%o<%lO%^nC^S!W^Oy%^z;'S%^;'S;=`%o<%lO%^dCoSzSOy%^z;'S%^;'S;=`%o<%lO%^bDQU|QOy%^z!`%^!`!aDd!a;'S%^;'S;=`%o<%lO%^bDkS|Qo`Oy%^z;'S%^;'S;=`%o<%lO%^bDzWOy%^z!c%^!c!}Ed!}#T%^#T#oEd#o;'S%^;'S;=`%o<%lO%^bEk[!YQo`Oy%^z}%^}!OEd!O!Q%^!Q![Ed![!c%^!c!}Ed!}#T%^#T#oEd#o;'S%^;'S;=`%o<%lO%^bFfSxQOy%^z;'S%^;'S;=`%o<%lO%^lFwSv[Oy%^z;'S%^;'S;=`%o<%lO%^bGWUOy%^z#b%^#b#cGj#c;'S%^;'S;=`%o<%lO%^bGoUo`Oy%^z#W%^#W#XHR#X;'S%^;'S;=`%o<%lO%^bHYS!`Qo`Oy%^z;'S%^;'S;=`%o<%lO%^bHiUOy%^z#f%^#f#gHR#g;'S%^;'S;=`%o<%lO%^fIQS!RUOy%^z;'S%^;'S;=`%o<%lO%^nIcS!Q^Oy%^z;'S%^;'S;=`%o<%lO%^fItU!PQOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^`JZP;=`<%l$}",tokenizers:[descendant,unitToken,identifiers,1,2,3,4,new LocalTokenGroup("m~RRYZ[z{a~~g~aO#Z~~dP!P!Qg~lO#[~~",28,102)],topRules:{StyleSheet:[0,4],Styles:[1,84]},specialized:[{term:97,get:value=>spec_callee[value]||-1},{term:56,get:value=>spec_AtKeyword[value]||-1},{term:98,get:value=>spec_identifier$1[value]||-1}],tokenPrec:1169});let _properties=null;function properties(){if(!_properties&&"object"==typeof document&&document.body){let{style:style}=document.body,names=[],seen=new Set;for(let prop in style)"cssText"!=prop&&"cssFloat"!=prop&&"string"==typeof style[prop]&&(/[A-Z]/.test(prop)&&(prop=prop.replace(/[A-Z]/g,(ch=>"-"+ch.toLowerCase()))),seen.has(prop)||(names.push(prop),seen.add(prop)));_properties=names.sort().map((name=>({type:"property",label:name})))}return _properties||[]}const pseudoClasses=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map((name=>({type:"class",label:name}))),values=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map((name=>({type:"keyword",label:name}))).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map((name=>({type:"constant",label:name})))),tags=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map((name=>({type:"type",label:name}))),identifier$1=/^(\w[\w-]*|-\w[\w-]*|)$/,variable=/^-(-[\w-]*)?$/;const VariablesByNode=new NodeWeakMap,declSelector=["Declaration"];function astTop(node){for(let cur=node;;){if(cur.type.isTop)return cur;if(!(cur=cur.parent))return node}}function variableNames(doc,node,isVariable){if(node.to-node.from>4096){let known=VariablesByNode.get(node);if(known)return known;let result=[],seen=new Set,cursor=node.cursor(IterMode.IncludeAnonymous);if(cursor.firstChild())do{for(let option of variableNames(doc,cursor.node,isVariable))seen.has(option.label)||(seen.add(option.label),result.push(option))}while(cursor.nextSibling());return VariablesByNode.set(node,result),result}{let result=[],seen=new Set;return node.cursor().iterate((node=>{var _a;if(isVariable(node)&&node.matchContext(declSelector)&&":"==(null===(_a=node.node.nextSibling)||void 0===_a?void 0:_a.name)){let name=doc.sliceString(node.from,node.to);seen.has(name)||(seen.add(name),result.push({label:name,type:"variable"}))}})),result}}const cssCompletionSource=(isVariable=n=>"VariableName"==n.name,context=>{let{state:state,pos:pos}=context,node=syntaxTree(state).resolveInner(pos,-1),isDash=node.type.isError&&node.from==node.to-1&&"-"==state.doc.sliceString(node.from,node.to);if("PropertyName"==node.name||(isDash||"TagName"==node.name)&&/^(Block|Styles)$/.test(node.resolve(node.to).name))return{from:node.from,options:properties(),validFor:identifier$1};if("ValueName"==node.name)return{from:node.from,options:values,validFor:identifier$1};if("PseudoClassName"==node.name)return{from:node.from,options:pseudoClasses,validFor:identifier$1};if(isVariable(node)||(context.explicit||isDash)&&function(node,doc){var _a;if(("("==node.name||node.type.isError)&&(node=node.parent||node),"ArgList"!=node.name)return!1;let callee=null===(_a=node.parent)||void 0===_a?void 0:_a.firstChild;return"Callee"==(null==callee?void 0:callee.name)&&"var"==doc.sliceString(callee.from,callee.to)}(node,state.doc))return{from:isVariable(node)||isDash?node.from:pos,options:variableNames(state.doc,astTop(node),isVariable),validFor:variable};if("TagName"==node.name){for(let{parent:parent}=node;parent;parent=parent.parent)if("Block"==parent.name)return{from:node.from,options:properties(),validFor:identifier$1};return{from:node.from,options:tags,validFor:identifier$1}}if(!context.explicit)return null;let above=node.resolve(pos),before=above.childBefore(pos);return before&&":"==before.name&&"PseudoClassSelector"==above.name?{from:pos,options:pseudoClasses,validFor:identifier$1}:before&&":"==before.name&&"Declaration"==above.name||"ArgList"==above.name?{from:pos,options:values,validFor:identifier$1}:"Block"==above.name||"Styles"==above.name?{from:pos,options:properties(),validFor:identifier$1}:null});var isVariable;const cssLanguage=LRLanguage.define({name:"css",parser:parser$1.configure({props:[indentNodeProp.add({Declaration:continuedIndent()}),foldNodeProp.add({Block:foldInside})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function css(){return new LanguageSupport(cssLanguage,cssLanguage.data.of({autocomplete:cssCompletionSource}))}const space=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],trackNewline=new ContextTracker({start:!1,shift:(context,term)=>3==term||4==term||306==term?context:307==term,strict:!1}),insertSemicolon=new ExternalTokenizer(((input,stack)=>{let{next:next}=input;(125==next||-1==next||stack.context)&&input.acceptToken(304)}),{contextual:!0,fallback:!0}),noSemicolon=new ExternalTokenizer(((input,stack)=>{let after,{next:next}=input;space.indexOf(next)>-1||(47!=next||47!=(after=input.peek(1))&&42!=after)&&(125==next||59==next||-1==next||stack.context||input.acceptToken(303))}),{contextual:!0}),incdecToken=new ExternalTokenizer(((input,stack)=>{let{next:next}=input;if((43==next||45==next)&&(input.advance(),next==input.next)){input.advance();let mayPostfix=!stack.context&&stack.canShift(1);input.acceptToken(mayPostfix?1:2)}}),{contextual:!0}),jsHighlight=styleTags({"get set async static":tags$1.modifier,"for while do if else switch try catch finally return throw break continue default case":tags$1.controlKeyword,"in of await yield void typeof delete instanceof":tags$1.operatorKeyword,"let var const function class extends":tags$1.definitionKeyword,"import export from":tags$1.moduleKeyword,"with debugger as new":tags$1.keyword,TemplateString:tags$1.special(tags$1.string),super:tags$1.atom,BooleanLiteral:tags$1.bool,this:tags$1.self,null:tags$1.null,Star:tags$1.modifier,VariableName:tags$1.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":tags$1.function(tags$1.variableName),VariableDefinition:tags$1.definition(tags$1.variableName),Label:tags$1.labelName,PropertyName:tags$1.propertyName,PrivatePropertyName:tags$1.special(tags$1.propertyName),"CallExpression/MemberExpression/PropertyName":tags$1.function(tags$1.propertyName),"FunctionDeclaration/VariableDefinition":tags$1.function(tags$1.definition(tags$1.variableName)),"ClassDeclaration/VariableDefinition":tags$1.definition(tags$1.className),PropertyDefinition:tags$1.definition(tags$1.propertyName),PrivatePropertyDefinition:tags$1.definition(tags$1.special(tags$1.propertyName)),UpdateOp:tags$1.updateOperator,LineComment:tags$1.lineComment,BlockComment:tags$1.blockComment,Number:tags$1.number,String:tags$1.string,Escape:tags$1.escape,ArithOp:tags$1.arithmeticOperator,LogicOp:tags$1.logicOperator,BitOp:tags$1.bitwiseOperator,CompareOp:tags$1.compareOperator,RegExp:tags$1.regexp,Equals:tags$1.definitionOperator,Arrow:tags$1.function(tags$1.punctuation),": Spread":tags$1.punctuation,"( )":tags$1.paren,"[ ]":tags$1.squareBracket,"{ }":tags$1.brace,"InterpolationStart InterpolationEnd":tags$1.special(tags$1.brace),".":tags$1.derefOperator,", ;":tags$1.separator,"@":tags$1.meta,TypeName:tags$1.typeName,TypeDefinition:tags$1.definition(tags$1.typeName),"type enum interface implements namespace module declare":tags$1.definitionKeyword,"abstract global Privacy readonly override":tags$1.modifier,"is keyof unique infer":tags$1.operatorKeyword,JSXAttributeValue:tags$1.attributeValue,JSXText:tags$1.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":tags$1.angleBracket,"JSXIdentifier JSXNameSpacedName":tags$1.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":tags$1.attributeName,"JSXBuiltin/JSXIdentifier":tags$1.standard(tags$1.tagName)}),spec_identifier={__proto__:null,export:14,as:19,from:27,default:30,async:35,function:36,extends:46,this:50,true:58,false:58,null:70,void:74,typeof:78,super:96,new:130,delete:146,yield:155,await:159,class:164,public:221,private:221,protected:221,readonly:223,instanceof:242,satisfies:245,in:246,const:248,import:280,keyof:335,unique:339,infer:345,is:381,abstract:401,implements:403,type:405,let:408,var:410,using:413,interface:419,enum:423,namespace:429,module:431,declare:435,global:439,for:458,of:467,while:470,with:474,do:478,if:482,else:484,switch:488,case:494,try:500,catch:504,finally:508,return:512,throw:516,break:520,continue:524,debugger:528},spec_word={__proto__:null,async:117,get:119,set:121,declare:181,public:183,private:183,protected:183,static:185,abstract:187,override:189,readonly:195,accessor:197,new:385},spec_LessThan={__proto__:null,"<":137},parser=LRParser.deserialize({version:14,states:"$6tO`QUOOO%TQUOOO'WQWOOP(eOSOOO*sQ(CjO'#CfO*zOpO'#CgO+YO!bO'#CgO+hO07`O'#DZO-yQUO'#DaO.ZQUO'#DlO%TQUO'#DvO0_QUO'#EOOOQ(CY'#EW'#EWO0xQSO'#ETOOQO'#Ei'#EiOOQO'#Ic'#IcO1QQSO'#GkO1]QSO'#EhO1bQSO'#EhO3dQ(CjO'#JdO6TQ(CjO'#JeO6qQSO'#FWO6vQ#tO'#FoOOQ(CY'#F`'#F`O7RO&jO'#F`O7aQ,UO'#FvO8wQSO'#FuOOQ(CY'#Je'#JeOOQ(CW'#Jd'#JdO8|QSO'#GoOOQQ'#KP'#KPO9XQSO'#IPO9^Q(C[O'#IQO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Q!eQT-Q'U-R]!pQ!q'U-R0y4tQ#n]R'_9qT#iZ%]S#hZ%]S%cm,]U([#f#g#jS-v(](^Q-z(_Q0Q*|Q2d-wU2e-x-y-{S5z2f2gR7y5{`#[W#U#X%`'x(R*y-qr#eZm#f#g#j%](](^(_*|-w-x-y-{2f2g5{Q1`,]Q1v,sQ5i1nQ7q5jT:|&}*zT#_W%`S#^W%`S'y#U(RS(O#X*yS,x&}*zT-l'x-qT'S!d%aQ$jfR)n$oT)c$j)dR3_.oT*S$w*UR*[$zQ0U+UQ2i.SQ4w0{Q6P2mQ7]4zQ7|6OQ8i7[Q8{7{Q9[8kQ9d8}Q9i9]R9l9elqOXs!Y#b%e&h&j&k&m,a,f1f1iQ&b!UR,U&_rmOXs!T!U!Y#b%e&_&h&j&k&m,a,f1f1iR,]&eT%dm,]R0u+uR,T&]Q%{{R+m%|R+c%vT&f!V&iT&g!V&iT1h,f1i",nodeNames:"⚠ ArithOp ArithOp LineComment BlockComment Script ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:366,context:trackNewline,nodeProps:[["group",-26,6,14,16,62,199,203,207,208,210,213,216,226,228,234,236,238,240,243,249,255,257,259,261,263,265,266,"Statement",-32,10,11,25,28,29,35,45,48,49,51,56,64,72,76,78,80,81,103,104,113,114,131,134,136,137,138,139,141,142,162,163,165,"Expression",-23,24,26,30,34,36,38,166,168,170,171,173,174,175,177,178,179,181,182,183,193,195,197,198,"Type",-3,84,96,102,"ClassItem"],["openedBy",31,"InterpolationStart",50,"[",54,"{",69,"(",143,"JSXStartTag",155,"JSXStartTag JSXStartCloseTag"],["closedBy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#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(U~~",141,327),new LocalTokenGroup("j~RQYZXz{^~^O'r~~aP!P!Qd~iO's~~",25,309)],topRules:{Script:[0,5],SingleExpression:[1,267],SingleClassItem:[2,268]},dialects:{jsx:12810,ts:12812},dynamicPrecedences:{76:1,78:1,163:1,191:1},specialized:[{term:313,get:value=>spec_identifier[value]||-1},{term:329,get:value=>spec_word[value]||-1},{term:67,get:value=>spec_LessThan[value]||-1}],tokenPrec:12836}),snippets=[snippetCompletion("function ${name}(${params}) {\n\t${}\n}",{label:"function",detail:"definition",type:"keyword"}),snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}",{label:"for",detail:"loop",type:"keyword"}),snippetCompletion("for (let ${name} of ${collection}) {\n\t${}\n}",{label:"for",detail:"of loop",type:"keyword"}),snippetCompletion("do {\n\t${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),snippetCompletion("while (${}) {\n\t${}\n}",{label:"while",detail:"loop",type:"keyword"}),snippetCompletion("try {\n\t${}\n} catch (${error}) {\n\t${}\n}",{label:"try",detail:"/ catch block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n}",{label:"if",detail:"block",type:"keyword"}),snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}",{label:"if",detail:"/ else block",type:"keyword"}),snippetCompletion("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}",{label:"class",detail:"definition",type:"keyword"}),snippetCompletion('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),snippetCompletion('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],cache=new NodeWeakMap,ScopeNodes=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function defID(type){return(node,def)=>{let id=node.node.getChild("VariableDefinition");return id&&def(id,type),!0}}const functionContext=["FunctionDeclaration"],gatherCompletions={FunctionDeclaration:defID("function"),ClassDeclaration:defID("class"),ClassExpression:()=>!0,EnumDeclaration:defID("constant"),TypeAliasDeclaration:defID("type"),NamespaceDeclaration:defID("namespace"),VariableDefinition(node,def){node.matchContext(functionContext)||def(node,"variable")},TypeDefinition(node,def){def(node,"type")},__proto__:null};function getScope(doc,node){let cached=cache.get(node);if(cached)return cached;let completions=[],top=!0;function def(node,type){let name=doc.sliceString(node.from,node.to);completions.push({label:name,type:type})}return node.cursor(IterMode.IncludeAnonymous).iterate((node=>{if(top)top=!1;else if(node.name){let gather=gatherCompletions[node.name];if(gather&&gather(node,def)||ScopeNodes.has(node.name))return!1}else if(node.to-node.from>8192){for(let c of getScope(doc,node.node))completions.push(c);return!1}})),cache.set(node,completions),completions}const Identifier=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,dontComplete=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function localCompletionSource(context){let inner=syntaxTree(context.state).resolveInner(context.pos,-1);if(dontComplete.indexOf(inner.name)>-1)return null;let isWord="VariableName"==inner.name||inner.to-inner.from<20&&Identifier.test(context.state.sliceDoc(inner.from,inner.to));if(!isWord&&!context.explicit)return null;let options=[];for(let pos=inner;pos;pos=pos.parent)ScopeNodes.has(pos.name)&&(options=options.concat(getScope(context.state.doc,pos)));return{options:options,from:isWord?inner.from:context.pos,validFor:Identifier}}const javascriptLanguage=LRLanguage.define({name:"javascript",parser:parser.configure({props:[indentNodeProp.add({IfStatement:continuedIndent({except:/^\s*({|else\b)/}),TryStatement:continuedIndent({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:context=>context.baseIndent,SwitchBody:context=>{let after=context.textAfter,closed=/^\s*\}/.test(after),isCase=/^\s*(case|default)\b/.test(after);return context.baseIndent+(closed?0:isCase?1:2)*context.unit},Block:function(_ref8){let{closing:closing,align:align=!0,units:units=1}=_ref8;return context=>delimitedStrategy(context,align,units,closing)}({closing:"}"}),ArrowFunction:cx=>cx.baseIndent+cx.unit,"TemplateString BlockComment":()=>null,"Statement Property":continuedIndent({except:/^{/}),JSXElement(context){let closed=/^\s*<\//.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},JSXEscape(context){let closed=/\s*\}/.test(context.textAfter);return context.lineIndent(context.node.from)+(closed?0:context.unit)},"JSXOpenTag JSXSelfClosingTag":context=>context.column(context.node.from)+context.unit}),foldNodeProp.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":foldInside,BlockComment:tree=>({from:tree.from+2,to:tree.to-2})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),jsxSublanguage={test:node=>/^JSX/.test(node.name),facet:defineLanguageFacet({commentTokens:{block:{open:"{/*",close:"*/}"}}})},typescriptLanguage=javascriptLanguage.configure({dialect:"ts"},"typescript"),jsxLanguage=javascriptLanguage.configure({dialect:"jsx",props:[sublanguageProp.add((n=>n.isTop?[jsxSublanguage]:void 0))]}),tsxLanguage=javascriptLanguage.configure({dialect:"jsx ts",props:[sublanguageProp.add((n=>n.isTop?[jsxSublanguage]:void 0))]},"typescript"),keywords="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map((kw=>({label:kw,type:"keyword"})));function javascript(){let config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},lang=config.jsx?config.typescript?tsxLanguage:jsxLanguage:config.typescript?typescriptLanguage:javascriptLanguage;return new LanguageSupport(lang,[javascriptLanguage.data.of({autocomplete:ifNotIn(dontComplete,completeFromList(snippets.concat(keywords)))}),javascriptLanguage.data.of({autocomplete:localCompletionSource}),config.jsx?autoCloseTags$1:[]])}function elementName$1(doc,tree){let max=arguments.length>2&&void 0!==arguments[2]?arguments[2]:doc.length;for(let ch=null==tree?void 0:tree.firstChild;ch;ch=ch.nextSibling)if("JSXIdentifier"==ch.name||"JSXBuiltin"==ch.name||"JSXNamespacedName"==ch.name||"JSXMemberExpression"==ch.name)return doc.sliceString(ch.from,Math.min(ch.to,max));return""}const android="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),autoCloseTags$1=EditorView.inputHandler.of(((view,from,to,text)=>{if((android?view.composing:view.compositionStarted)||view.state.readOnly||from!=to||">"!=text&&"/"!=text||!javascriptLanguage.isActiveAt(view.state,from,-1))return!1;let{state:state}=view,changes=state.changeByRange((range=>{var _a;let name,{head:head}=range,around=syntaxTree(state).resolveInner(head,-1);if("JSXStartTag"==around.name&&(around=around.parent),"JSXAttributeValue"==around.name&&around.to>head);else{if(">"==text&&"JSXFragmentTag"==around.name)return{range:EditorSelection.cursor(head+1),changes:{from:head,insert:">"}};if("/"==text&&"JSXFragmentTag"==around.name){let empty=around.parent,base=null==empty?void 0:empty.parent;if(empty.from==head-1&&"JSXEndTag"!=(null===(_a=base.lastChild)||void 0===_a?void 0:_a.name)&&(name=elementName$1(state.doc,null==base?void 0:base.firstChild,head))){let insert="/".concat(name,">");return{range:EditorSelection.cursor(head+insert.length),changes:{from:head,insert:insert}}}}else if(">"==text){let openTag=function(node){for(;;){if("JSXOpenTag"==node.name||"JSXSelfClosingTag"==node.name||"JSXFragmentTag"==node.name)return node;if("JSXEscape"==node.name||!node.parent)return null;node=node.parent}}(around);if(openTag&&(!(node=openTag.lastChild)||"JSXEndTag"!=node.name&&"JSXSelfCloseEndTag"!=node.name)&&"")}}}}var node;return{range:range}}));return!changes.changes.empty&&(view.dispatch(changes,{userEvent:"input.type",scrollIntoView:!0}),!0)})),Targets=["_blank","_self","_top","_parent"],Charsets=["ascii","utf-8","utf-16","latin1","latin1"],Methods=["get","post","put","delete"],Encs=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],Bool=["true","false"],S={},Tags={a:{attrs:{href:null,ping:null,type:null,media:null,target:Targets,hreflang:null}},abbr:S,address:S,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:S,aside:S,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:S,base:{attrs:{href:null,target:Targets}},bdi:S,bdo:S,blockquote:{attrs:{cite:null}},body:S,br:S,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:S,center:S,cite:S,code:S,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:S,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:S,div:S,dl:S,dt:S,em:S,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:S,figure:S,footer:S,form:{attrs:{action:null,name:null,"accept-charset":Charsets,autocomplete:["on","off"],enctype:Encs,method:Methods,novalidate:["novalidate"],target:Targets}},h1:S,h2:S,h3:S,h4:S,h5:S,h6:S,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:S,hgroup:S,hr:S,html:{attrs:{manifest:null}},i:S,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Encs,formmethod:Methods,formnovalidate:["novalidate"],formtarget:Targets,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:S,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:S,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:S,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:Charsets,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:S,noscript:S,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:S,param:{attrs:{name:null,value:null}},pre:S,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:S,rt:S,ruby:S,samp:S,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:Charsets}},section:S,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:S,source:{attrs:{src:null,type:null,media:null}},span:S,strong:S,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:S,summary:S,sup:S,table:S,tbody:S,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:S,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:S,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:S,time:{attrs:{datetime:null}},title:S,tr:S,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:S,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:S},GlobalAttrs={accesskey:null,class:null,contenteditable:Bool,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:Bool,autocorrect:Bool,autocapitalize:Bool,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":Bool,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Bool,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Bool,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Bool,"aria-hidden":Bool,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Bool,"aria-multiselectable":Bool,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Bool,"aria-relevant":null,"aria-required":Bool,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},eventAttributes="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map((n=>"on"+n));for(let a of eventAttributes)GlobalAttrs[a]=null;class Schema{constructor(extraTags,extraAttrs){this.tags=Object.assign(Object.assign({},Tags),extraTags),this.globalAttrs=Object.assign(Object.assign({},GlobalAttrs),extraAttrs),this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}function elementName(doc,tree){let max=arguments.length>2&&void 0!==arguments[2]?arguments[2]:doc.length;if(!tree)return"";let tag=tree.firstChild,name=tag&&tag.getChild("TagName");return name?doc.sliceString(name.from,Math.min(name.to,max)):""}function findParentElement(tree){let skip=arguments.length>1&&void 0!==arguments[1]&&arguments[1];for(;tree;tree=tree.parent)if("Element"==tree.name){if(!skip)return tree;skip=!1}return null}function allowedChildren(doc,tree,schema){let parentInfo=schema.tags[elementName(doc,findParentElement(tree))];return(null==parentInfo?void 0:parentInfo.children)||schema.allTags}function openTags(doc,tree){let open=[];for(let parent=findParentElement(tree);parent&&!parent.type.isTop;parent=findParentElement(parent.parent)){let tagName=elementName(doc,parent);if(tagName&&"CloseTag"==parent.lastChild.name)break;tagName&&open.indexOf(tagName)<0&&("EndTag"==tree.name||tree.from>=parent.firstChild.to)&&open.push(tagName)}return open}Schema.default=new Schema;const identifier=/^[:\-\.\w\u00b7-\uffff]*$/;function completeTag(state,schema,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">",parent=findParentElement(tree,!0);return{from:from,to:to,options:allowedChildren(state.doc,parent,schema).map((tagName=>({label:tagName,type:"type"}))).concat(openTags(state.doc,tree).map(((tag,i)=>({label:"/"+tag,apply:"/"+tag+end,type:"type",boost:99-i})))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function completeCloseTag(state,tree,from,to){let end=/\s*>/.test(state.sliceDoc(to,to+5))?"":">";return{from:from,to:to,options:openTags(state.doc,tree).map(((tag,i)=>({label:tag,apply:tag+end,type:"type",boost:99-i}))),validFor:identifier}}function htmlCompletionFor(schema,context){let{state:state,pos:pos}=context,tree=syntaxTree(state).resolveInner(pos,-1),around=tree.resolve(pos);for(let before,scan=pos;around==tree&&(before=tree.childBefore(scan));){let last=before.lastChild;if(!last||!last.type.isError||last.from({label:attrName,type:"property"}))),validFor:identifier}}(state,schema,tree,"AttributeName"==tree.name?tree.from:pos,pos):"Is"==tree.name||"AttributeValue"==tree.name||"UnquotedAttributeValue"==tree.name?function(state,schema,tree,from,to){var _a;let token,nameNode=null===(_a=tree.parent)||void 0===_a?void 0:_a.getChild("AttributeName"),options=[];if(nameNode){let attrName=state.sliceDoc(nameNode.from,nameNode.to),attrs=schema.globalAttrs[attrName];if(!attrs){let elt=findParentElement(tree),info=elt?schema.tags[elementName(state.doc,elt)]:null;attrs=(null==info?void 0:info.attrs)&&info.attrs[attrName]}if(attrs){let base=state.sliceDoc(from,to).toLowerCase(),quoteStart='"',quoteEnd='"';/^['"]/.test(base)?(token='"'==base[0]?/^[^"]*$/:/^[^']*$/,quoteStart="",quoteEnd=state.sliceDoc(to,to+1)==base[0]?"":base[0],base=base.slice(1),from++):token=/^[^\s<>='"]*$/;for(let value of attrs)options.push({label:value,apply:quoteStart+value+quoteEnd,type:"constant"})}}return{from:from,to:to,options:options,validFor:token}}(state,schema,tree,"Is"==tree.name?pos:tree.from,pos):!context.explicit||"Element"!=around.name&&"Text"!=around.name&&"Document"!=around.name?null:function(state,schema,tree,pos){let options=[],level=0;for(let tagName of allowedChildren(state.doc,tree,schema))options.push({label:"<"+tagName,type:"type"});for(let open of openTags(state.doc,tree))options.push({label:"",type:"type",boost:99-level++});return{from:pos,to:pos,options:options,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}(state,schema,tree,pos)}function htmlCompletionSourceWith(config){let{extraTags:extraTags,extraGlobalAttributes:extraAttrs}=config,schema=extraAttrs||extraTags?new Schema(extraTags,extraAttrs):Schema.default;return context=>htmlCompletionFor(schema,context)}const jsonParser=javascriptLanguage.parser.configure({top:"SingleExpression"}),defaultNesting=[{tag:"script",attrs:attrs=>"text/typescript"==attrs.type||"ts"==attrs.lang,parser:typescriptLanguage.parser},{tag:"script",attrs:attrs=>"text/babel"==attrs.type||"text/jsx"==attrs.type,parser:jsxLanguage.parser},{tag:"script",attrs:attrs=>"text/typescript-jsx"==attrs.type,parser:tsxLanguage.parser},{tag:"script",attrs:attrs=>/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(attrs.type),parser:jsonParser},{tag:"script",attrs:attrs=>!attrs.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(attrs.type),parser:javascriptLanguage.parser},{tag:"style",attrs:attrs=>(!attrs.lang||"css"==attrs.lang)&&(!attrs.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(attrs.type)),parser:cssLanguage.parser}],defaultAttrs=[{name:"style",parser:cssLanguage.parser.configure({top:"Styles"})}].concat(eventAttributes.map((name=>({name:name,parser:javascriptLanguage.parser})))),htmlPlain=LRLanguage.define({name:"html",parser:parser$2.configure({props:[indentNodeProp.add({Element(context){let after=/^(\s*)(<\/)?/.exec(context.textAfter);return context.node.to<=context.pos+after[0].length?context.continue():context.lineIndent(context.node.from)+(after[2]?0:context.unit)},"OpenTag CloseTag SelfClosingTag":context=>context.column(context.node.from)+context.unit,Document(context){if(context.pos+/\s*/.exec(context.textAfter)[0].lengthnode.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"\x3c!--",close:"--\x3e"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-._"}}),htmlLanguage=htmlPlain.configure({wrap:configureNesting(defaultNesting,defaultAttrs)});const selfClosers=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),autoCloseTags=EditorView.inputHandler.of(((view,from,to,text,insertTransaction)=>{if(view.composing||view.state.readOnly||from!=to||">"!=text&&"/"!=text||!htmlLanguage.isActiveAt(view.state,from,-1))return!1;let base=insertTransaction(),{state:state}=base,closeTags=state.changeByRange((range=>{var _a,_b,_c;let name,didType=state.doc.sliceString(range.from-1,range.to)==text,{head:head}=range,after=syntaxTree(state).resolveInner(head,-1);if(didType&&">"==text&&"EndTag"==after.name){let tag=after.parent;if("CloseTag"!=(null===(_b=null===(_a=tag.parent)||void 0===_a?void 0:_a.lastChild)||void 0===_b?void 0:_b.name)&&(name=elementName(state.doc,tag.parent,head))&&!selfClosers.has(name)){return{range:range,changes:{from:head,to:head+(">"===state.doc.sliceString(head,head+1)?1:0),insert:"")}}}}else if(didType&&"/"==text&&"IncompleteCloseTag"==after.name){let tag=after.parent;if(after.from==head-2&&"CloseTag"!=(null===(_c=tag.lastChild)||void 0===_c?void 0:_c.name)&&(name=elementName(state.doc,tag,head))&&!selfClosers.has(name)){let to=head+(">"===state.doc.sliceString(head,head+1)?1:0),insert="".concat(name,">");return{range:EditorSelection.cursor(head+insert.length,-1),changes:{from:head,to:to,insert:insert}}}}return{range:range}}));return!closeTags.changes.empty&&(view.dispatch([base,state.update(closeTags,{userEvent:"input.complete",scrollIntoView:!0})]),!0)})),cm6proDark=[EditorView.theme({"&":{color:"#cccccc",backgroundColor:"#1f1f1f"},".cm-content":{caretColor:"#4d4d4d"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"#4d4d4d"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:"#3d3d3d"},".cm-panels":{backgroundColor:"#1f1f1f",color:"#4d4d4d"},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#2e2e2e"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:"1px solid ".concat("#eee8d5")},".cm-gutters":{backgroundColor:"#1f1f1f",color:"#808080",border:"none"},".cm-activeLineGutter":{backgroundColor:"#2e2e2e"},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:"#1a1a1a"},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:"#1a1a1a",borderBottomColor:"#1a1a1a"},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:"#2e2e2e",color:"#4d4d4d"}}},{dark:!0}),syntaxHighlighting(HighlightStyle.define([{tag:tags$1.keyword,color:"#a7bf06"},{tag:[tags$1.name,tags$1.deleted,tags$1.character,tags$1.propertyName,tags$1.macroName],color:"#569cd6"},{tag:[tags$1.variableName],color:"#cccccc"},{tag:[tags$1.function(tags$1.variableName)],color:"#268bd2"},{tag:[tags$1.labelName],color:"#d33682"},{tag:[tags$1.color,tags$1.constant(tags$1.name),tags$1.standard(tags$1.name)],color:"#d1a008"},{tag:[tags$1.definition(tags$1.name),tags$1.separator],color:"#569cd6"},{tag:[tags$1.brace],color:"#d33682"},{tag:[tags$1.annotation],color:"#d30102"},{tag:[tags$1.number,tags$1.changed,tags$1.annotation,tags$1.modifier,tags$1.self,tags$1.namespace],color:"#d33682"},{tag:[tags$1.typeName,tags$1.className],color:"#cb4b16"},{tag:[tags$1.operator,tags$1.operatorKeyword],color:"#7e83e6"},{tag:[tags$1.tagName],color:"#268bd2"},{tag:[tags$1.squareBracket],color:"#dc322f"},{tag:[tags$1.angleBracket],color:"#808080"},{tag:[tags$1.attributeName],color:"#569cd6"},{tag:[tags$1.regexp],color:"#d30102"},{tag:[tags$1.quote],color:"#a7bf06"},{tag:[tags$1.string],color:"#d1a008"},{tag:tags$1.link,color:"#569cd6",textDecoration:"underline",textUnderlinePosition:"under"},{tag:[tags$1.url,tags$1.escape,tags$1.special(tags$1.string)],color:"#d1a008"},{tag:[tags$1.meta],color:"#dc322f"},{tag:[tags$1.comment],color:"#638e50",fontStyle:"italic"},{tag:tags$1.strong,fontWeight:"bold",color:"#eee8d5"},{tag:tags$1.emphasis,fontStyle:"italic",color:"#a7bf06"},{tag:tags$1.strikethrough,textDecoration:"line-through"},{tag:tags$1.heading,fontWeight:"bold",color:"#d1a008"},{tag:tags$1.heading1,fontWeight:"bold",color:"#fdf6e3"},{tag:[tags$1.heading2,tags$1.heading3,tags$1.heading4],fontWeight:"bold",color:"#eee8d5"},{tag:[tags$1.heading5,tags$1.heading6],color:"#eee8d5"},{tag:[tags$1.atom,tags$1.bool,tags$1.special(tags$1.variableName)],color:"#d33682"},{tag:[tags$1.processingInstruction,tags$1.inserted,tags$1.contentSeparator],color:"#dc322f"},{tag:[tags$1.contentSeparator],color:"#d1a008"},{tag:tags$1.invalid,color:"#dc322f",borderBottom:"1px dotted ".concat("#dc322f")}]))],CONFIG={strict:!1,tab_size:2},hasHtml=content=>/<(?[A-Za-z]+\b)[^>]*(?:.|\n)*?<\/{1}\k>/.test(content),mergeObjects=(current,updates)=>{if(!current||!updates)throw new Error("Both 'current' and 'updates' must be passed-in to merge()");if("object"!=typeof current||"object"!=typeof updates||Array.isArray(current)||Array.isArray(updates))throw new Error("Both 'current' and 'updates' must be passed-in as objects to merge()");let merged={...current};for(let key of Object.keys(updates))"object"!=typeof updates[key]?merged[key]=updates[key]:merged[key]=mergeObjects(merged[key]||{},updates[key]);return merged},validateConfig=config=>{if("object"!=typeof config)throw"Config must be an object.";if(!(Object.hasOwn(config,"tab_size")||Object.hasOwn(config,"strict")))return CONFIG;let tab_size=config.tab_size;if(tab_size){if("number"!=typeof tab_size)throw"Tab size must be a number.";if(!Number.isSafeInteger(tab_size))throw"Tab size ".concat(tab_size," is not safe. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger for more info.");if(tab_size=Math.floor(tab_size),tab_size<1||tab_size>16)throw"Tab size out of range. Expecting 1 to 16.";config.tab_size=tab_size}if(Object.hasOwn(config,"strict")&&"boolean"!=typeof config.strict)throw"Strict config must be a boolean.";return((dconfig,config)=>mergeObjects(structuredClone(dconfig),config))(CONFIG,config)},void_elements=["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"],entify=function(html){let minify=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return html=(html=(html=html.replace(/(]*>)\n+/g,"$1").replace(/(]*>)\n\s+/g,"$1").replace(/(]*>)\s+\n/g,"$1")).replace(/\s+<\/textarea>/g,"")).replace(/]*>((.|\n)*?)<\/textarea>/g,((match,capture)=>match.replace(capture,(match=>match.replace(//g,">").replace(/\//g,"/").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/%/g,"%").replace(/\{/g,"{").replace(/\}/g,"}"))))),minify&&(html=html.replace(/]*>((.|\n)*?)<\/textarea>/g,((match,capture)=>match=(match=match.replace(capture,(match=>match.replace(/\n|\t/g,"").replace(/[a-z]+="\s*"/gi,"").replace(/>\s+<").replace(/\s+/g," ")))).replace(/\s+/g," ").replace(/\s>/g,">").replace(/>\s/g,">").replace(/\smatch.replace(/\s/g,""))).replace(/(class=.*)\s(["'])/g,"$1$2")))),html};let strict;const convert={line:[]},preprocess=html=>(html=function(html){return arguments.length>1&&void 0!==arguments[1]&&!arguments[1]||hasHtml(html)?html.replace(/<([a-zA-Z\-0-9]+)[^>]*>/g,((match,name)=>void_elements.indexOf(name)>-1?"".concat(match.substring(0,match.length-1)," />").replace(/\/\s\//g,"/"):match.replace(/[\s]?\/>/g,">")))):html}(html,!1),html=function(html){return arguments.length>1&&void 0!==arguments[1]&&!arguments[1]||hasHtml(html)?(html=entify(html)).replace(/\n|\t/g,"").replace(/[a-z]+="\s*"/gi,"").replace(/>\s+<").replace(/\s+/g," ").replace(/\s>/g,">").replace(/<\s\//g,"\s/g,">").replace(/\smatch.replace(/\s/g,""))).replace(/(class=.*)\s(["'])/g,"$1$2"):html}(html,!1),html=(html=>{convert.line=[];let i=-1;return html.replace(/<[^>]*>/g,(match=>(convert.line.push(match),i++,"\n[#-# : ".concat(i," : ").concat(match," : #-#]\n"))))})(html),html),prettify=(html,config)=>{const validated_config=config?validateConfig(config):CONFIG;return strict=validated_config.strict,hasHtml(html)?html=((html,step)=>{let indents="";convert.line.forEach(((source,index)=>{html=html.replace(/\n+/g,"\n").replace("[#-# : ".concat(index," : ").concat(source," : #-#]"),(match=>{let subtrahend=0;const prevLine="[#-# : ".concat(index-1," : ").concat(convert.line[index-1]," : #-#]");indents+="0",0===index&&subtrahend++,match.indexOf("#-# : ".concat(index," : -1&&subtrahend++,prevLine.indexOf("-1&&subtrahend++,prevLine.indexOf("\x3c!--")>-1&&subtrahend++,prevLine.indexOf("/> : #-#")>-1&&subtrahend++,prevLine.indexOf("#-# : ".concat(index-1," : -1&&subtrahend++;const offset=indents.length-subtrahend;if(indents=indents.substring(0,offset),strict&&match.indexOf("\x3c!--")>-1)return"";const result=match.replace("[#-# : ".concat(index," : "),"").replace(" : #-#]","");return result.padStart(result.length+step*offset)}))})),html=html.replace(/>[^<]*?[^><\/\s][^<]*?<\/|>\s+[^><\s]|]*>\s+<\/script>|<(\w+)>\s+<\/(\w+)|<([\w\-]+)[^>]*[^\/]>\s+<\/([\w\-]+)>/g,(match=>match.replace(/\n|\t|\s{2,}/g,""))),strict&&(html=html.replace(/\s\/>/g,">"));const lead_newline_check=html.substring(0,1),tail_newline_check=html.substring(html.length-1);return"\n"===lead_newline_check&&(html=html.substring(1,html.length)),"\n"===tail_newline_check&&(html=html.substring(0,html.length-1)),html})(html=preprocess(html),validated_config.tab_size):html},themes={light:EditorView.baseTheme(),dark:cm6proDark};return _exports.default=class{static getThemes(){return["light","dark"]}constructor(textarea){_defineProperty(this,"_parentElement",void 0),_defineProperty(this,"_source",void 0),_defineProperty(this,"_editorView",void 0),this._parentElement=textarea.parentElement,this.themeConfig=new Compartment,this.linewrapConfig=new Compartment;let updateListenerExtension=EditorView.updateListener.of((update=>{textarea.value=update.state.doc.toString()})),extensions=[basicSetup,this.linewrapConfig.of([EditorView.lineWrapping]),this.themeConfig.of([themes.light]),updateListenerExtension],name=textarea.name.split("[",1)[0],formatElement=textarea.form.querySelector('[name="'+name+'[format]"]');if(formatElement)switch(parseInt(formatElement.value)){case 90:extensions.push(css());break;case 91:extensions.push(javascript());break;default:extensions.push(function(){let wrap,config=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},dialect="";!1===config.matchClosingTags&&(dialect="noMatch"),!0===config.selfClosingTags&&(dialect=(dialect?dialect+" ":"")+"selfClosing"),(config.nestedLanguages&&config.nestedLanguages.length||config.nestedAttributes&&config.nestedAttributes.length)&&(wrap=configureNesting((config.nestedLanguages||[]).concat(defaultNesting),(config.nestedAttributes||[]).concat(defaultAttrs)));let lang=wrap?htmlPlain.configure({wrap:wrap,dialect:dialect}):dialect?htmlLanguage.configure({dialect:dialect}):htmlLanguage;return new LanguageSupport(lang,[htmlLanguage.data.of({autocomplete:htmlCompletionSourceWith(config)}),!1!==config.autoCloseTags?autoCloseTags:[],javascript().support,css().support])}())}this._editorView=new EditorView({extensions:extensions,parent:this._parentElement,doc:textarea.value}),textarea.parentNode.insertBefore(this._editorView.dom,textarea),textarea.style.display="none",textarea.parentNode.nextElementSibling.style.display="none"}setValue(source){this._source=source;const view=this._editorView;view.dispatch({changes:{from:0,to:view.state.doc.length,insert:source||""}})}getValue(){return this._editorView.state.doc.toString()}setTheme(themeName){themes[themeName]?this._editorView.dispatch({effects:this.themeConfig.reconfigure([themes[themeName]])}):console.error("Unknown theme",themeName)}setLineWrapping(bool){this._editorView.dispatch({effects:this.linewrapConfig.reconfigure(bool?[EditorView.lineWrapping]:[])})}prettify(){const source=this.getValue(),beautified=prettify(source);this.setValue(beautified)}focus(){this._editorView.hasFocus||this._editorView.focus()}},_exports.default})); //# sourceMappingURL=cm6pro-lazy.min.js.map \ No newline at end of file diff --git a/amd/build/cm6pro-lazy.min.js.map b/amd/build/cm6pro-lazy.min.js.map index a6a563e..8f35497 100644 --- a/amd/build/cm6pro-lazy.min.js.map +++ b/amd/build/cm6pro-lazy.min.js.map @@ -1 +1 @@ -{"version":3,"file":"cm6pro-lazy.min.js","sources":["../src/cm6pro-lazy.js"],"sourcesContent":["/* eslint-disable */\n/**\nThe data structure for documents. @nonabstract\n*/\nclass Text {\n /**\n Get the line description around the given position.\n */\n lineAt(pos) {\n if (pos < 0 || pos > this.length)\n throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);\n return this.lineInner(pos, false, 1, 0);\n }\n /**\n Get the description for the given (1-based) line number.\n */\n line(n) {\n if (n < 1 || n > this.lines)\n throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);\n return this.lineInner(n, true, 1, 0);\n }\n /**\n Replace a range of the text with the given content.\n */\n replace(from, to, text) {\n [from, to] = clip(this, from, to);\n let parts = [];\n this.decompose(0, from, parts, 2 /* Open.To */);\n if (text.length)\n text.decompose(0, text.length, parts, 1 /* Open.From */ | 2 /* Open.To */);\n this.decompose(to, this.length, parts, 1 /* Open.From */);\n return TextNode.from(parts, this.length - (to - from) + text.length);\n }\n /**\n Append another document to this one.\n */\n append(other) {\n return this.replace(this.length, this.length, other);\n }\n /**\n Retrieve the text between the given points.\n */\n slice(from, to = this.length) {\n [from, to] = clip(this, from, to);\n let parts = [];\n this.decompose(from, to, parts, 0);\n return TextNode.from(parts, to - from);\n }\n /**\n Test whether this text is equal to another instance.\n */\n eq(other) {\n if (other == this)\n return true;\n if (other.length != this.length || other.lines != this.lines)\n return false;\n let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1);\n let a = new RawTextCursor(this), b = new RawTextCursor(other);\n for (let skip = start, pos = start;;) {\n a.next(skip);\n b.next(skip);\n skip = 0;\n if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value)\n return false;\n pos += a.value.length;\n if (a.done || pos >= end)\n return true;\n }\n }\n /**\n Iterate over the text. When `dir` is `-1`, iteration happens\n from end to start. This will return lines and the breaks between\n them as separate strings.\n */\n iter(dir = 1) { return new RawTextCursor(this, dir); }\n /**\n Iterate over a range of the text. When `from` > `to`, the\n iterator will run in reverse.\n */\n iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to); }\n /**\n Return a cursor that iterates over the given range of lines,\n _without_ returning the line breaks between, and yielding empty\n strings for empty lines.\n \n When `from` and `to` are given, they should be 1-based line numbers.\n */\n iterLines(from, to) {\n let inner;\n if (from == null) {\n inner = this.iter();\n }\n else {\n if (to == null)\n to = this.lines + 1;\n let start = this.line(from).from;\n inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));\n }\n return new LineCursor(inner);\n }\n /**\n Return the document as a string, using newline characters to\n separate lines.\n */\n toString() { return this.sliceString(0); }\n /**\n Convert the document to an array of lines (which can be\n deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).\n */\n toJSON() {\n let lines = [];\n this.flatten(lines);\n return lines;\n }\n /**\n @internal\n */\n constructor() { }\n /**\n Create a `Text` instance for the given array of lines.\n */\n static of(text) {\n if (text.length == 0)\n throw new RangeError(\"A document must have at least one line\");\n if (text.length == 1 && !text[0])\n return Text.empty;\n return text.length <= 32 /* Tree.Branch */ ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));\n }\n}\n// Leaves store an array of line strings. There are always line breaks\n// between these strings. Leaves are limited in size and have to be\n// contained in TextNode instances for bigger documents.\nclass TextLeaf extends Text {\n constructor(text, length = textLength(text)) {\n super();\n this.text = text;\n this.length = length;\n }\n get lines() { return this.text.length; }\n get children() { return null; }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let string = this.text[i], end = offset + string.length;\n if ((isLine ? line : end) >= target)\n return new Line(offset, end, line, string);\n offset = end + 1;\n line++;\n }\n }\n decompose(from, to, target, open) {\n let text = from <= 0 && to >= this.length ? this\n : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));\n if (open & 1 /* Open.From */) {\n let prev = target.pop();\n let joined = appendText(text.text, prev.text.slice(), 0, text.length);\n if (joined.length <= 32 /* Tree.Branch */) {\n target.push(new TextLeaf(joined, prev.length + text.length));\n }\n else {\n let mid = joined.length >> 1;\n target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));\n }\n }\n else {\n target.push(text);\n }\n }\n replace(from, to, text) {\n if (!(text instanceof TextLeaf))\n return super.replace(from, to, text);\n [from, to] = clip(this, from, to);\n let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);\n let newLen = this.length + text.length - (to - from);\n if (lines.length <= 32 /* Tree.Branch */)\n return new TextLeaf(lines, newLen);\n return TextNode.from(TextLeaf.split(lines, []), newLen);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n [from, to] = clip(this, from, to);\n let result = \"\";\n for (let pos = 0, i = 0; pos <= to && i < this.text.length; i++) {\n let line = this.text[i], end = pos + line.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += line.slice(Math.max(0, from - pos), to - pos);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let line of this.text)\n target.push(line);\n }\n scanIdentical() { return 0; }\n static split(text, target) {\n let part = [], len = -1;\n for (let line of text) {\n part.push(line);\n len += line.length + 1;\n if (part.length == 32 /* Tree.Branch */) {\n target.push(new TextLeaf(part, len));\n part = [];\n len = -1;\n }\n }\n if (len > -1)\n target.push(new TextLeaf(part, len));\n return target;\n }\n}\n// Nodes provide the tree structure of the `Text` type. They store a\n// number of other nodes or leaves, taking care to balance themselves\n// on changes. There are implied line breaks _between_ the children of\n// a node (but not before the first or after the last child).\nclass TextNode extends Text {\n constructor(children, length) {\n super();\n this.children = children;\n this.length = length;\n this.lines = 0;\n for (let child of children)\n this.lines += child.lines;\n }\n lineInner(target, isLine, line, offset) {\n for (let i = 0;; i++) {\n let child = this.children[i], end = offset + child.length, endLine = line + child.lines - 1;\n if ((isLine ? endLine : end) >= target)\n return child.lineInner(target, isLine, line, offset);\n offset = end + 1;\n line = endLine + 1;\n }\n }\n decompose(from, to, target, open) {\n for (let i = 0, pos = 0; pos <= to && i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n if (from <= end && to >= pos) {\n let childOpen = open & ((pos <= from ? 1 /* Open.From */ : 0) | (end >= to ? 2 /* Open.To */ : 0));\n if (pos >= from && end <= to && !childOpen)\n target.push(child);\n else\n child.decompose(from - pos, to - pos, target, childOpen);\n }\n pos = end + 1;\n }\n }\n replace(from, to, text) {\n [from, to] = clip(this, from, to);\n if (text.lines < this.lines)\n for (let i = 0, pos = 0; i < this.children.length; i++) {\n let child = this.children[i], end = pos + child.length;\n // Fast path: if the change only affects one child and the\n // child's size remains in the acceptable range, only update\n // that child\n if (from >= pos && to <= end) {\n let updated = child.replace(from - pos, to - pos, text);\n let totalLines = this.lines - child.lines + updated.lines;\n if (updated.lines < (totalLines >> (5 /* Tree.BranchShift */ - 1)) &&\n updated.lines > (totalLines >> (5 /* Tree.BranchShift */ + 1))) {\n let copy = this.children.slice();\n copy[i] = updated;\n return new TextNode(copy, this.length - (to - from) + text.length);\n }\n return super.replace(pos, end, updated);\n }\n pos = end + 1;\n }\n return super.replace(from, to, text);\n }\n sliceString(from, to = this.length, lineSep = \"\\n\") {\n [from, to] = clip(this, from, to);\n let result = \"\";\n for (let i = 0, pos = 0; i < this.children.length && pos <= to; i++) {\n let child = this.children[i], end = pos + child.length;\n if (pos > from && i)\n result += lineSep;\n if (from < end && to > pos)\n result += child.sliceString(from - pos, to - pos, lineSep);\n pos = end + 1;\n }\n return result;\n }\n flatten(target) {\n for (let child of this.children)\n child.flatten(target);\n }\n scanIdentical(other, dir) {\n if (!(other instanceof TextNode))\n return 0;\n let length = 0;\n let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length]\n : [this.children.length - 1, other.children.length - 1, -1, -1];\n for (;; iA += dir, iB += dir) {\n if (iA == eA || iB == eB)\n return length;\n let chA = this.children[iA], chB = other.children[iB];\n if (chA != chB)\n return length + chA.scanIdentical(chB, dir);\n length += chA.length + 1;\n }\n }\n static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {\n let lines = 0;\n for (let ch of children)\n lines += ch.lines;\n if (lines < 32 /* Tree.Branch */) {\n let flat = [];\n for (let ch of children)\n ch.flatten(flat);\n return new TextLeaf(flat, length);\n }\n let chunk = Math.max(32 /* Tree.Branch */, lines >> 5 /* Tree.BranchShift */), maxChunk = chunk << 1, minChunk = chunk >> 1;\n let chunked = [], currentLines = 0, currentLen = -1, currentChunk = [];\n function add(child) {\n let last;\n if (child.lines > maxChunk && child instanceof TextNode) {\n for (let node of child.children)\n add(node);\n }\n else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {\n flush();\n chunked.push(child);\n }\n else if (child instanceof TextLeaf && currentLines &&\n (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf &&\n child.lines + last.lines <= 32 /* Tree.Branch */) {\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);\n }\n else {\n if (currentLines + child.lines > chunk)\n flush();\n currentLines += child.lines;\n currentLen += child.length + 1;\n currentChunk.push(child);\n }\n }\n function flush() {\n if (currentLines == 0)\n return;\n chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));\n currentLen = -1;\n currentLines = currentChunk.length = 0;\n }\n for (let child of children)\n add(child);\n flush();\n return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);\n }\n}\nText.empty = /*@__PURE__*/new TextLeaf([\"\"], 0);\nfunction textLength(text) {\n let length = -1;\n for (let line of text)\n length += line.length + 1;\n return length;\n}\nfunction appendText(text, target, from = 0, to = 1e9) {\n for (let pos = 0, i = 0, first = true; i < text.length && pos <= to; i++) {\n let line = text[i], end = pos + line.length;\n if (end >= from) {\n if (end > to)\n line = line.slice(0, to - pos);\n if (pos < from)\n line = line.slice(from - pos);\n if (first) {\n target[target.length - 1] += line;\n first = false;\n }\n else\n target.push(line);\n }\n pos = end + 1;\n }\n return target;\n}\nfunction sliceText(text, from, to) {\n return appendText(text, [\"\"], from, to);\n}\nclass RawTextCursor {\n constructor(text, dir = 1) {\n this.dir = dir;\n this.done = false;\n this.lineBreak = false;\n this.value = \"\";\n this.nodes = [text];\n this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];\n }\n nextInner(skip, dir) {\n this.done = this.lineBreak = false;\n for (;;) {\n let last = this.nodes.length - 1;\n let top = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1;\n let size = top instanceof TextLeaf ? top.text.length : top.children.length;\n if (offset == (dir > 0 ? size : 0)) {\n if (last == 0) {\n this.done = true;\n this.value = \"\";\n return this;\n }\n if (dir > 0)\n this.offsets[last - 1]++;\n this.nodes.pop();\n this.offsets.pop();\n }\n else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {\n this.offsets[last] += dir;\n if (skip == 0) {\n this.lineBreak = true;\n this.value = \"\\n\";\n return this;\n }\n skip--;\n }\n else if (top instanceof TextLeaf) {\n // Move to the next string\n let next = top.text[offset + (dir < 0 ? -1 : 0)];\n this.offsets[last] += dir;\n if (next.length > Math.max(0, skip)) {\n this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);\n return this;\n }\n skip -= next.length;\n }\n else {\n let next = top.children[offset + (dir < 0 ? -1 : 0)];\n if (skip > next.length) {\n skip -= next.length;\n this.offsets[last] += dir;\n }\n else {\n if (dir < 0)\n this.offsets[last]--;\n this.nodes.push(next);\n this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);\n }\n }\n }\n }\n next(skip = 0) {\n if (skip < 0) {\n this.nextInner(-skip, (-this.dir));\n skip = this.value.length;\n }\n return this.nextInner(skip, this.dir);\n }\n}\nclass PartialTextCursor {\n constructor(text, start, end) {\n this.value = \"\";\n this.done = false;\n this.cursor = new RawTextCursor(text, start > end ? -1 : 1);\n this.pos = start > end ? text.length : 0;\n this.from = Math.min(start, end);\n this.to = Math.max(start, end);\n }\n nextInner(skip, dir) {\n if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {\n this.value = \"\";\n this.done = true;\n return this;\n }\n skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);\n let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;\n if (skip > limit)\n skip = limit;\n limit -= skip;\n let { value } = this.cursor.next(skip);\n this.pos += (value.length + skip) * dir;\n this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);\n this.done = !this.value;\n return this;\n }\n next(skip = 0) {\n if (skip < 0)\n skip = Math.max(skip, this.from - this.pos);\n else if (skip > 0)\n skip = Math.min(skip, this.to - this.pos);\n return this.nextInner(skip, this.cursor.dir);\n }\n get lineBreak() { return this.cursor.lineBreak && this.value != \"\"; }\n}\nclass LineCursor {\n constructor(inner) {\n this.inner = inner;\n this.afterBreak = true;\n this.value = \"\";\n this.done = false;\n }\n next(skip = 0) {\n let { done, lineBreak, value } = this.inner.next(skip);\n if (done && this.afterBreak) {\n this.value = \"\";\n this.afterBreak = false;\n }\n else if (done) {\n this.done = true;\n this.value = \"\";\n }\n else if (lineBreak) {\n if (this.afterBreak) {\n this.value = \"\";\n }\n else {\n this.afterBreak = true;\n this.next();\n }\n }\n else {\n this.value = value;\n this.afterBreak = false;\n }\n return this;\n }\n get lineBreak() { return false; }\n}\nif (typeof Symbol != \"undefined\") {\n Text.prototype[Symbol.iterator] = function () { return this.iter(); };\n RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] =\n LineCursor.prototype[Symbol.iterator] = function () { return this; };\n}\n/**\nThis type describes a line in the document. It is created\non-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).\n*/\nclass Line {\n /**\n @internal\n */\n constructor(\n /**\n The position of the start of the line.\n */\n from, \n /**\n The position at the end of the line (_before_ the line break,\n or at the end of document for the last line).\n */\n to, \n /**\n This line's line number (1-based).\n */\n number, \n /**\n The line's content.\n */\n text) {\n this.from = from;\n this.to = to;\n this.number = number;\n this.text = text;\n }\n /**\n The length of the line (not including any line break after it).\n */\n get length() { return this.to - this.from; }\n}\nfunction clip(text, from, to) {\n from = Math.max(0, Math.min(text.length, from));\n return [from, Math.max(from, Math.min(text.length, to))];\n}\n\n// Compressed representation of the Grapheme_Cluster_Break=Extend\n// information from\n// http://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakProperty.txt.\n// Each pair of elements represents a range, as an offet from the\n// previous range and a length. Numbers are in base-36, with the empty\n// string being a shorthand for 1.\nlet 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);\n// Convert offsets into absolute values\nfor (let i = 1; i < extend.length; i++)\n extend[i] += extend[i - 1];\nfunction isExtendingChar(code) {\n for (let i = 1; i < extend.length; i += 2)\n if (extend[i] > code)\n return extend[i - 1] <= code;\n return false;\n}\nfunction isRegionalIndicator(code) {\n return code >= 0x1F1E6 && code <= 0x1F1FF;\n}\nconst ZWJ = 0x200d;\n/**\nReturns a next grapheme cluster break _after_ (not equal to)\n`pos`, if `forward` is true, or before otherwise. Returns `pos`\nitself if no further cluster break is available in the string.\nMoves across surrogate pairs, extending characters (when\n`includeExtending` is true), characters joined with zero-width\njoiners, and flag emoji.\n*/\nfunction findClusterBreak(str, pos, forward = true, includeExtending = true) {\n return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);\n}\nfunction nextClusterBreak(str, pos, includeExtending) {\n if (pos == str.length)\n return pos;\n // If pos is in the middle of a surrogate pair, move to its start\n if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))\n pos--;\n let prev = codePointAt(str, pos);\n pos += codePointSize(prev);\n while (pos < str.length) {\n let next = codePointAt(str, pos);\n if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {\n pos += codePointSize(next);\n prev = next;\n }\n else if (isRegionalIndicator(next)) {\n let countBefore = 0, i = pos - 2;\n while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {\n countBefore++;\n i -= 2;\n }\n if (countBefore % 2 == 0)\n break;\n else\n pos += 2;\n }\n else {\n break;\n }\n }\n return pos;\n}\nfunction prevClusterBreak(str, pos, includeExtending) {\n while (pos > 0) {\n let found = nextClusterBreak(str, pos - 2, includeExtending);\n if (found < pos)\n return found;\n pos--;\n }\n return 0;\n}\nfunction surrogateLow(ch) { return ch >= 0xDC00 && ch < 0xE000; }\nfunction surrogateHigh(ch) { return ch >= 0xD800 && ch < 0xDC00; }\n/**\nFind the code point at the given position in a string (like the\n[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)\nstring method).\n*/\nfunction codePointAt(str, pos) {\n let code0 = str.charCodeAt(pos);\n if (!surrogateHigh(code0) || pos + 1 == str.length)\n return code0;\n let code1 = str.charCodeAt(pos + 1);\n if (!surrogateLow(code1))\n return code0;\n return ((code0 - 0xd800) << 10) + (code1 - 0xdc00) + 0x10000;\n}\n/**\nGiven a Unicode codepoint, return the JavaScript string that\nrespresents it (like\n[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).\n*/\nfunction fromCodePoint(code) {\n if (code <= 0xffff)\n return String.fromCharCode(code);\n code -= 0x10000;\n return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);\n}\n/**\nThe amount of positions a character takes up a JavaScript string.\n*/\nfunction codePointSize(code) { return code < 0x10000 ? 1 : 2; }\n\nconst DefaultSplit = /\\r\\n?|\\n/;\n/**\nDistinguishes different ways in which positions can be mapped.\n*/\nvar MapMode = /*@__PURE__*/(function (MapMode) {\n /**\n Map a position to a valid new position, even when its context\n was deleted.\n */\n MapMode[MapMode[\"Simple\"] = 0] = \"Simple\";\n /**\n Return null if deletion happens across the position.\n */\n MapMode[MapMode[\"TrackDel\"] = 1] = \"TrackDel\";\n /**\n Return null if the character _before_ the position is deleted.\n */\n MapMode[MapMode[\"TrackBefore\"] = 2] = \"TrackBefore\";\n /**\n Return null if the character _after_ the position is deleted.\n */\n MapMode[MapMode[\"TrackAfter\"] = 3] = \"TrackAfter\";\nreturn MapMode})(MapMode || (MapMode = {}));\n/**\nA change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)\nthat doesn't store the inserted text. As such, it can't be\napplied, but is cheaper to store and manipulate.\n*/\nclass ChangeDesc {\n // Sections are encoded as pairs of integers. The first is the\n // length in the current document, and the second is -1 for\n // unaffected sections, and the length of the replacement content\n // otherwise. So an insertion would be (0, n>0), a deletion (n>0,\n // 0), and a replacement two positive numbers.\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n sections) {\n this.sections = sections;\n }\n /**\n The length of the document before the change.\n */\n get length() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2)\n result += this.sections[i];\n return result;\n }\n /**\n The length of the document after the change.\n */\n get newLength() {\n let result = 0;\n for (let i = 0; i < this.sections.length; i += 2) {\n let ins = this.sections[i + 1];\n result += ins < 0 ? this.sections[i] : ins;\n }\n return result;\n }\n /**\n False when there are actual changes in this set.\n */\n get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; }\n /**\n Iterate over the unchanged parts left by these changes. `posA`\n provides the position of the range in the old document, `posB`\n the new position in the changed document.\n */\n iterGaps(f) {\n for (let i = 0, posA = 0, posB = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0) {\n f(posA, posB, len);\n posB += len;\n }\n else {\n posB += ins;\n }\n posA += len;\n }\n }\n /**\n Iterate over the ranges changed by these changes. (See\n [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a\n variant that also provides you with the inserted text.)\n `fromA`/`toA` provides the extent of the change in the starting\n document, `fromB`/`toB` the extent of the replacement in the\n changed document.\n \n When `individual` is true, adjacent changes (which are kept\n separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are\n reported separately.\n */\n iterChangedRanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a description of the inverted form of these changes.\n */\n get invertedDesc() {\n let sections = [];\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n if (ins < 0)\n sections.push(len, ins);\n else\n sections.push(ins, len);\n }\n return new ChangeDesc(sections);\n }\n /**\n Compute the combined effect of applying another set of changes\n after this one. The length of the document after this set should\n match the length before `other`.\n */\n composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other); }\n /**\n Map this description, which should start with the same document\n as `other`, over another set of changes, so that it can be\n applied after it. When `before` is true, map as if the changes\n in `other` happened before the ones in `this`.\n */\n mapDesc(other, before = false) { return other.empty ? this : mapSet(this, other, before); }\n mapPos(pos, assoc = -1, mode = MapMode.Simple) {\n let posA = 0, posB = 0;\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;\n if (ins < 0) {\n if (endA > pos)\n return posB + (pos - posA);\n posB += len;\n }\n else {\n if (mode != MapMode.Simple && endA >= pos &&\n (mode == MapMode.TrackDel && posA < pos && endA > pos ||\n mode == MapMode.TrackBefore && posA < pos ||\n mode == MapMode.TrackAfter && endA > pos))\n return null;\n if (endA > pos || endA == pos && assoc < 0 && !len)\n return pos == posA || assoc < 0 ? posB : posB + ins;\n posB += ins;\n }\n posA = endA;\n }\n if (pos > posA)\n throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);\n return posB;\n }\n /**\n Check whether these changes touch a given range. When one of the\n changes entirely covers the range, the string `\"cover\"` is\n returned.\n */\n touchesRange(from, to = from) {\n for (let i = 0, pos = 0; i < this.sections.length && pos <= to;) {\n let len = this.sections[i++], ins = this.sections[i++], end = pos + len;\n if (ins >= 0 && pos <= to && end >= from)\n return pos < from && end > to ? \"cover\" : true;\n pos = end;\n }\n return false;\n }\n /**\n @internal\n */\n toString() {\n let result = \"\";\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++];\n result += (result ? \" \" : \"\") + len + (ins >= 0 ? \":\" + ins : \"\");\n }\n return result;\n }\n /**\n Serialize this change desc to a JSON-representable value.\n */\n toJSON() { return this.sections; }\n /**\n Create a change desc from its JSON representation (as produced\n by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != \"number\"))\n throw new RangeError(\"Invalid JSON representation of ChangeDesc\");\n return new ChangeDesc(json);\n }\n /**\n @internal\n */\n static create(sections) { return new ChangeDesc(sections); }\n}\n/**\nA change set represents a group of modifications to a document. It\nstores the document length, and can only be applied to documents\nwith exactly that length.\n*/\nclass ChangeSet extends ChangeDesc {\n constructor(sections, \n /**\n @internal\n */\n inserted) {\n super(sections);\n this.inserted = inserted;\n }\n /**\n Apply the changes to a document, returning the modified\n document.\n */\n apply(doc) {\n if (this.length != doc.length)\n throw new RangeError(\"Applying change set to a document with the wrong length\");\n iterChanges(this, (fromA, toA, fromB, _toB, text) => doc = doc.replace(fromB, fromB + (toA - fromA), text), false);\n return doc;\n }\n mapDesc(other, before = false) { return mapSet(this, other, before, true); }\n /**\n Given the document as it existed _before_ the changes, return a\n change set that represents the inverse of this set, which could\n be used to go from the document created by the changes back to\n the document as it existed before the changes.\n */\n invert(doc) {\n let sections = this.sections.slice(), inserted = [];\n for (let i = 0, pos = 0; i < sections.length; i += 2) {\n let len = sections[i], ins = sections[i + 1];\n if (ins >= 0) {\n sections[i] = ins;\n sections[i + 1] = len;\n let index = i >> 1;\n while (inserted.length < index)\n inserted.push(Text.empty);\n inserted.push(len ? doc.slice(pos, pos + len) : Text.empty);\n }\n pos += len;\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n Combine two subsequent change sets into a single set. `other`\n must start in the document produced by `this`. If `this` goes\n `docA` → `docB` and `other` represents `docB` → `docC`, the\n returned value will represent the change `docA` → `docC`.\n */\n compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, true); }\n /**\n Given another change set starting in the same document, maps this\n change set over the other, producing a new change set that can be\n applied to the document produced by applying `other`. When\n `before` is `true`, order changes as if `this` comes before\n `other`, otherwise (the default) treat `other` as coming first.\n \n Given two changes `A` and `B`, `A.compose(B.map(A))` and\n `B.compose(A.map(B, true))` will produce the same document. This\n provides a basic form of [operational\n transformation](https://en.wikipedia.org/wiki/Operational_transformation),\n and can be used for collaborative editing.\n */\n map(other, before = false) { return other.empty ? this : mapSet(this, other, before, true); }\n /**\n Iterate over the changed ranges in the document, calling `f` for\n each, with the range in the original document (`fromA`-`toA`)\n and the range that replaces it in the new document\n (`fromB`-`toB`).\n \n When `individual` is true, adjacent changes are reported\n separately.\n */\n iterChanges(f, individual = false) {\n iterChanges(this, f, individual);\n }\n /**\n Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change\n set.\n */\n get desc() { return ChangeDesc.create(this.sections); }\n /**\n @internal\n */\n filter(ranges) {\n let resultSections = [], resultInserted = [], filteredSections = [];\n let iter = new SectionIter(this);\n done: for (let i = 0, pos = 0;;) {\n let next = i == ranges.length ? 1e9 : ranges[i++];\n while (pos < next || pos == next && iter.len == 0) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, next - pos);\n addSection(filteredSections, len, -1);\n let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;\n addSection(resultSections, len, ins);\n if (ins > 0)\n addInsert(resultInserted, resultSections, iter.text);\n iter.forward(len);\n pos += len;\n }\n let end = ranges[i++];\n while (pos < end) {\n if (iter.done)\n break done;\n let len = Math.min(iter.len, end - pos);\n addSection(resultSections, len, -1);\n addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);\n iter.forward(len);\n pos += len;\n }\n }\n return { changes: new ChangeSet(resultSections, resultInserted),\n filtered: ChangeDesc.create(filteredSections) };\n }\n /**\n Serialize this change set to a JSON-representable value.\n */\n toJSON() {\n let parts = [];\n for (let i = 0; i < this.sections.length; i += 2) {\n let len = this.sections[i], ins = this.sections[i + 1];\n if (ins < 0)\n parts.push(len);\n else if (ins == 0)\n parts.push([len]);\n else\n parts.push([len].concat(this.inserted[i >> 1].toJSON()));\n }\n return parts;\n }\n /**\n Create a change set for the given changes, for a document of the\n given length, using `lineSep` as line separator.\n */\n static of(changes, length, lineSep) {\n let sections = [], inserted = [], pos = 0;\n let total = null;\n function flush(force = false) {\n if (!force && !sections.length)\n return;\n if (pos < length)\n addSection(sections, length - pos, -1);\n let set = new ChangeSet(sections, inserted);\n total = total ? total.compose(set.map(total)) : set;\n sections = [];\n inserted = [];\n pos = 0;\n }\n function process(spec) {\n if (Array.isArray(spec)) {\n for (let sub of spec)\n process(sub);\n }\n else if (spec instanceof ChangeSet) {\n if (spec.length != length)\n throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);\n flush();\n total = total ? total.compose(spec.map(total)) : spec;\n }\n else {\n let { from, to = from, insert } = spec;\n if (from > to || from < 0 || to > length)\n throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);\n let insText = !insert ? Text.empty : typeof insert == \"string\" ? Text.of(insert.split(lineSep || DefaultSplit)) : insert;\n let insLen = insText.length;\n if (from == to && insLen == 0)\n return;\n if (from < pos)\n flush();\n if (from > pos)\n addSection(sections, from - pos, -1);\n addSection(sections, to - from, insLen);\n addInsert(inserted, sections, insText);\n pos = to;\n }\n }\n process(changes);\n flush(!total);\n return total;\n }\n /**\n Create an empty changeset of the given length.\n */\n static empty(length) {\n return new ChangeSet(length ? [length, -1] : [], []);\n }\n /**\n Create a changeset from its JSON representation (as produced by\n [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).\n */\n static fromJSON(json) {\n if (!Array.isArray(json))\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n let sections = [], inserted = [];\n for (let i = 0; i < json.length; i++) {\n let part = json[i];\n if (typeof part == \"number\") {\n sections.push(part, -1);\n }\n else if (!Array.isArray(part) || typeof part[0] != \"number\" || part.some((e, i) => i && typeof e != \"string\")) {\n throw new RangeError(\"Invalid JSON representation of ChangeSet\");\n }\n else if (part.length == 1) {\n sections.push(part[0], 0);\n }\n else {\n while (inserted.length < i)\n inserted.push(Text.empty);\n inserted[i] = Text.of(part.slice(1));\n sections.push(part[0], inserted[i].length);\n }\n }\n return new ChangeSet(sections, inserted);\n }\n /**\n @internal\n */\n static createSet(sections, inserted) {\n return new ChangeSet(sections, inserted);\n }\n}\nfunction addSection(sections, len, ins, forceJoin = false) {\n if (len == 0 && ins <= 0)\n return;\n let last = sections.length - 2;\n if (last >= 0 && ins <= 0 && ins == sections[last + 1])\n sections[last] += len;\n else if (len == 0 && sections[last] == 0)\n sections[last + 1] += ins;\n else if (forceJoin) {\n sections[last] += len;\n sections[last + 1] += ins;\n }\n else\n sections.push(len, ins);\n}\nfunction addInsert(values, sections, value) {\n if (value.length == 0)\n return;\n let index = (sections.length - 2) >> 1;\n if (index < values.length) {\n values[values.length - 1] = values[values.length - 1].append(value);\n }\n else {\n while (values.length < index)\n values.push(Text.empty);\n values.push(value);\n }\n}\nfunction iterChanges(desc, f, individual) {\n let inserted = desc.inserted;\n for (let posA = 0, posB = 0, i = 0; i < desc.sections.length;) {\n let len = desc.sections[i++], ins = desc.sections[i++];\n if (ins < 0) {\n posA += len;\n posB += len;\n }\n else {\n let endA = posA, endB = posB, text = Text.empty;\n for (;;) {\n endA += len;\n endB += ins;\n if (ins && inserted)\n text = text.append(inserted[(i - 2) >> 1]);\n if (individual || i == desc.sections.length || desc.sections[i + 1] < 0)\n break;\n len = desc.sections[i++];\n ins = desc.sections[i++];\n }\n f(posA, endA, posB, endB, text);\n posA = endA;\n posB = endB;\n }\n }\n}\nfunction mapSet(setA, setB, before, mkSet = false) {\n // Produce a copy of setA that applies to the document after setB\n // has been applied (assuming both start at the same document).\n let sections = [], insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n // Iterate over both sets in parallel. inserted tracks, for changes\n // in A that have to be processed piece-by-piece, whether their\n // content has been inserted already, and refers to the section\n // index.\n for (let inserted = -1;;) {\n if (a.ins == -1 && b.ins == -1) {\n // Move across ranges skipped by both sets.\n let len = Math.min(a.len, b.len);\n addSection(sections, len, -1);\n a.forward(len);\n b.forward(len);\n }\n else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {\n // If there's a change in B that comes before the next change in\n // A (ordered by start pos, then len, then before flag), skip\n // that (and process any changes in A it covers).\n let len = b.len;\n addSection(sections, b.ins, -1);\n while (len) {\n let piece = Math.min(a.len, len);\n if (a.ins >= 0 && inserted < a.i && a.len <= piece) {\n addSection(sections, 0, a.ins);\n if (insert)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n }\n a.forward(piece);\n len -= piece;\n }\n b.next();\n }\n else if (a.ins >= 0) {\n // Process the part of a change in A up to the start of the next\n // non-deletion change in B (if overlapping).\n let len = 0, left = a.len;\n while (left) {\n if (b.ins == -1) {\n let piece = Math.min(left, b.len);\n len += piece;\n left -= piece;\n b.forward(piece);\n }\n else if (b.ins == 0 && b.len < left) {\n left -= b.len;\n b.next();\n }\n else {\n break;\n }\n }\n addSection(sections, len, inserted < a.i ? a.ins : 0);\n if (insert && inserted < a.i)\n addInsert(insert, sections, a.text);\n inserted = a.i;\n a.forward(a.len - left);\n }\n else if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else {\n throw new Error(\"Mismatched change set lengths\");\n }\n }\n}\nfunction composeSets(setA, setB, mkSet = false) {\n let sections = [];\n let insert = mkSet ? [] : null;\n let a = new SectionIter(setA), b = new SectionIter(setB);\n for (let open = false;;) {\n if (a.done && b.done) {\n return insert ? ChangeSet.createSet(sections, insert) : ChangeDesc.create(sections);\n }\n else if (a.ins == 0) { // Deletion in A\n addSection(sections, a.len, 0, open);\n a.next();\n }\n else if (b.len == 0 && !b.done) { // Insertion in B\n addSection(sections, 0, b.ins, open);\n if (insert)\n addInsert(insert, sections, b.text);\n b.next();\n }\n else if (a.done || b.done) {\n throw new Error(\"Mismatched change set lengths\");\n }\n else {\n let len = Math.min(a.len2, b.len), sectionLen = sections.length;\n if (a.ins == -1) {\n let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;\n addSection(sections, len, insB, open);\n if (insert && insB)\n addInsert(insert, sections, b.text);\n }\n else if (b.ins == -1) {\n addSection(sections, a.off ? 0 : a.len, len, open);\n if (insert)\n addInsert(insert, sections, a.textBit(len));\n }\n else {\n addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);\n if (insert && !b.off)\n addInsert(insert, sections, b.text);\n }\n open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);\n a.forward2(len);\n b.forward(len);\n }\n }\n}\nclass SectionIter {\n constructor(set) {\n this.set = set;\n this.i = 0;\n this.next();\n }\n next() {\n let { sections } = this.set;\n if (this.i < sections.length) {\n this.len = sections[this.i++];\n this.ins = sections[this.i++];\n }\n else {\n this.len = 0;\n this.ins = -2;\n }\n this.off = 0;\n }\n get done() { return this.ins == -2; }\n get len2() { return this.ins < 0 ? this.len : this.ins; }\n get text() {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length ? Text.empty : inserted[index];\n }\n textBit(len) {\n let { inserted } = this.set, index = (this.i - 2) >> 1;\n return index >= inserted.length && !len ? Text.empty\n : inserted[index].slice(this.off, len == null ? undefined : this.off + len);\n }\n forward(len) {\n if (len == this.len)\n this.next();\n else {\n this.len -= len;\n this.off += len;\n }\n }\n forward2(len) {\n if (this.ins == -1)\n this.forward(len);\n else if (len == this.ins)\n this.next();\n else {\n this.ins -= len;\n this.off += len;\n }\n }\n}\n\n/**\nA single selection range. When\n[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)\nis enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold\nmultiple ranges. By default, selections hold exactly one range.\n*/\nclass SelectionRange {\n constructor(\n /**\n The lower boundary of the range.\n */\n from, \n /**\n The upper boundary of the range.\n */\n to, flags) {\n this.from = from;\n this.to = to;\n this.flags = flags;\n }\n /**\n The anchor of the range—the side that doesn't move when you\n extend it.\n */\n get anchor() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.to : this.from; }\n /**\n The head of the range, which is moved when the range is\n [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).\n */\n get head() { return this.flags & 32 /* RangeFlag.Inverted */ ? this.from : this.to; }\n /**\n True when `anchor` and `head` are at the same position.\n */\n get empty() { return this.from == this.to; }\n /**\n If this is a cursor that is explicitly associated with the\n character on one of its sides, this returns the side. -1 means\n the character before its position, 1 the character after, and 0\n means no association.\n */\n get assoc() { return this.flags & 8 /* RangeFlag.AssocBefore */ ? -1 : this.flags & 16 /* RangeFlag.AssocAfter */ ? 1 : 0; }\n /**\n The bidirectional text level associated with this cursor, if\n any.\n */\n get bidiLevel() {\n let level = this.flags & 7 /* RangeFlag.BidiLevelMask */;\n return level == 7 ? null : level;\n }\n /**\n The goal column (stored vertical offset) associated with a\n cursor. This is used to preserve the vertical position when\n [moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across\n lines of different length.\n */\n get goalColumn() {\n let value = this.flags >> 6 /* RangeFlag.GoalColumnOffset */;\n return value == 16777215 /* RangeFlag.NoGoalColumn */ ? undefined : value;\n }\n /**\n Map this range through a change, producing a valid range in the\n updated document.\n */\n map(change, assoc = -1) {\n let from, to;\n if (this.empty) {\n from = to = change.mapPos(this.from, assoc);\n }\n else {\n from = change.mapPos(this.from, 1);\n to = change.mapPos(this.to, -1);\n }\n return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);\n }\n /**\n Extend this range to cover at least `from` to `to`.\n */\n extend(from, to = from) {\n if (from <= this.anchor && to >= this.anchor)\n return EditorSelection.range(from, to);\n let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;\n return EditorSelection.range(this.anchor, head);\n }\n /**\n Compare this range to another range.\n */\n eq(other, includeAssoc = false) {\n return this.anchor == other.anchor && this.head == other.head &&\n (!includeAssoc || !this.empty || this.assoc == other.assoc);\n }\n /**\n Return a JSON-serializable object representing the range.\n */\n toJSON() { return { anchor: this.anchor, head: this.head }; }\n /**\n Convert a JSON representation of a range to a `SelectionRange`\n instance.\n */\n static fromJSON(json) {\n if (!json || typeof json.anchor != \"number\" || typeof json.head != \"number\")\n throw new RangeError(\"Invalid JSON representation for SelectionRange\");\n return EditorSelection.range(json.anchor, json.head);\n }\n /**\n @internal\n */\n static create(from, to, flags) {\n return new SelectionRange(from, to, flags);\n }\n}\n/**\nAn editor selection holds one or more selection ranges.\n*/\nclass EditorSelection {\n constructor(\n /**\n The ranges in the selection, sorted by position. Ranges cannot\n overlap (but they may touch, if they aren't empty).\n */\n ranges, \n /**\n The index of the _main_ range in the selection (which is\n usually the range that was added last).\n */\n mainIndex) {\n this.ranges = ranges;\n this.mainIndex = mainIndex;\n }\n /**\n Map a selection through a change. Used to adjust the selection\n position for changes.\n */\n map(change, assoc = -1) {\n if (change.empty)\n return this;\n return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);\n }\n /**\n Compare this selection to another selection. By default, ranges\n are compared only by position. When `includeAssoc` is true,\n cursor ranges must also have the same\n [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.\n */\n eq(other, includeAssoc = false) {\n if (this.ranges.length != other.ranges.length ||\n this.mainIndex != other.mainIndex)\n return false;\n for (let i = 0; i < this.ranges.length; i++)\n if (!this.ranges[i].eq(other.ranges[i], includeAssoc))\n return false;\n return true;\n }\n /**\n Get the primary selection range. Usually, you should make sure\n your code applies to _all_ ranges, by using methods like\n [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).\n */\n get main() { return this.ranges[this.mainIndex]; }\n /**\n Make sure the selection only has one range. Returns a selection\n holding only the main range from this selection.\n */\n asSingle() {\n return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);\n }\n /**\n Extend this selection with an extra range.\n */\n addRange(range, main = true) {\n return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);\n }\n /**\n Replace a given range with another range, and then normalize the\n selection to merge and sort ranges if necessary.\n */\n replaceRange(range, which = this.mainIndex) {\n let ranges = this.ranges.slice();\n ranges[which] = range;\n return EditorSelection.create(ranges, this.mainIndex);\n }\n /**\n Convert this selection to an object that can be serialized to\n JSON.\n */\n toJSON() {\n return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex };\n }\n /**\n Create a selection from a JSON representation.\n */\n static fromJSON(json) {\n if (!json || !Array.isArray(json.ranges) || typeof json.main != \"number\" || json.main >= json.ranges.length)\n throw new RangeError(\"Invalid JSON representation for EditorSelection\");\n return new EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main);\n }\n /**\n Create a selection holding a single range.\n */\n static single(anchor, head = anchor) {\n return new EditorSelection([EditorSelection.range(anchor, head)], 0);\n }\n /**\n Sort and merge the given set of ranges, creating a valid\n selection.\n */\n static create(ranges, mainIndex = 0) {\n if (ranges.length == 0)\n throw new RangeError(\"A selection needs at least one range\");\n for (let pos = 0, i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n if (range.empty ? range.from <= pos : range.from < pos)\n return EditorSelection.normalized(ranges.slice(), mainIndex);\n pos = range.to;\n }\n return new EditorSelection(ranges, mainIndex);\n }\n /**\n Create a cursor selection range at the given position. You can\n safely ignore the optional arguments in most situations.\n */\n static cursor(pos, assoc = 0, bidiLevel, goalColumn) {\n return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 /* RangeFlag.AssocBefore */ : 16 /* RangeFlag.AssocAfter */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) |\n ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */));\n }\n /**\n Create a selection range.\n */\n static range(anchor, head, goalColumn, bidiLevel) {\n let flags = ((goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215 /* RangeFlag.NoGoalColumn */) << 6 /* RangeFlag.GoalColumnOffset */) |\n (bidiLevel == null ? 7 : Math.min(6, bidiLevel));\n return head < anchor ? SelectionRange.create(head, anchor, 32 /* RangeFlag.Inverted */ | 16 /* RangeFlag.AssocAfter */ | flags)\n : SelectionRange.create(anchor, head, (head > anchor ? 8 /* RangeFlag.AssocBefore */ : 0) | flags);\n }\n /**\n @internal\n */\n static normalized(ranges, mainIndex = 0) {\n let main = ranges[mainIndex];\n ranges.sort((a, b) => a.from - b.from);\n mainIndex = ranges.indexOf(main);\n for (let i = 1; i < ranges.length; i++) {\n let range = ranges[i], prev = ranges[i - 1];\n if (range.empty ? range.from <= prev.to : range.from < prev.to) {\n let from = prev.from, to = Math.max(range.to, prev.to);\n if (i <= mainIndex)\n mainIndex--;\n ranges.splice(--i, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));\n }\n }\n return new EditorSelection(ranges, mainIndex);\n }\n}\nfunction checkSelection(selection, docLength) {\n for (let range of selection.ranges)\n if (range.to > docLength)\n throw new RangeError(\"Selection points outside of document\");\n}\n\nlet nextID = 0;\n/**\nA facet is a labeled value that is associated with an editor\nstate. It takes inputs from any number of extensions, and combines\nthose into a single output value.\n\nExamples of uses of facets are the [tab\nsize](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor\nattributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update\nlisteners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).\n\nNote that `Facet` instances can be used anywhere where\n[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.\n*/\nclass Facet {\n constructor(\n /**\n @internal\n */\n combine, \n /**\n @internal\n */\n compareInput, \n /**\n @internal\n */\n compare, isStatic, enables) {\n this.combine = combine;\n this.compareInput = compareInput;\n this.compare = compare;\n this.isStatic = isStatic;\n /**\n @internal\n */\n this.id = nextID++;\n this.default = combine([]);\n this.extensions = typeof enables == \"function\" ? enables(this) : enables;\n }\n /**\n Returns a facet reader for this facet, which can be used to\n [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.\n */\n get reader() { return this; }\n /**\n Define a new facet.\n */\n static define(config = {}) {\n return new Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray$1 : (a, b) => a === b), !!config.static, config.enables);\n }\n /**\n Returns an extension that adds the given value to this facet.\n */\n of(value) {\n return new FacetProvider([], this, 0 /* Provider.Static */, value);\n }\n /**\n Create an extension that computes a value for the facet from a\n state. You must take care to declare the parts of the state that\n this value depends on, since your function is only called again\n for a new state when one of those parts changed.\n \n In cases where your value depends only on a single field, you'll\n want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.\n */\n compute(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 1 /* Provider.Single */, get);\n }\n /**\n Create an extension that computes zero or more values for this\n facet from a state.\n */\n computeN(deps, get) {\n if (this.isStatic)\n throw new Error(\"Can't compute a static facet\");\n return new FacetProvider(deps, this, 2 /* Provider.Multi */, get);\n }\n from(field, get) {\n if (!get)\n get = x => x;\n return this.compute([field], state => get(state.field(field)));\n }\n}\nfunction sameArray$1(a, b) {\n return a == b || a.length == b.length && a.every((e, i) => e === b[i]);\n}\nclass FacetProvider {\n constructor(dependencies, facet, type, value) {\n this.dependencies = dependencies;\n this.facet = facet;\n this.type = type;\n this.value = value;\n this.id = nextID++;\n }\n dynamicSlot(addresses) {\n var _a;\n let getter = this.value;\n let compare = this.facet.compareInput;\n let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2 /* Provider.Multi */;\n let depDoc = false, depSel = false, depAddrs = [];\n for (let dep of this.dependencies) {\n if (dep == \"doc\")\n depDoc = true;\n else if (dep == \"selection\")\n depSel = true;\n else if ((((_a = addresses[dep.id]) !== null && _a !== void 0 ? _a : 1) & 1) == 0)\n depAddrs.push(addresses[dep.id]);\n }\n return {\n create(state) {\n state.values[idx] = getter(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if ((depDoc && tr.docChanged) || (depSel && (tr.docChanged || tr.selection)) || ensureAll(state, depAddrs)) {\n let newVal = getter(state);\n if (multi ? !compareArray(newVal, state.values[idx], compare) : !compare(newVal, state.values[idx])) {\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n }\n return 0;\n },\n reconfigure: (state, oldState) => {\n let newVal, oldAddr = oldState.config.address[id];\n if (oldAddr != null) {\n let oldVal = getAddr(oldState, oldAddr);\n if (this.dependencies.every(dep => {\n return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) :\n dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;\n }) || (multi ? compareArray(newVal = getter(state), oldVal, compare) : compare(newVal = getter(state), oldVal))) {\n state.values[idx] = oldVal;\n return 0;\n }\n }\n else {\n newVal = getter(state);\n }\n state.values[idx] = newVal;\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n}\nfunction compareArray(a, b, compare) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (!compare(a[i], b[i]))\n return false;\n return true;\n}\nfunction ensureAll(state, addrs) {\n let changed = false;\n for (let addr of addrs)\n if (ensureAddr(state, addr) & 1 /* SlotStatus.Changed */)\n changed = true;\n return changed;\n}\nfunction dynamicFacetSlot(addresses, facet, providers) {\n let providerAddrs = providers.map(p => addresses[p.id]);\n let providerTypes = providers.map(p => p.type);\n let dynamic = providerAddrs.filter(p => !(p & 1));\n let idx = addresses[facet.id] >> 1;\n function get(state) {\n let values = [];\n for (let i = 0; i < providerAddrs.length; i++) {\n let value = getAddr(state, providerAddrs[i]);\n if (providerTypes[i] == 2 /* Provider.Multi */)\n for (let val of value)\n values.push(val);\n else\n values.push(value);\n }\n return facet.combine(values);\n }\n return {\n create(state) {\n for (let addr of providerAddrs)\n ensureAddr(state, addr);\n state.values[idx] = get(state);\n return 1 /* SlotStatus.Changed */;\n },\n update(state, tr) {\n if (!ensureAll(state, dynamic))\n return 0;\n let value = get(state);\n if (facet.compare(value, state.values[idx]))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure(state, oldState) {\n let depChanged = ensureAll(state, providerAddrs);\n let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet);\n if (oldProviders && !depChanged && sameArray$1(providers, oldProviders)) {\n state.values[idx] = oldValue;\n return 0;\n }\n let value = get(state);\n if (facet.compare(value, oldValue)) {\n state.values[idx] = oldValue;\n return 0;\n }\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n }\n };\n}\nconst initField = /*@__PURE__*/Facet.define({ static: true });\n/**\nFields can store additional information in an editor state, and\nkeep it in sync with the rest of the state.\n*/\nclass StateField {\n constructor(\n /**\n @internal\n */\n id, createF, updateF, compareF, \n /**\n @internal\n */\n spec) {\n this.id = id;\n this.createF = createF;\n this.updateF = updateF;\n this.compareF = compareF;\n this.spec = spec;\n /**\n @internal\n */\n this.provides = undefined;\n }\n /**\n Define a state field.\n */\n static define(config) {\n let field = new StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config);\n if (config.provide)\n field.provides = config.provide(field);\n return field;\n }\n create(state) {\n let init = state.facet(initField).find(i => i.field == this);\n return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);\n }\n /**\n @internal\n */\n slot(addresses) {\n let idx = addresses[this.id] >> 1;\n return {\n create: (state) => {\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n },\n update: (state, tr) => {\n let oldVal = state.values[idx];\n let value = this.updateF(oldVal, tr);\n if (this.compareF(oldVal, value))\n return 0;\n state.values[idx] = value;\n return 1 /* SlotStatus.Changed */;\n },\n reconfigure: (state, oldState) => {\n if (oldState.config.address[this.id] != null) {\n state.values[idx] = oldState.field(this);\n return 0;\n }\n state.values[idx] = this.create(state);\n return 1 /* SlotStatus.Changed */;\n }\n };\n }\n /**\n Returns an extension that enables this field and overrides the\n way it is initialized. Can be useful when you need to provide a\n non-default starting value for the field.\n */\n init(create) {\n return [this, initField.of({ field: this, create })];\n }\n /**\n State field instances can be used as\n [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a\n given state.\n */\n get extension() { return this; }\n}\nconst Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 };\nfunction prec(value) {\n return (ext) => new PrecExtension(ext, value);\n}\n/**\nBy default extensions are registered in the order they are found\nin the flattened form of nested array that was provided.\nIndividual extension values can be assigned a precedence to\noverride this. Extensions that do not have a precedence set get\nthe precedence of the nearest parent with a precedence, or\n[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The\nfinal ordering of extensions is determined by first sorting by\nprecedence and then by order within each precedence.\n*/\nconst Prec = {\n /**\n The highest precedence level, for extensions that should end up\n near the start of the precedence ordering.\n */\n highest: /*@__PURE__*/prec(Prec_.highest),\n /**\n A higher-than-default precedence, for extensions that should\n come before those with default precedence.\n */\n high: /*@__PURE__*/prec(Prec_.high),\n /**\n The default precedence, which is also used for extensions\n without an explicit precedence.\n */\n default: /*@__PURE__*/prec(Prec_.default),\n /**\n A lower-than-default precedence.\n */\n low: /*@__PURE__*/prec(Prec_.low),\n /**\n The lowest precedence level. Meant for things that should end up\n near the end of the extension order.\n */\n lowest: /*@__PURE__*/prec(Prec_.lowest)\n};\nclass PrecExtension {\n constructor(inner, prec) {\n this.inner = inner;\n this.prec = prec;\n }\n}\n/**\nExtension compartments can be used to make a configuration\ndynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your\nconfiguration in a compartment, you can later\n[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a\ntransaction.\n*/\nclass Compartment {\n /**\n Create an instance of this compartment to add to your [state\n configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).\n */\n of(ext) { return new CompartmentInstance(this, ext); }\n /**\n Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that\n reconfigures this compartment.\n */\n reconfigure(content) {\n return Compartment.reconfigure.of({ compartment: this, extension: content });\n }\n /**\n Get the current content of the compartment in the state, or\n `undefined` if it isn't present.\n */\n get(state) {\n return state.config.compartments.get(this);\n }\n}\nclass CompartmentInstance {\n constructor(compartment, inner) {\n this.compartment = compartment;\n this.inner = inner;\n }\n}\nclass Configuration {\n constructor(base, compartments, dynamicSlots, address, staticValues, facets) {\n this.base = base;\n this.compartments = compartments;\n this.dynamicSlots = dynamicSlots;\n this.address = address;\n this.staticValues = staticValues;\n this.facets = facets;\n this.statusTemplate = [];\n while (this.statusTemplate.length < dynamicSlots.length)\n this.statusTemplate.push(0 /* SlotStatus.Unresolved */);\n }\n staticFacet(facet) {\n let addr = this.address[facet.id];\n return addr == null ? facet.default : this.staticValues[addr >> 1];\n }\n static resolve(base, compartments, oldState) {\n let fields = [];\n let facets = Object.create(null);\n let newCompartments = new Map();\n for (let ext of flatten(base, compartments, newCompartments)) {\n if (ext instanceof StateField)\n fields.push(ext);\n else\n (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);\n }\n let address = Object.create(null);\n let staticValues = [];\n let dynamicSlots = [];\n for (let field of fields) {\n address[field.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => field.slot(a));\n }\n let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;\n for (let id in facets) {\n let providers = facets[id], facet = providers[0].facet;\n let oldProviders = oldFacets && oldFacets[id] || [];\n if (providers.every(p => p.type == 0 /* Provider.Static */)) {\n address[facet.id] = (staticValues.length << 1) | 1;\n if (sameArray$1(oldProviders, providers)) {\n staticValues.push(oldState.facet(facet));\n }\n else {\n let value = facet.combine(providers.map(p => p.value));\n staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);\n }\n }\n else {\n for (let p of providers) {\n if (p.type == 0 /* Provider.Static */) {\n address[p.id] = (staticValues.length << 1) | 1;\n staticValues.push(p.value);\n }\n else {\n address[p.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => p.dynamicSlot(a));\n }\n }\n address[facet.id] = dynamicSlots.length << 1;\n dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));\n }\n }\n let dynamic = dynamicSlots.map(f => f(address));\n return new Configuration(base, newCompartments, dynamic, address, staticValues, facets);\n }\n}\nfunction flatten(extension, compartments, newCompartments) {\n let result = [[], [], [], [], []];\n let seen = new Map();\n function inner(ext, prec) {\n let known = seen.get(ext);\n if (known != null) {\n if (known <= prec)\n return;\n let found = result[known].indexOf(ext);\n if (found > -1)\n result[known].splice(found, 1);\n if (ext instanceof CompartmentInstance)\n newCompartments.delete(ext.compartment);\n }\n seen.set(ext, prec);\n if (Array.isArray(ext)) {\n for (let e of ext)\n inner(e, prec);\n }\n else if (ext instanceof CompartmentInstance) {\n if (newCompartments.has(ext.compartment))\n throw new RangeError(`Duplicate use of compartment in extensions`);\n let content = compartments.get(ext.compartment) || ext.inner;\n newCompartments.set(ext.compartment, content);\n inner(content, prec);\n }\n else if (ext instanceof PrecExtension) {\n inner(ext.inner, ext.prec);\n }\n else if (ext instanceof StateField) {\n result[prec].push(ext);\n if (ext.provides)\n inner(ext.provides, prec);\n }\n else if (ext instanceof FacetProvider) {\n result[prec].push(ext);\n if (ext.facet.extensions)\n inner(ext.facet.extensions, Prec_.default);\n }\n else {\n let content = ext.extension;\n if (!content)\n throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);\n inner(content, prec);\n }\n }\n inner(extension, Prec_.default);\n return result.reduce((a, b) => a.concat(b));\n}\nfunction ensureAddr(state, addr) {\n if (addr & 1)\n return 2 /* SlotStatus.Computed */;\n let idx = addr >> 1;\n let status = state.status[idx];\n if (status == 4 /* SlotStatus.Computing */)\n throw new Error(\"Cyclic dependency between fields and/or facets\");\n if (status & 2 /* SlotStatus.Computed */)\n return status;\n state.status[idx] = 4 /* SlotStatus.Computing */;\n let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);\n return state.status[idx] = 2 /* SlotStatus.Computed */ | changed;\n}\nfunction getAddr(state, addr) {\n return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];\n}\n\nconst languageData = /*@__PURE__*/Facet.define();\nconst allowMultipleSelections = /*@__PURE__*/Facet.define({\n combine: values => values.some(v => v),\n static: true\n});\nconst lineSeparator = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : undefined,\n static: true\n});\nconst changeFilter = /*@__PURE__*/Facet.define();\nconst transactionFilter = /*@__PURE__*/Facet.define();\nconst transactionExtender = /*@__PURE__*/Facet.define();\nconst readOnly = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : false\n});\n\n/**\nAnnotations are tagged values that are used to add metadata to\ntransactions in an extensible way. They should be used to model\nthings that effect the entire transaction (such as its [time\nstamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its\n[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen\n_alongside_ the other changes made by the transaction, [state\neffects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.\n*/\nclass Annotation {\n /**\n @internal\n */\n constructor(\n /**\n The annotation type.\n */\n type, \n /**\n The value of this annotation.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Define a new type of annotation.\n */\n static define() { return new AnnotationType(); }\n}\n/**\nMarker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).\n*/\nclass AnnotationType {\n /**\n Create an instance of this annotation.\n */\n of(value) { return new Annotation(this, value); }\n}\n/**\nRepresentation of a type of state effect. Defined with\n[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).\n*/\nclass StateEffectType {\n /**\n @internal\n */\n constructor(\n // The `any` types in these function types are there to work\n // around TypeScript issue #37631, where the type guard on\n // `StateEffect.is` mysteriously stops working when these properly\n // have type `Value`.\n /**\n @internal\n */\n map) {\n this.map = map;\n }\n /**\n Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this\n type.\n */\n of(value) { return new StateEffect(this, value); }\n}\n/**\nState effects can be used to represent additional effects\nassociated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They\nare often useful to model changes to custom [state\nfields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in\ndocument or selection changes.\n*/\nclass StateEffect {\n /**\n @internal\n */\n constructor(\n /**\n @internal\n */\n type, \n /**\n The value of this effect.\n */\n value) {\n this.type = type;\n this.value = value;\n }\n /**\n Map this effect through a position mapping. Will return\n `undefined` when that ends up deleting the effect.\n */\n map(mapping) {\n let mapped = this.type.map(this.value, mapping);\n return mapped === undefined ? undefined : mapped == this.value ? this : new StateEffect(this.type, mapped);\n }\n /**\n Tells you whether this effect object is of a given\n [type](https://codemirror.net/6/docs/ref/#state.StateEffectType).\n */\n is(type) { return this.type == type; }\n /**\n Define a new effect type. The type parameter indicates the type\n of values that his effect holds. It should be a type that\n doesn't include `undefined`, since that is used in\n [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is\n removed.\n */\n static define(spec = {}) {\n return new StateEffectType(spec.map || (v => v));\n }\n /**\n Map an array of effects through a change set.\n */\n static mapEffects(effects, mapping) {\n if (!effects.length)\n return effects;\n let result = [];\n for (let effect of effects) {\n let mapped = effect.map(mapping);\n if (mapped)\n result.push(mapped);\n }\n return result;\n }\n}\n/**\nThis effect can be used to reconfigure the root extensions of\nthe editor. Doing this will discard any extensions\n[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset\nthe content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)\ncompartments.\n*/\nStateEffect.reconfigure = /*@__PURE__*/StateEffect.define();\n/**\nAppend extensions to the top-level configuration of the editor.\n*/\nStateEffect.appendConfig = /*@__PURE__*/StateEffect.define();\n/**\nChanges to the editor state are grouped into transactions.\nTypically, a user action creates a single transaction, which may\ncontain any number of document changes, may change the selection,\nor have other effects. Create a transaction by calling\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately\ndispatch one by calling\n[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).\n*/\nclass Transaction {\n constructor(\n /**\n The state from which the transaction starts.\n */\n startState, \n /**\n The document changes made by this transaction.\n */\n changes, \n /**\n The selection set by this transaction, or undefined if it\n doesn't explicitly set a selection.\n */\n selection, \n /**\n The effects added to the transaction.\n */\n effects, \n /**\n @internal\n */\n annotations, \n /**\n Whether the selection should be scrolled into view after this\n transaction is dispatched.\n */\n scrollIntoView) {\n this.startState = startState;\n this.changes = changes;\n this.selection = selection;\n this.effects = effects;\n this.annotations = annotations;\n this.scrollIntoView = scrollIntoView;\n /**\n @internal\n */\n this._doc = null;\n /**\n @internal\n */\n this._state = null;\n if (selection)\n checkSelection(selection, changes.newLength);\n if (!annotations.some((a) => a.type == Transaction.time))\n this.annotations = annotations.concat(Transaction.time.of(Date.now()));\n }\n /**\n @internal\n */\n static create(startState, changes, selection, effects, annotations, scrollIntoView) {\n return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView);\n }\n /**\n The new document produced by the transaction. Contrary to\n [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't\n force the entire new state to be computed right away, so it is\n recommended that [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter\n when they need to look at the new document.\n */\n get newDoc() {\n return this._doc || (this._doc = this.changes.apply(this.startState.doc));\n }\n /**\n The new selection produced by the transaction. If\n [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,\n this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's\n current selection through the changes made by the transaction.\n */\n get newSelection() {\n return this.selection || this.startState.selection.map(this.changes);\n }\n /**\n The new state created by the transaction. Computed on demand\n (but retained for subsequent access), so it is recommended not to\n access it in [transaction\n filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.\n */\n get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }\n /**\n Get the value of the given annotation type, if any.\n */\n annotation(type) {\n for (let ann of this.annotations)\n if (ann.type == type)\n return ann.value;\n return undefined;\n }\n /**\n Indicates whether the transaction changed the document.\n */\n get docChanged() { return !this.changes.empty; }\n /**\n Indicates whether this transaction reconfigures the state\n (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or\n with a top-level configuration\n [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).\n */\n get reconfigured() { return this.startState.config != this.state.config; }\n /**\n Returns true if the transaction has a [user\n event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to\n or more specific than `event`. For example, if the transaction\n has `\"select.pointer\"` as user event, `\"select\"` and\n `\"select.pointer\"` will match it.\n */\n isUserEvent(event) {\n let e = this.annotation(Transaction.userEvent);\n return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == \".\"));\n }\n}\n/**\nAnnotation used to store transaction timestamps. Automatically\nadded to every transaction, holding `Date.now()`.\n*/\nTransaction.time = /*@__PURE__*/Annotation.define();\n/**\nAnnotation used to associate a transaction with a user interface\nevent. Holds a string identifying the event, using a\ndot-separated format to support attaching more specific\ninformation. The events used by the core libraries are:\n\n - `\"input\"` when content is entered\n - `\"input.type\"` for typed input\n - `\"input.type.compose\"` for composition\n - `\"input.paste\"` for pasted input\n - `\"input.drop\"` when adding content with drag-and-drop\n - `\"input.complete\"` when autocompleting\n - `\"delete\"` when the user deletes content\n - `\"delete.selection\"` when deleting the selection\n - `\"delete.forward\"` when deleting forward from the selection\n - `\"delete.backward\"` when deleting backward from the selection\n - `\"delete.cut\"` when cutting to the clipboard\n - `\"move\"` when content is moved\n - `\"move.drop\"` when content is moved within the editor through drag-and-drop\n - `\"select\"` when explicitly changing the selection\n - `\"select.pointer\"` when selecting with a mouse or other pointing device\n - `\"undo\"` and `\"redo\"` for history actions\n\nUse [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check\nwhether the annotation matches a given event.\n*/\nTransaction.userEvent = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating whether a transaction should be added to\nthe undo history or not.\n*/\nTransaction.addToHistory = /*@__PURE__*/Annotation.define();\n/**\nAnnotation indicating (when present and true) that a transaction\nrepresents a change made by some other actor, not the user. This\nis used, for example, to tag other people's changes in\ncollaborative editing.\n*/\nTransaction.remote = /*@__PURE__*/Annotation.define();\nfunction joinRanges(a, b) {\n let result = [];\n for (let iA = 0, iB = 0;;) {\n let from, to;\n if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {\n from = a[iA++];\n to = a[iA++];\n }\n else if (iB < b.length) {\n from = b[iB++];\n to = b[iB++];\n }\n else\n return result;\n if (!result.length || result[result.length - 1] < from)\n result.push(from, to);\n else if (result[result.length - 1] < to)\n result[result.length - 1] = to;\n }\n}\nfunction mergeTransaction(a, b, sequential) {\n var _a;\n let mapForA, mapForB, changes;\n if (sequential) {\n mapForA = b.changes;\n mapForB = ChangeSet.empty(b.changes.length);\n changes = a.changes.compose(b.changes);\n }\n else {\n mapForA = b.changes.map(a.changes);\n mapForB = a.changes.mapDesc(b.changes, true);\n changes = a.changes.compose(mapForA);\n }\n return {\n changes,\n selection: b.selection ? b.selection.map(mapForB) : (_a = a.selection) === null || _a === void 0 ? void 0 : _a.map(mapForA),\n effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),\n annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,\n scrollIntoView: a.scrollIntoView || b.scrollIntoView\n };\n}\nfunction resolveTransactionInner(state, spec, docSize) {\n let sel = spec.selection, annotations = asArray$1(spec.annotations);\n if (spec.userEvent)\n annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));\n return {\n changes: spec.changes instanceof ChangeSet ? spec.changes\n : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)),\n selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),\n effects: asArray$1(spec.effects),\n annotations,\n scrollIntoView: !!spec.scrollIntoView\n };\n}\nfunction resolveTransaction(state, specs, filter) {\n let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);\n if (specs.length && specs[0].filter === false)\n filter = false;\n for (let i = 1; i < specs.length; i++) {\n if (specs[i].filter === false)\n filter = false;\n let seq = !!specs[i].sequential;\n s = mergeTransaction(s, resolveTransactionInner(state, specs[i], seq ? s.changes.newLength : state.doc.length), seq);\n }\n let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);\n return extendTransaction(filter ? filterTransaction(tr) : tr);\n}\n// Finish a transaction by applying filters if necessary.\nfunction filterTransaction(tr) {\n let state = tr.startState;\n // Change filters\n let result = true;\n for (let filter of state.facet(changeFilter)) {\n let value = filter(tr);\n if (value === false) {\n result = false;\n break;\n }\n if (Array.isArray(value))\n result = result === true ? value : joinRanges(result, value);\n }\n if (result !== true) {\n let changes, back;\n if (result === false) {\n back = tr.changes.invertedDesc;\n changes = ChangeSet.empty(state.doc.length);\n }\n else {\n let filtered = tr.changes.filter(result);\n changes = filtered.changes;\n back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;\n }\n tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);\n }\n // Transaction filters\n let filters = state.facet(transactionFilter);\n for (let i = filters.length - 1; i >= 0; i--) {\n let filtered = filters[i](tr);\n if (filtered instanceof Transaction)\n tr = filtered;\n else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction)\n tr = filtered[0];\n else\n tr = resolveTransaction(state, asArray$1(filtered), false);\n }\n return tr;\n}\nfunction extendTransaction(tr) {\n let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr;\n for (let i = extenders.length - 1; i >= 0; i--) {\n let extension = extenders[i](tr);\n if (extension && Object.keys(extension).length)\n spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);\n }\n return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);\n}\nconst none$2 = [];\nfunction asArray$1(value) {\n return value == null ? none$2 : Array.isArray(value) ? value : [value];\n}\n\n/**\nThe categories produced by a [character\ncategorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used\ndo things like selecting by word.\n*/\nvar CharCategory = /*@__PURE__*/(function (CharCategory) {\n /**\n Word characters.\n */\n CharCategory[CharCategory[\"Word\"] = 0] = \"Word\";\n /**\n Whitespace.\n */\n CharCategory[CharCategory[\"Space\"] = 1] = \"Space\";\n /**\n Anything else.\n */\n CharCategory[CharCategory[\"Other\"] = 2] = \"Other\";\nreturn CharCategory})(CharCategory || (CharCategory = {}));\nconst nonASCIISingleCaseWordChar = /[\\u00df\\u0587\\u0590-\\u05f4\\u0600-\\u06ff\\u3040-\\u309f\\u30a0-\\u30ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\uac00-\\ud7af]/;\nlet wordChar;\ntry {\n wordChar = /*@__PURE__*/new RegExp(\"[\\\\p{Alphabetic}\\\\p{Number}_]\", \"u\");\n}\ncatch (_) { }\nfunction hasWordChar(str) {\n if (wordChar)\n return wordChar.test(str);\n for (let i = 0; i < str.length; i++) {\n let ch = str[i];\n if (/\\w/.test(ch) || ch > \"\\x80\" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)))\n return true;\n }\n return false;\n}\nfunction makeCategorizer(wordChars) {\n return (char) => {\n if (!/\\S/.test(char))\n return CharCategory.Space;\n if (hasWordChar(char))\n return CharCategory.Word;\n for (let i = 0; i < wordChars.length; i++)\n if (char.indexOf(wordChars[i]) > -1)\n return CharCategory.Word;\n return CharCategory.Other;\n };\n}\n\n/**\nThe editor state class is a persistent (immutable) data structure.\nTo update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a\n[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state\ninstance, without modifying the original object.\n\nAs such, _never_ mutate properties of a state directly. That'll\njust break things.\n*/\nclass EditorState {\n constructor(\n /**\n @internal\n */\n config, \n /**\n The current document.\n */\n doc, \n /**\n The current selection.\n */\n selection, \n /**\n @internal\n */\n values, computeSlot, tr) {\n this.config = config;\n this.doc = doc;\n this.selection = selection;\n this.values = values;\n this.status = config.statusTemplate.slice();\n this.computeSlot = computeSlot;\n // Fill in the computed state immediately, so that further queries\n // for it made during the update return this state\n if (tr)\n tr._state = this;\n for (let i = 0; i < this.config.dynamicSlots.length; i++)\n ensureAddr(this, i << 1);\n this.computeSlot = null;\n }\n field(field, require = true) {\n let addr = this.config.address[field.id];\n if (addr == null) {\n if (require)\n throw new RangeError(\"Field is not present in this state\");\n return undefined;\n }\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this\n state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)\n can be passed. Unless\n [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the\n [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec\n are assumed to start in the _current_ document (not the document\n produced by previous specs), and its\n [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and\n [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer\n to the document created by its _own_ changes. The resulting\n transaction contains the combined effect of all the different\n specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later\n specs take precedence over earlier ones.\n */\n update(...specs) {\n return resolveTransaction(this, specs, true);\n }\n /**\n @internal\n */\n applyTransaction(tr) {\n let conf = this.config, { base, compartments } = conf;\n for (let effect of tr.effects) {\n if (effect.is(Compartment.reconfigure)) {\n if (conf) {\n compartments = new Map;\n conf.compartments.forEach((val, key) => compartments.set(key, val));\n conf = null;\n }\n compartments.set(effect.value.compartment, effect.value.extension);\n }\n else if (effect.is(StateEffect.reconfigure)) {\n conf = null;\n base = effect.value;\n }\n else if (effect.is(StateEffect.appendConfig)) {\n conf = null;\n base = asArray$1(base).concat(effect.value);\n }\n }\n let startValues;\n if (!conf) {\n conf = Configuration.resolve(base, compartments, this);\n let intermediateState = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null);\n startValues = intermediateState.values;\n }\n else {\n startValues = tr.startState.values.slice();\n }\n let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();\n new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);\n }\n /**\n Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that\n replaces every selection range with the given content.\n */\n replaceSelection(text) {\n if (typeof text == \"string\")\n text = this.toText(text);\n return this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text },\n range: EditorSelection.cursor(range.from + text.length) }));\n }\n /**\n Create a set of changes and a new selection by running the given\n function for each range in the active selection. The function\n can return an optional set of changes (in the coordinate space\n of the start document), plus an updated range (in the coordinate\n space of the document produced by the call's own changes). This\n method will merge all the changes and ranges into a single\n changeset and selection, and return it as a [transaction\n spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to\n [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).\n */\n changeByRange(f) {\n let sel = this.selection;\n let result1 = f(sel.ranges[0]);\n let changes = this.changes(result1.changes), ranges = [result1.range];\n let effects = asArray$1(result1.effects);\n for (let i = 1; i < sel.ranges.length; i++) {\n let result = f(sel.ranges[i]);\n let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes);\n for (let j = 0; j < i; j++)\n ranges[j] = ranges[j].map(newMapped);\n let mapBy = changes.mapDesc(newChanges, true);\n ranges.push(result.range.map(mapBy));\n changes = changes.compose(newMapped);\n effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray$1(result.effects), mapBy));\n }\n return {\n changes,\n selection: EditorSelection.create(ranges, sel.mainIndex),\n effects\n };\n }\n /**\n Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change\n description, taking the state's document length and line\n separator into account.\n */\n changes(spec = []) {\n if (spec instanceof ChangeSet)\n return spec;\n return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));\n }\n /**\n Using the state's [line\n separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a\n [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.\n */\n toText(string) {\n return Text.of(string.split(this.facet(EditorState.lineSeparator) || DefaultSplit));\n }\n /**\n Return the given range of the document as a string.\n */\n sliceDoc(from = 0, to = this.doc.length) {\n return this.doc.sliceString(from, to, this.lineBreak);\n }\n /**\n Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).\n */\n facet(facet) {\n let addr = this.config.address[facet.id];\n if (addr == null)\n return facet.default;\n ensureAddr(this, addr);\n return getAddr(this, addr);\n }\n /**\n Convert this state to a JSON-serializable object. When custom\n fields should be serialized, you can pass them in as an object\n mapping property names (in the resulting object, which should\n not use `doc` or `selection`) to fields.\n */\n toJSON(fields) {\n let result = {\n doc: this.sliceDoc(),\n selection: this.selection.toJSON()\n };\n if (fields)\n for (let prop in fields) {\n let value = fields[prop];\n if (value instanceof StateField && this.config.address[value.id] != null)\n result[prop] = value.spec.toJSON(this.field(fields[prop]), this);\n }\n return result;\n }\n /**\n Deserialize a state from its JSON representation. When custom\n fields should be deserialized, pass the same object you passed\n to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as\n third argument.\n */\n static fromJSON(json, config = {}, fields) {\n if (!json || typeof json.doc != \"string\")\n throw new RangeError(\"Invalid JSON representation for EditorState\");\n let fieldInit = [];\n if (fields)\n for (let prop in fields) {\n if (Object.prototype.hasOwnProperty.call(json, prop)) {\n let field = fields[prop], value = json[prop];\n fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));\n }\n }\n return EditorState.create({\n doc: json.doc,\n selection: EditorSelection.fromJSON(json.selection),\n extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit\n });\n }\n /**\n Create a new state. You'll usually only need this when\n initializing an editor—updated states are created by applying\n transactions.\n */\n static create(config = {}) {\n let configuration = Configuration.resolve(config.extensions || [], new Map);\n let doc = config.doc instanceof Text ? config.doc\n : Text.of((config.doc || \"\").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit));\n let selection = !config.selection ? EditorSelection.single(0)\n : config.selection instanceof EditorSelection ? config.selection\n : EditorSelection.single(config.selection.anchor, config.selection.head);\n checkSelection(selection, doc.length);\n if (!configuration.staticFacet(allowMultipleSelections))\n selection = selection.asSingle();\n return new EditorState(configuration, doc, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);\n }\n /**\n The size (in columns) of a tab in the document, determined by\n the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.\n */\n get tabSize() { return this.facet(EditorState.tabSize); }\n /**\n Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)\n string for this state.\n */\n get lineBreak() { return this.facet(EditorState.lineSeparator) || \"\\n\"; }\n /**\n Returns true when the editor is\n [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.\n */\n get readOnly() { return this.facet(readOnly); }\n /**\n Look up a translation for the given phrase (via the\n [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the\n original string if no translation is found.\n \n If additional arguments are passed, they will be inserted in\n place of markers like `$1` (for the first value) and `$2`, etc.\n A single `$` is equivalent to `$1`, and `$$` will produce a\n literal dollar sign.\n */\n phrase(phrase, ...insert) {\n for (let map of this.facet(EditorState.phrases))\n if (Object.prototype.hasOwnProperty.call(map, phrase)) {\n phrase = map[phrase];\n break;\n }\n if (insert.length)\n phrase = phrase.replace(/\\$(\\$|\\d*)/g, (m, i) => {\n if (i == \"$\")\n return \"$\";\n let n = +(i || 1);\n return !n || n > insert.length ? m : insert[n - 1];\n });\n return phrase;\n }\n /**\n Find the values for a given language data field, provided by the\n the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.\n \n Examples of language data fields are...\n \n - [`\"commentTokens\"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying\n comment syntax.\n - [`\"autocomplete\"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)\n for providing language-specific completion sources.\n - [`\"wordChars\"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding\n characters that should be considered part of words in this\n language.\n - [`\"closeBrackets\"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls\n bracket closing behavior.\n */\n languageDataAt(name, pos, side = -1) {\n let values = [];\n for (let provider of this.facet(languageData)) {\n for (let result of provider(this, pos, side)) {\n if (Object.prototype.hasOwnProperty.call(result, name))\n values.push(result[name]);\n }\n }\n return values;\n }\n /**\n Return a function that can categorize strings (expected to\n represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))\n into one of:\n \n - Word (contains an alphanumeric character or a character\n explicitly listed in the local language's `\"wordChars\"`\n language data, which should be a string)\n - Space (contains only whitespace)\n - Other (anything else)\n */\n charCategorizer(at) {\n return makeCategorizer(this.languageDataAt(\"wordChars\", at).join(\"\"));\n }\n /**\n Find the word at the given position, meaning the range\n containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters\n around it. If no word characters are adjacent to the position,\n this returns null.\n */\n wordAt(pos) {\n let { text, from, length } = this.doc.lineAt(pos);\n let cat = this.charCategorizer(pos);\n let start = pos - from, end = pos - from;\n while (start > 0) {\n let prev = findClusterBreak(text, start, false);\n if (cat(text.slice(prev, start)) != CharCategory.Word)\n break;\n start = prev;\n }\n while (end < length) {\n let next = findClusterBreak(text, end);\n if (cat(text.slice(end, next)) != CharCategory.Word)\n break;\n end = next;\n }\n return start == end ? null : EditorSelection.range(start + from, end + from);\n }\n}\n/**\nA facet that, when enabled, causes the editor to allow multiple\nranges to be selected. Be careful though, because by default the\neditor relies on the native DOM selection, which cannot handle\nmultiple selections. An extension like\n[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make\nsecondary selections visible to the user.\n*/\nEditorState.allowMultipleSelections = allowMultipleSelections;\n/**\nConfigures the tab size to use in this state. The first\n(highest-precedence) value of the facet is used. If no value is\ngiven, this defaults to 4.\n*/\nEditorState.tabSize = /*@__PURE__*/Facet.define({\n combine: values => values.length ? values[0] : 4\n});\n/**\nThe line separator to use. By default, any of `\"\\n\"`, `\"\\r\\n\"`\nand `\"\\r\"` is treated as a separator when splitting lines, and\nlines are joined with `\"\\n\"`.\n\nWhen you configure a value here, only that precise separator\nwill be used, allowing you to round-trip documents through the\neditor without normalizing line separators.\n*/\nEditorState.lineSeparator = lineSeparator;\n/**\nThis facet controls the value of the\n[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is\nconsulted by commands and extensions that implement editing\nfunctionality to determine whether they should apply. It\ndefaults to false, but when its highest-precedence value is\n`true`, such functionality disables itself.\n\nNot to be confused with\n[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which\ncontrols whether the editor's DOM is set to be editable (and\nthus focusable).\n*/\nEditorState.readOnly = readOnly;\n/**\nRegisters translation phrases. The\n[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through\nall objects registered with this facet to find translations for\nits argument.\n*/\nEditorState.phrases = /*@__PURE__*/Facet.define({\n compare(a, b) {\n let kA = Object.keys(a), kB = Object.keys(b);\n return kA.length == kB.length && kA.every(k => a[k] == b[k]);\n }\n});\n/**\nA facet used to register [language\ndata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.\n*/\nEditorState.languageData = languageData;\n/**\nFacet used to register change filters, which are called for each\ntransaction (unless explicitly\n[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress\npart of the transaction's changes.\n\nSuch a function can return `true` to indicate that it doesn't\nwant to do anything, `false` to completely stop the changes in\nthe transaction, or a set of ranges in which changes should be\nsuppressed. Such ranges are represented as an array of numbers,\nwith each pair of two numbers indicating the start and end of a\nrange. So for example `[10, 20, 100, 110]` suppresses changes\nbetween 10 and 20, and between 100 and 110.\n*/\nEditorState.changeFilter = changeFilter;\n/**\nFacet used to register a hook that gets a chance to update or\nreplace transaction specs before they are applied. This will\nonly be applied for transactions that don't have\n[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You\ncan either return a single transaction spec (possibly the input\ntransaction), or an array of specs (which will be combined in\nthe same way as the arguments to\n[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).\n\nWhen possible, it is recommended to avoid accessing\n[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,\nsince it will force creation of a state that will then be\ndiscarded again, if the transaction is actually filtered.\n\n(This functionality should be used with care. Indiscriminately\nmodifying transaction is likely to break something or degrade\nthe user experience.)\n*/\nEditorState.transactionFilter = transactionFilter;\n/**\nThis is a more limited form of\n[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),\nwhich can only add\n[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and\n[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type\nof filter runs even if the transaction has disabled regular\n[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable\nfor effects that don't need to touch the changes or selection,\nbut do want to process every transaction.\n\nExtenders run _after_ filters, when both are present.\n*/\nEditorState.transactionExtender = transactionExtender;\nCompartment.reconfigure = /*@__PURE__*/StateEffect.define();\n\n/**\nUtility function for combining behaviors to fill in a config\nobject from an array of provided configs. `defaults` should hold\ndefault values for all optional fields in `Config`.\n\nThe function will, by default, error\nwhen a field gets two values that aren't `===`-equal, but you can\nprovide combine functions per field to do something else.\n*/\nfunction combineConfig(configs, defaults, // Should hold only the optional properties of Config, but I haven't managed to express that\ncombine = {}) {\n let result = {};\n for (let config of configs)\n for (let key of Object.keys(config)) {\n let value = config[key], current = result[key];\n if (current === undefined)\n result[key] = value;\n else if (current === value || value === undefined) ; // No conflict\n else if (Object.hasOwnProperty.call(combine, key))\n result[key] = combine[key](current, value);\n else\n throw new Error(\"Config merge conflict for field \" + key);\n }\n for (let key in defaults)\n if (result[key] === undefined)\n result[key] = defaults[key];\n return result;\n}\n\n/**\nEach range is associated with a value, which must inherit from\nthis class.\n*/\nclass RangeValue {\n /**\n Compare this value with another value. Used when comparing\n rangesets. The default implementation compares by identity.\n Unless you are only creating a fixed number of unique instances\n of your value type, it is a good idea to implement this\n properly.\n */\n eq(other) { return this == other; }\n /**\n Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.\n */\n range(from, to = from) { return Range$1.create(from, to, this); }\n}\nRangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;\nRangeValue.prototype.point = false;\nRangeValue.prototype.mapMode = MapMode.TrackDel;\n/**\nA range associates a value with a range of positions.\n*/\nlet Range$1 = class Range {\n constructor(\n /**\n The range's start position.\n */\n from, \n /**\n Its end position.\n */\n to, \n /**\n The value associated with this range.\n */\n value) {\n this.from = from;\n this.to = to;\n this.value = value;\n }\n /**\n @internal\n */\n static create(from, to, value) {\n return new Range(from, to, value);\n }\n};\nfunction cmpRange(a, b) {\n return a.from - b.from || a.value.startSide - b.value.startSide;\n}\nclass Chunk {\n constructor(from, to, value, \n // Chunks are marked with the largest point that occurs\n // in them (or -1 for no points), so that scans that are\n // only interested in points (such as the\n // heightmap-related logic) can skip range-only chunks.\n maxPoint) {\n this.from = from;\n this.to = to;\n this.value = value;\n this.maxPoint = maxPoint;\n }\n get length() { return this.to[this.to.length - 1]; }\n // Find the index of the given position and side. Use the ranges'\n // `from` pos when `end == false`, `to` when `end == true`.\n findIndex(pos, side, end, startAt = 0) {\n let arr = end ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }\n between(offset, from, to, f) {\n for (let i = this.findIndex(from, -1000000000 /* C.Far */, true), e = this.findIndex(to, 1000000000 /* C.Far */, false, i); i < e; i++)\n if (f(this.from[i] + offset, this.to[i] + offset, this.value[i]) === false)\n return false;\n }\n map(offset, changes) {\n let value = [], from = [], to = [], newPos = -1, maxPoint = -1;\n for (let i = 0; i < this.value.length; i++) {\n let val = this.value[i], curFrom = this.from[i] + offset, curTo = this.to[i] + offset, newFrom, newTo;\n if (curFrom == curTo) {\n let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);\n if (mapped == null)\n continue;\n newFrom = newTo = mapped;\n if (val.startSide != val.endSide) {\n newTo = changes.mapPos(curFrom, val.endSide);\n if (newTo < newFrom)\n continue;\n }\n }\n else {\n newFrom = changes.mapPos(curFrom, val.startSide);\n newTo = changes.mapPos(curTo, val.endSide);\n if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0)\n continue;\n }\n if ((newTo - newFrom || val.endSide - val.startSide) < 0)\n continue;\n if (newPos < 0)\n newPos = newFrom;\n if (val.point)\n maxPoint = Math.max(maxPoint, newTo - newFrom);\n value.push(val);\n from.push(newFrom - newPos);\n to.push(newTo - newPos);\n }\n return { mapped: value.length ? new Chunk(from, to, value, maxPoint) : null, pos: newPos };\n }\n}\n/**\nA range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a\nway that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and\n[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data\nstructure.\n*/\nclass RangeSet {\n constructor(\n /**\n @internal\n */\n chunkPos, \n /**\n @internal\n */\n chunk, \n /**\n @internal\n */\n nextLayer, \n /**\n @internal\n */\n maxPoint) {\n this.chunkPos = chunkPos;\n this.chunk = chunk;\n this.nextLayer = nextLayer;\n this.maxPoint = maxPoint;\n }\n /**\n @internal\n */\n static create(chunkPos, chunk, nextLayer, maxPoint) {\n return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);\n }\n /**\n @internal\n */\n get length() {\n let last = this.chunk.length - 1;\n return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);\n }\n /**\n The number of ranges in the set.\n */\n get size() {\n if (this.isEmpty)\n return 0;\n let size = this.nextLayer.size;\n for (let chunk of this.chunk)\n size += chunk.value.length;\n return size;\n }\n /**\n @internal\n */\n chunkEnd(index) {\n return this.chunkPos[index] + this.chunk[index].length;\n }\n /**\n Update the range set, optionally adding new ranges or filtering\n out existing ones.\n \n (Note: The type parameter is just there as a kludge to work\n around TypeScript variance issues that prevented `RangeSet`\n from being a subtype of `RangeSet` when `X` is a subtype of\n `Y`.)\n */\n update(updateSpec) {\n let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec;\n let filter = updateSpec.filter;\n if (add.length == 0 && !filter)\n return this;\n if (sort)\n add = add.slice().sort(cmpRange);\n if (this.isEmpty)\n return add.length ? RangeSet.of(add) : this;\n let cur = new LayerCursor(this, null, -1).goto(0), i = 0, spill = [];\n let builder = new RangeSetBuilder();\n while (cur.value || i < add.length) {\n if (i < add.length && (cur.from - add[i].from || cur.startSide - add[i].value.startSide) >= 0) {\n let range = add[i++];\n if (!builder.addInner(range.from, range.to, range.value))\n spill.push(range);\n }\n else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length &&\n (i == add.length || this.chunkEnd(cur.chunkIndex) < add[i].from) &&\n (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) &&\n builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) {\n cur.nextChunk();\n }\n else {\n if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) {\n if (!builder.addInner(cur.from, cur.to, cur.value))\n spill.push(Range$1.create(cur.from, cur.to, cur.value));\n }\n cur.next();\n }\n }\n return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty\n : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo }));\n }\n /**\n Map this range set through a set of changes, return the new set.\n */\n map(changes) {\n if (changes.empty || this.isEmpty)\n return this;\n let chunks = [], chunkPos = [], maxPoint = -1;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n let touch = changes.touchesRange(start, start + chunk.length);\n if (touch === false) {\n maxPoint = Math.max(maxPoint, chunk.maxPoint);\n chunks.push(chunk);\n chunkPos.push(changes.mapPos(start));\n }\n else if (touch === true) {\n let { mapped, pos } = chunk.map(start, changes);\n if (mapped) {\n maxPoint = Math.max(maxPoint, mapped.maxPoint);\n chunks.push(mapped);\n chunkPos.push(pos);\n }\n }\n }\n let next = this.nextLayer.map(changes);\n return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);\n }\n /**\n Iterate over the ranges that touch the region `from` to `to`,\n calling `f` for each. There is no guarantee that the ranges will\n be reported in any specific order. When the callback returns\n `false`, iteration stops.\n */\n between(from, to, f) {\n if (this.isEmpty)\n return;\n for (let i = 0; i < this.chunk.length; i++) {\n let start = this.chunkPos[i], chunk = this.chunk[i];\n if (to >= start && from <= start + chunk.length &&\n chunk.between(start, from - start, to - start, f) === false)\n return;\n }\n this.nextLayer.between(from, to, f);\n }\n /**\n Iterate over the ranges in this set, in order, including all\n ranges that end at or after `from`.\n */\n iter(from = 0) {\n return HeapCursor.from([this]).goto(from);\n }\n /**\n @internal\n */\n get isEmpty() { return this.nextLayer == this; }\n /**\n Iterate over the ranges in a collection of sets, in order,\n starting from `from`.\n */\n static iter(sets, from = 0) {\n return HeapCursor.from(sets).goto(from);\n }\n /**\n Iterate over two groups of sets, calling methods on `comparator`\n to notify it of possible differences.\n */\n static compare(oldSets, newSets, \n /**\n This indicates how the underlying data changed between these\n ranges, and is needed to synchronize the iteration.\n */\n textDiff, comparator, \n /**\n Can be used to ignore all non-point ranges, and points below\n the given size. When -1, all ranges are compared.\n */\n minPointSize = -1) {\n let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);\n let sharedChunks = findSharedChunks(a, b, textDiff);\n let sideA = new SpanCursor(a, sharedChunks, minPointSize);\n let sideB = new SpanCursor(b, sharedChunks, minPointSize);\n textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));\n if (textDiff.empty && textDiff.length == 0)\n compare(sideA, 0, sideB, 0, 0, comparator);\n }\n /**\n Compare the contents of two groups of range sets, returning true\n if they are equivalent in the given range.\n */\n static eq(oldSets, newSets, from = 0, to) {\n if (to == null)\n to = 1000000000 /* C.Far */ - 1;\n let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);\n let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);\n if (a.length != b.length)\n return false;\n if (!a.length)\n return true;\n let sharedChunks = findSharedChunks(a, b);\n let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from);\n for (;;) {\n if (sideA.to != sideB.to ||\n !sameValues(sideA.active, sideB.active) ||\n sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))\n return false;\n if (sideA.to > to)\n return true;\n sideA.next();\n sideB.next();\n }\n }\n /**\n Iterate over a group of range sets at the same time, notifying\n the iterator about the ranges covering every given piece of\n content. Returns the open count (see\n [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end\n of the iteration.\n */\n static spans(sets, from, to, iterator, \n /**\n When given and greater than -1, only points of at least this\n size are taken into account.\n */\n minPointSize = -1) {\n let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from;\n let openRanges = cursor.openStart;\n for (;;) {\n let curTo = Math.min(cursor.to, to);\n if (cursor.point) {\n let active = cursor.activeForPoint(cursor.to);\n let openCount = cursor.pointFrom < from ? active.length + 1\n : cursor.point.startSide < 0 ? active.length\n : Math.min(active.length, openRanges);\n iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);\n openRanges = Math.min(cursor.openEnd(curTo), active.length);\n }\n else if (curTo > pos) {\n iterator.span(pos, curTo, cursor.active, openRanges);\n openRanges = cursor.openEnd(curTo);\n }\n if (cursor.to > to)\n return openRanges + (cursor.point && cursor.to > to ? 1 : 0);\n pos = cursor.to;\n cursor.next();\n }\n }\n /**\n Create a range set for the given range or array of ranges. By\n default, this expects the ranges to be _sorted_ (by start\n position and, if two start at the same position,\n `value.startSide`). You can pass `true` as second argument to\n cause the method to sort them.\n */\n static of(ranges, sort = false) {\n let build = new RangeSetBuilder();\n for (let range of ranges instanceof Range$1 ? [ranges] : sort ? lazySort(ranges) : ranges)\n build.add(range.from, range.to, range.value);\n return build.finish();\n }\n /**\n Join an array of range sets into a single set.\n */\n static join(sets) {\n if (!sets.length)\n return RangeSet.empty;\n let result = sets[sets.length - 1];\n for (let i = sets.length - 2; i >= 0; i--) {\n for (let layer = sets[i]; layer != RangeSet.empty; layer = layer.nextLayer)\n result = new RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint));\n }\n return result;\n }\n}\n/**\nThe empty set of ranges.\n*/\nRangeSet.empty = /*@__PURE__*/new RangeSet([], [], null, -1);\nfunction lazySort(ranges) {\n if (ranges.length > 1)\n for (let prev = ranges[0], i = 1; i < ranges.length; i++) {\n let cur = ranges[i];\n if (cmpRange(prev, cur) > 0)\n return ranges.slice().sort(cmpRange);\n prev = cur;\n }\n return ranges;\n}\nRangeSet.empty.nextLayer = RangeSet.empty;\n/**\nA range set builder is a data structure that helps build up a\n[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating\nan array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.\n*/\nclass RangeSetBuilder {\n finishChunk(newArrays) {\n this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));\n this.chunkPos.push(this.chunkStart);\n this.chunkStart = -1;\n this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);\n this.maxPoint = -1;\n if (newArrays) {\n this.from = [];\n this.to = [];\n this.value = [];\n }\n }\n /**\n Create an empty builder.\n */\n constructor() {\n this.chunks = [];\n this.chunkPos = [];\n this.chunkStart = -1;\n this.last = null;\n this.lastFrom = -1000000000 /* C.Far */;\n this.lastTo = -1000000000 /* C.Far */;\n this.from = [];\n this.to = [];\n this.value = [];\n this.maxPoint = -1;\n this.setMaxPoint = -1;\n this.nextLayer = null;\n }\n /**\n Add a range. Ranges should be added in sorted (by `from` and\n `value.startSide`) order.\n */\n add(from, to, value) {\n if (!this.addInner(from, to, value))\n (this.nextLayer || (this.nextLayer = new RangeSetBuilder)).add(from, to, value);\n }\n /**\n @internal\n */\n addInner(from, to, value) {\n let diff = from - this.lastTo || value.startSide - this.last.endSide;\n if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0)\n throw new Error(\"Ranges must be added sorted by `from` position and `startSide`\");\n if (diff < 0)\n return false;\n if (this.from.length == 250 /* C.ChunkSize */)\n this.finishChunk(true);\n if (this.chunkStart < 0)\n this.chunkStart = from;\n this.from.push(from - this.chunkStart);\n this.to.push(to - this.chunkStart);\n this.last = value;\n this.lastFrom = from;\n this.lastTo = to;\n this.value.push(value);\n if (value.point)\n this.maxPoint = Math.max(this.maxPoint, to - from);\n return true;\n }\n /**\n @internal\n */\n addChunk(from, chunk) {\n if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0)\n return false;\n if (this.from.length)\n this.finishChunk(true);\n this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);\n this.chunks.push(chunk);\n this.chunkPos.push(from);\n let last = chunk.value.length - 1;\n this.last = chunk.value[last];\n this.lastFrom = chunk.from[last] + from;\n this.lastTo = chunk.to[last] + from;\n return true;\n }\n /**\n Finish the range set. Returns the new set. The builder can't be\n used anymore after this has been called.\n */\n finish() { return this.finishInner(RangeSet.empty); }\n /**\n @internal\n */\n finishInner(next) {\n if (this.from.length)\n this.finishChunk(false);\n if (this.chunks.length == 0)\n return next;\n let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);\n this.from = null; // Make sure further `add` calls produce errors\n return result;\n }\n}\nfunction findSharedChunks(a, b, textDiff) {\n let inA = new Map();\n for (let set of a)\n for (let i = 0; i < set.chunk.length; i++)\n if (set.chunk[i].maxPoint <= 0)\n inA.set(set.chunk[i], set.chunkPos[i]);\n let shared = new Set();\n for (let set of b)\n for (let i = 0; i < set.chunk.length; i++) {\n let known = inA.get(set.chunk[i]);\n if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i] &&\n !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i].length)))\n shared.add(set.chunk[i]);\n }\n return shared;\n}\nclass LayerCursor {\n constructor(layer, skip, minPoint, rank = 0) {\n this.layer = layer;\n this.skip = skip;\n this.minPoint = minPoint;\n this.rank = rank;\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n get endSide() { return this.value ? this.value.endSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.chunkIndex = this.rangeIndex = 0;\n this.gotoInner(pos, side, false);\n return this;\n }\n gotoInner(pos, side, forward) {\n while (this.chunkIndex < this.layer.chunk.length) {\n let next = this.layer.chunk[this.chunkIndex];\n if (!(this.skip && this.skip.has(next) ||\n this.layer.chunkEnd(this.chunkIndex) < pos ||\n next.maxPoint < this.minPoint))\n break;\n this.chunkIndex++;\n forward = false;\n }\n if (this.chunkIndex < this.layer.chunk.length) {\n let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);\n if (!forward || this.rangeIndex < rangeIndex)\n this.setRangeIndex(rangeIndex);\n }\n this.next();\n }\n forward(pos, side) {\n if ((this.to - pos || this.endSide - side) < 0)\n this.gotoInner(pos, side, true);\n }\n next() {\n for (;;) {\n if (this.chunkIndex == this.layer.chunk.length) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n break;\n }\n else {\n let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex];\n let from = chunkPos + chunk.from[this.rangeIndex];\n this.from = from;\n this.to = chunkPos + chunk.to[this.rangeIndex];\n this.value = chunk.value[this.rangeIndex];\n this.setRangeIndex(this.rangeIndex + 1);\n if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint)\n break;\n }\n }\n }\n setRangeIndex(index) {\n if (index == this.layer.chunk[this.chunkIndex].value.length) {\n this.chunkIndex++;\n if (this.skip) {\n while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex]))\n this.chunkIndex++;\n }\n this.rangeIndex = 0;\n }\n else {\n this.rangeIndex = index;\n }\n }\n nextChunk() {\n this.chunkIndex++;\n this.rangeIndex = 0;\n this.next();\n }\n compare(other) {\n return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank ||\n this.to - other.to || this.endSide - other.endSide;\n }\n}\nclass HeapCursor {\n constructor(heap) {\n this.heap = heap;\n }\n static from(sets, skip = null, minPoint = -1) {\n let heap = [];\n for (let i = 0; i < sets.length; i++) {\n for (let cur = sets[i]; !cur.isEmpty; cur = cur.nextLayer) {\n if (cur.maxPoint >= minPoint)\n heap.push(new LayerCursor(cur, skip, minPoint, i));\n }\n }\n return heap.length == 1 ? heap[0] : new HeapCursor(heap);\n }\n get startSide() { return this.value ? this.value.startSide : 0; }\n goto(pos, side = -1000000000 /* C.Far */) {\n for (let cur of this.heap)\n cur.goto(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n this.next();\n return this;\n }\n forward(pos, side) {\n for (let cur of this.heap)\n cur.forward(pos, side);\n for (let i = this.heap.length >> 1; i >= 0; i--)\n heapBubble(this.heap, i);\n if ((this.to - pos || this.value.endSide - side) < 0)\n this.next();\n }\n next() {\n if (this.heap.length == 0) {\n this.from = this.to = 1000000000 /* C.Far */;\n this.value = null;\n this.rank = -1;\n }\n else {\n let top = this.heap[0];\n this.from = top.from;\n this.to = top.to;\n this.value = top.value;\n this.rank = top.rank;\n if (top.value)\n top.next();\n heapBubble(this.heap, 0);\n }\n }\n}\nfunction heapBubble(heap, index) {\n for (let cur = heap[index];;) {\n let childIndex = (index << 1) + 1;\n if (childIndex >= heap.length)\n break;\n let child = heap[childIndex];\n if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {\n child = heap[childIndex + 1];\n childIndex++;\n }\n if (cur.compare(child) < 0)\n break;\n heap[childIndex] = cur;\n heap[index] = child;\n index = childIndex;\n }\n}\nclass SpanCursor {\n constructor(sets, skip, minPoint) {\n this.minPoint = minPoint;\n this.active = [];\n this.activeTo = [];\n this.activeRank = [];\n this.minActive = -1;\n // A currently active point range, if any\n this.point = null;\n this.pointFrom = 0;\n this.pointRank = 0;\n this.to = -1000000000 /* C.Far */;\n this.endSide = 0;\n // The amount of open active ranges at the start of the iterator.\n // Not including points.\n this.openStart = -1;\n this.cursor = HeapCursor.from(sets, skip, minPoint);\n }\n goto(pos, side = -1000000000 /* C.Far */) {\n this.cursor.goto(pos, side);\n this.active.length = this.activeTo.length = this.activeRank.length = 0;\n this.minActive = -1;\n this.to = pos;\n this.endSide = side;\n this.openStart = -1;\n this.next();\n return this;\n }\n forward(pos, side) {\n while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0)\n this.removeActive(this.minActive);\n this.cursor.forward(pos, side);\n }\n removeActive(index) {\n remove(this.active, index);\n remove(this.activeTo, index);\n remove(this.activeRank, index);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n addActive(trackOpen) {\n let i = 0, { value, to, rank } = this.cursor;\n // Organize active marks by rank first, then by size\n while (i < this.activeRank.length && (rank - this.activeRank[i] || to - this.activeTo[i]) > 0)\n i++;\n insert(this.active, i, value);\n insert(this.activeTo, i, to);\n insert(this.activeRank, i, rank);\n if (trackOpen)\n insert(trackOpen, i, this.cursor.from);\n this.minActive = findMinIndex(this.active, this.activeTo);\n }\n // After calling this, if `this.point` != null, the next range is a\n // point. Otherwise, it's a regular range, covered by `this.active`.\n next() {\n let from = this.to, wasPoint = this.point;\n this.point = null;\n let trackOpen = this.openStart < 0 ? [] : null;\n for (;;) {\n let a = this.minActive;\n if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {\n if (this.activeTo[a] > from) {\n this.to = this.activeTo[a];\n this.endSide = this.active[a].endSide;\n break;\n }\n this.removeActive(a);\n if (trackOpen)\n remove(trackOpen, a);\n }\n else if (!this.cursor.value) {\n this.to = this.endSide = 1000000000 /* C.Far */;\n break;\n }\n else if (this.cursor.from > from) {\n this.to = this.cursor.from;\n this.endSide = this.cursor.startSide;\n break;\n }\n else {\n let nextVal = this.cursor.value;\n if (!nextVal.point) { // Opening a range\n this.addActive(trackOpen);\n this.cursor.next();\n }\n else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) {\n // Ignore any non-empty points that end precisely at the end of the prev point\n this.cursor.next();\n }\n else { // New point\n this.point = nextVal;\n this.pointFrom = this.cursor.from;\n this.pointRank = this.cursor.rank;\n this.to = this.cursor.to;\n this.endSide = nextVal.endSide;\n this.cursor.next();\n this.forward(this.to, this.endSide);\n break;\n }\n }\n }\n if (trackOpen) {\n this.openStart = 0;\n for (let i = trackOpen.length - 1; i >= 0 && trackOpen[i] < from; i--)\n this.openStart++;\n }\n }\n activeForPoint(to) {\n if (!this.active.length)\n return this.active;\n let active = [];\n for (let i = this.active.length - 1; i >= 0; i--) {\n if (this.activeRank[i] < this.pointRank)\n break;\n if (this.activeTo[i] > to || this.activeTo[i] == to && this.active[i].endSide >= this.point.endSide)\n active.push(this.active[i]);\n }\n return active.reverse();\n }\n openEnd(to) {\n let open = 0;\n for (let i = this.activeTo.length - 1; i >= 0 && this.activeTo[i] > to; i--)\n open++;\n return open;\n }\n}\nfunction compare(a, startA, b, startB, length, comparator) {\n a.goto(startA);\n b.goto(startB);\n let endB = startB + length;\n let pos = startB, dPos = startB - startA;\n for (;;) {\n let diff = (a.to + dPos) - b.to || a.endSide - b.endSide;\n let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB);\n if (a.point || b.point) {\n if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) &&\n sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to))))\n comparator.comparePoint(pos, clipEnd, a.point, b.point);\n }\n else {\n if (clipEnd > pos && !sameValues(a.active, b.active))\n comparator.compareRange(pos, clipEnd, a.active, b.active);\n }\n if (end > endB)\n break;\n pos = end;\n if (diff <= 0)\n a.next();\n if (diff >= 0)\n b.next();\n }\n}\nfunction sameValues(a, b) {\n if (a.length != b.length)\n return false;\n for (let i = 0; i < a.length; i++)\n if (a[i] != b[i] && !a[i].eq(b[i]))\n return false;\n return true;\n}\nfunction remove(array, index) {\n for (let i = index, e = array.length - 1; i < e; i++)\n array[i] = array[i + 1];\n array.pop();\n}\nfunction insert(array, index, value) {\n for (let i = array.length - 1; i >= index; i--)\n array[i + 1] = array[i];\n array[index] = value;\n}\nfunction findMinIndex(value, array) {\n let found = -1, foundPos = 1000000000 /* C.Far */;\n for (let i = 0; i < array.length; i++)\n if ((array[i] - foundPos || value[i].endSide - value[found].endSide) < 0) {\n found = i;\n foundPos = array[i];\n }\n return found;\n}\n\n/**\nCount the column position at the given offset into the string,\ntaking extending characters and tab size into account.\n*/\nfunction countColumn(string, tabSize, to = string.length) {\n let n = 0;\n for (let i = 0; i < to;) {\n if (string.charCodeAt(i) == 9) {\n n += tabSize - (n % tabSize);\n i++;\n }\n else {\n n++;\n i = findClusterBreak(string, i);\n }\n }\n return n;\n}\n/**\nFind the offset that corresponds to the given column position in a\nstring, taking extending characters and tab size into account. By\ndefault, the string length is returned when it is too short to\nreach the column. Pass `strict` true to make it return -1 in that\nsituation.\n*/\nfunction findColumn(string, col, tabSize, strict) {\n for (let i = 0, n = 0;;) {\n if (n >= col)\n return i;\n if (i == string.length)\n break;\n n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;\n i = findClusterBreak(string, i);\n }\n return strict === true ? -1 : string.length;\n}\n\nconst C = \"\\u037c\";\nconst COUNT = typeof Symbol == \"undefined\" ? \"__\" + C : Symbol.for(C);\nconst SET = typeof Symbol == \"undefined\" ? \"__styleSet\" + Math.floor(Math.random() * 1e8) : Symbol(\"styleSet\");\nconst top = typeof globalThis != \"undefined\" ? globalThis : typeof window != \"undefined\" ? window : {};\n\n// :: - Style modules encapsulate a set of CSS rules defined from\n// JavaScript. Their definitions are only available in a given DOM\n// root after it has been _mounted_ there with `StyleModule.mount`.\n//\n// Style modules should be created once and stored somewhere, as\n// opposed to re-creating them every time you need them. The amount of\n// CSS rules generated for a given DOM root is bounded by the amount\n// of style modules that were used. So to avoid leaking rules, don't\n// create these dynamically, but treat them as one-time allocations.\nclass StyleModule {\n // :: (Object