pyret-embed 0.0.25 → 0.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
(definition=>{if("function"==typeof bootstrap)bootstrap("promise",definition);else if("object"==typeof exports&&"object"==typeof module)module.exports=definition();else if("function"==typeof define&&define.amd)define(definition);else if("undefined"!=typeof ses)ses.ok()&&(ses.makeQ=definition);else{if("undefined"==typeof window&&"undefined"==typeof self)throw new Error("This environment was not anticipated by Q. Please file a bug.");var global="undefined"!=typeof window?window:self,previousQ=global.Q;global.Q=definition(),global.Q.noConflict=function(){return global.Q=previousQ,this}}})(function(){var hasStacks=!1;try{throw new Error}catch(e){hasStacks=!!e.stack}function noop(){}var qFileName,nextTick,channel,requestPortTick,head,tail,flushing,requestTick,isNodeJS,laterQueue,qStartingLine=captureLine();tail=head={task:void 0,next:null},requestTick=void 0,isNodeJS=flushing=!1,laterQueue=[],nextTick=function(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null},flushing||(flushing=!0,requestTick())},requestTick="object"==typeof process&&"[object process]"===process.toString()&&process.nextTick?(isNodeJS=!0,function(){process.nextTick(flush)}):"function"==typeof setImmediate?"undefined"!=typeof window?setImmediate.bind(window,flush):function(){setImmediate(flush)}:"undefined"!=typeof MessageChannel?((channel=new MessageChannel).port1.onmessage=function(){requestTick=requestPortTick,(channel.port1.onmessage=flush)()},requestPortTick=function(){channel.port2.postMessage(0)},function(){setTimeout(flush,0),requestPortTick()}):function(){setTimeout(flush,0)},nextTick.runAfter=function(task){laterQueue.push(task),flushing||(flushing=!0,requestTick())};function flush(){for(var task,domain;head.next;)task=(head=head.next).task,head.task=void 0,(domain=head.domain)&&(head.domain=void 0,domain.enter()),runSingle(task,domain);for(;laterQueue.length;)runSingle(task=laterQueue.pop());flushing=!1}function runSingle(task,domain){try{task()}catch(e){if(isNodeJS)throw domain&&domain.exit(),setTimeout(flush,0),domain&&domain.enter(),e;setTimeout(function(){throw e},0)}domain&&domain.exit()}var call=Function.call;function uncurryThis(f){return function(){return call.apply(f,arguments)}}var array_slice=uncurryThis(Array.prototype.slice),array_reduce=uncurryThis(Array.prototype.reduce||function(callback,basis){var index=0,length=this.length;if(1===arguments.length)for(;;){if(index in this){basis=this[index++];break}if(++index>=length)throw new TypeError}for(;index<length;index++)index in this&&(basis=callback(basis,this[index],index));return basis}),array_indexOf=uncurryThis(Array.prototype.indexOf||function(value){for(var i=0;i<this.length;i++)if(this[i]===value)return i;return-1}),array_map=uncurryThis(Array.prototype.map||function(callback,thisp){var self=this,collect=[];return array_reduce(self,function(undefined,value,index){collect.push(callback.call(thisp,value,index,self))},void 0),collect}),object_create=Object.create||function(prototype){function Type(){}return Type.prototype=prototype,new Type},object_hasOwnProperty=uncurryThis(Object.prototype.hasOwnProperty),object_keys=Object.keys||function(object){var key,keys=[];for(key in object)object_hasOwnProperty(object,key)&&keys.push(key);return keys},object_toString=uncurryThis(Object.prototype.toString);var QReturnValue="undefined"!=typeof ReturnValue?ReturnValue:function(value){this.value=value},STACK_JUMP_SEPARATOR="From previous event:";function makeStackTraceLong(error,promise){if(hasStacks&&promise.stack&&"object"==typeof error&&null!==error&&error.stack&&-1===error.stack.indexOf(STACK_JUMP_SEPARATOR)){for(var stacks=[],p=promise;p;p=p.source)p.stack&&stacks.unshift(p.stack);stacks.unshift(error.stack);promise=stacks.join("\n"+STACK_JUMP_SEPARATOR+"\n");error.stack=(stackString=>{for(var lines=stackString.split("\n"),desiredLines=[],i=0;i<lines.length;++i){var line=lines[i];(stackLine=>{var fileName;return(stackLine=getFileNameAndLineNumber(stackLine))&&(fileName=stackLine[0],stackLine=stackLine[1],fileName===qFileName)&&qStartingLine<=stackLine&&stackLine<=qEndingLine})(line)||(stackLine=>-1!==stackLine.indexOf("(module.js:")||-1!==stackLine.indexOf("(node.js:"))(line)||!line||desiredLines.push(line)}return desiredLines.join("\n")})(promise)}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);return(attempt1=attempt1||/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine))?[attempt1[1],Number(attempt1[2])]:(attempt1=/.*@(.+):(\d+)$/.exec(stackLine))?[attempt1[1],Number(attempt1[2])]:void 0}function captureLine(){if(hasStacks)try{throw new Error}catch(e){var lines=e.stack.split("\n"),lines=getFileNameAndLineNumber(0<lines[0].indexOf("@")?lines[1]:lines[2]);if(lines)return qFileName=lines[0],lines[1]}}function Q(value){return value instanceof Promise?value:isPromiseAlike(value)?(promise=value,deferred=defer(),Q.nextTick(function(){try{promise.then(deferred.resolve,deferred.reject,deferred.notify)}catch(exception){deferred.reject(exception)}}),deferred.promise):fulfill(value);var promise,deferred}function defer(){var resolvedPromise,messages=[],progressListeners=[],deferred=object_create(defer.prototype),promise=object_create(Promise.prototype);if(promise.promiseDispatch=function(resolve,op,operands){var args=array_slice(arguments);messages?(messages.push(args),"when"===op&&operands[1]&&progressListeners.push(operands[1])):Q.nextTick(function(){resolvedPromise.promiseDispatch.apply(resolvedPromise,args)})},promise.valueOf=function(){var nearerValue;return messages?promise:(isPromise(nearerValue=nearer(resolvedPromise))&&(resolvedPromise=nearerValue),nearerValue)},promise.inspect=function(){return resolvedPromise?resolvedPromise.inspect():{state:"pending"}},Q.longStackSupport&&hasStacks)try{throw new Error}catch(e){promise.stack=e.stack.substring(e.stack.indexOf("\n")+1)}function become(newPromise){resolvedPromise=newPromise,promise.source=newPromise,array_reduce(messages,function(undefined,message){Q.nextTick(function(){newPromise.promiseDispatch.apply(newPromise,message)})},void 0),progressListeners=messages=void 0}return deferred.promise=promise,deferred.resolve=function(value){resolvedPromise||become(Q(value))},deferred.fulfill=function(value){resolvedPromise||become(fulfill(value))},deferred.reject=function(reason){resolvedPromise||become(reject(reason))},deferred.notify=function(progress){resolvedPromise||array_reduce(progressListeners,function(undefined,progressListener){Q.nextTick(function(){progressListener(progress)})},void 0)},deferred}function promise(resolver){if("function"!=typeof resolver)throw new TypeError("resolver must be a function.");var deferred=defer();try{resolver(deferred.resolve,deferred.reject,deferred.notify)}catch(reason){deferred.reject(reason)}return deferred.promise}function race(answerPs){return promise(function(resolve,reject){for(var i=0,len=answerPs.length;i<len;i++)Q(answerPs[i]).then(resolve,reject)})}function Promise(descriptor,fallback,inspect){void 0===fallback&&(fallback=function(op){return reject(new Error("Promise does not support operation: "+op))}),void 0===inspect&&(inspect=function(){return{state:"unknown"}});var inspected,promise=object_create(Promise.prototype);return promise.promiseDispatch=function(resolve,op,args){var result;try{result=descriptor[op]?descriptor[op].apply(promise,args):fallback.call(promise,op,args)}catch(exception){result=reject(exception)}resolve&&resolve(result)},(promise.inspect=inspect)&&("rejected"===(inspected=inspect()).state&&(promise.exception=inspected.reason),promise.valueOf=function(){var inspected=inspect();return"pending"===inspected.state||"rejected"===inspected.state?promise:inspected.value}),promise}function when(value,fulfilled,rejected,progressed){return Q(value).then(fulfilled,rejected,progressed)}function nearer(value){if(isPromise(value)){var inspected=value.inspect();if("fulfilled"===inspected.state)return inspected.value}return value}function isPromise(object){return object instanceof Promise}function isPromiseAlike(object){return object===Object(object)&&"function"==typeof object.then}(Q.resolve=Q).nextTick=nextTick,Q.longStackSupport=!1,"object"==typeof process&&process&&process.env&&process.env.Q_DEBUG&&(Q.longStackSupport=!0),(Q.defer=defer).prototype.makeNodeResolver=function(){var self=this;return function(error,value){error?self.reject(error):2<arguments.length?self.resolve(array_slice(arguments,1)):self.resolve(value)}},Q.Promise=promise,(Q.promise=promise).race=race,promise.all=all,promise.reject=reject,(promise.resolve=Q).passByCopy=function(object){return object},Promise.prototype.passByCopy=function(){return this},Q.join=function(x,y){return Q(x).join(y)},Promise.prototype.join=function(that){return Q([this,that]).spread(function(x,y){if(x===y)return x;throw new Error("Can't join: not the same: "+x+" "+y)})},Q.race=race,Promise.prototype.race=function(){return this.then(Q.race)},(Q.makePromise=Promise).prototype.toString=function(){return"[object Promise]"},Promise.prototype.then=function(fulfilled,rejected,progressed){var self=this,deferred=defer(),done=!1;return Q.nextTick(function(){self.promiseDispatch(function(value){done||(done=!0,deferred.resolve((value=>{try{return"function"==typeof fulfilled?fulfilled(value):value}catch(exception){return reject(exception)}})(value)))},"when",[function(exception){done||(done=!0,deferred.resolve((exception=>{if("function"==typeof rejected){makeStackTraceLong(exception,self);try{return rejected(exception)}catch(newException){return reject(newException)}}return reject(exception)})(exception)))}])}),self.promiseDispatch(void 0,"when",[void 0,function(value){var newValue,threw=!1;try{newValue=(value=>"function"==typeof progressed?progressed(value):value)(value)}catch(e){if(threw=!0,!Q.onerror)throw e;Q.onerror(e)}threw||deferred.notify(newValue)}]),deferred.promise},Q.tap=function(promise,callback){return Q(promise).tap(callback)},Promise.prototype.tap=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall(value).thenResolve(value)})},Q.when=when,Promise.prototype.thenResolve=function(value){return this.then(function(){return value})},Q.thenResolve=function(promise,value){return Q(promise).thenResolve(value)},Promise.prototype.thenReject=function(reason){return this.then(function(){throw reason})},Q.thenReject=function(promise,reason){return Q(promise).thenReject(reason)},Q.nearer=nearer,Q.isPromise=isPromise,Q.isPromiseAlike=isPromiseAlike,Q.isPending=function(object){return isPromise(object)&&"pending"===object.inspect().state},Promise.prototype.isPending=function(){return"pending"===this.inspect().state},Q.isFulfilled=function(object){return!isPromise(object)||"fulfilled"===object.inspect().state},Promise.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},Q.isRejected=function(object){return isPromise(object)&&"rejected"===object.inspect().state},Promise.prototype.isRejected=function(){return"rejected"===this.inspect().state};var callback,name,alternative,unhandledReasons=[],unhandledRejections=[],reportedUnhandledRejections=[],trackUnhandledRejections=!0;function resetUnhandledRejections(){unhandledReasons.length=0,unhandledRejections.length=0,trackUnhandledRejections=trackUnhandledRejections||!0}function reject(reason){var rejection=Promise({when:function(rejected){var promise,at;return rejected&&(promise=this,trackUnhandledRejections)&&-1!==(at=array_indexOf(unhandledRejections,promise))&&("object"==typeof process&&"function"==typeof process.emit&&Q.nextTick.runAfter(function(){var atReport=array_indexOf(reportedUnhandledRejections,promise);-1!==atReport&&(process.emit("rejectionHandled",unhandledReasons[at],promise),reportedUnhandledRejections.splice(atReport,1))}),unhandledRejections.splice(at,1),unhandledReasons.splice(at,1)),rejected?rejected(reason):this}},function(){return this},function(){return{state:"rejected",reason:reason}});return((promise,reason)=>{trackUnhandledRejections&&("object"==typeof process&&"function"==typeof process.emit&&Q.nextTick.runAfter(function(){-1!==array_indexOf(unhandledRejections,promise)&&(process.emit("unhandledRejection",reason,promise),reportedUnhandledRejections.push(promise))}),unhandledRejections.push(promise),reason&&void 0!==reason.stack?unhandledReasons.push(reason.stack):unhandledReasons.push("(no stack) "+reason))})(rejection,reason),rejection}function fulfill(value){return Promise({when:function(){return value},get:function(name){return value[name]},set:function(name,rhs){value[name]=rhs},delete:function(name){delete value[name]},post:function(name,args){return null==name?value.apply(void 0,args):value[name].apply(value,args)},apply:function(thisp,args){return value.apply(thisp,args)},keys:function(){return object_keys(value)}},void 0,function(){return{state:"fulfilled",value:value}})}function spread(value,fulfilled,rejected){return Q(value).spread(fulfilled,rejected)}function dispatch(object,op,args){return Q(object).dispatch(op,args)}function all(promises){return when(promises,function(promises){var pendingCount=0,deferred=defer();return array_reduce(promises,function(undefined,promise,index){var snapshot;isPromise(promise)&&"fulfilled"===(snapshot=promise.inspect()).state?promises[index]=snapshot.value:(++pendingCount,when(promise,function(value){promises[index]=value,0==--pendingCount&&deferred.resolve(promises)},deferred.reject,function(progress){deferred.notify({index:index,value:progress})}))},void 0),0===pendingCount&&deferred.resolve(promises),deferred.promise})}function any(promises){var deferred,pendingCount;return 0===promises.length?Q.resolve():(deferred=Q.defer(),array_reduce(promises,function(prev,current,index){var promise=promises[index];pendingCount++,when(promise,function(result){deferred.resolve(result)},function(){0==--pendingCount&&deferred.reject(new Error("Can't get fulfillment value from any promise, all promises were rejected."))},function(progress){deferred.notify({index:index,value:progress})})},void(pendingCount=0)),deferred.promise)}function allResolved(promises){return when(promises,function(promises){return promises=array_map(promises,Q),when(all(array_map(promises,function(promise){return when(promise,noop,noop)})),function(){return promises})})}Q.resetUnhandledRejections=resetUnhandledRejections,Q.getUnhandledReasons=function(){return unhandledReasons.slice()},Q.stopUnhandledRejectionTracking=function(){resetUnhandledRejections(),trackUnhandledRejections=!1},resetUnhandledRejections(),Q.reject=reject,Q.fulfill=fulfill,Q.master=function(object){return Promise({isDef:function(){}},function(op,args){return dispatch(object,op,args)},function(){return Q(object).inspect()})},Q.spread=spread,Promise.prototype.spread=function(fulfilled,rejected){return this.all().then(function(array){return fulfilled.apply(void 0,array)},rejected)},Q.async=function(makeGenerator){return function(){function continuer(verb,arg){var result;if("undefined"==typeof StopIteration){try{result=generator[verb](arg)}catch(exception){return reject(exception)}return result.done?Q(result.value):when(result.value,callback,errback)}try{result=generator[verb](arg)}catch(exception){return(exception=>"[object StopIteration]"===object_toString(exception)||exception instanceof QReturnValue)(exception)?Q(exception.value):reject(exception)}return when(result,callback,errback)}var generator=makeGenerator.apply(this,arguments),callback=continuer.bind(continuer,"next"),errback=continuer.bind(continuer,"throw");return callback()}},Q.spawn=function(makeGenerator){Q.done(Q.async(makeGenerator)())},Q.return=function(value){throw new QReturnValue(value)},Q.promised=function(callback){return function(){return spread([this,all(arguments)],function(self,args){return callback.apply(self,args)})}},Q.dispatch=dispatch,Promise.prototype.dispatch=function(op,args){var self=this,deferred=defer();return Q.nextTick(function(){self.promiseDispatch(deferred.resolve,op,args)}),deferred.promise},Q.get=function(object,key){return Q(object).dispatch("get",[key])},Promise.prototype.get=function(key){return this.dispatch("get",[key])},Q.set=function(object,key,value){return Q(object).dispatch("set",[key,value])},Promise.prototype.set=function(key,value){return this.dispatch("set",[key,value])},Q.del=Q.delete=function(object,key){return Q(object).dispatch("delete",[key])},Promise.prototype.del=Promise.prototype.delete=function(key){return this.dispatch("delete",[key])},Q.mapply=Q.post=function(object,name,args){return Q(object).dispatch("post",[name,args])},Promise.prototype.mapply=Promise.prototype.post=function(name,args){return this.dispatch("post",[name,args])},Q.send=Q.mcall=Q.invoke=function(object,name){return Q(object).dispatch("post",[name,array_slice(arguments,2)])},Promise.prototype.send=Promise.prototype.mcall=Promise.prototype.invoke=function(name){return this.dispatch("post",[name,array_slice(arguments,1)])},Q.fapply=function(object,args){return Q(object).dispatch("apply",[void 0,args])},Promise.prototype.fapply=function(args){return this.dispatch("apply",[void 0,args])},Q.try=Q.fcall=function(object){return Q(object).dispatch("apply",[void 0,array_slice(arguments,1)])},Promise.prototype.fcall=function(){return this.dispatch("apply",[void 0,array_slice(arguments)])},Q.fbind=function(object){var promise=Q(object),args=array_slice(arguments,1);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Promise.prototype.fbind=function(){var promise=this,args=array_slice(arguments);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Q.keys=function(object){return Q(object).dispatch("keys",[])},Promise.prototype.keys=function(){return this.dispatch("keys",[])},Q.all=all,Promise.prototype.all=function(){return all(this)},Q.any=any,Promise.prototype.any=function(){return any(this)},Q.allResolved=(callback=allResolved,name="allResolved",alternative="allSettled",function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(name+" is deprecated, use "+alternative+" instead.",new Error("").stack),callback.apply(callback,arguments)}),Promise.prototype.allResolved=function(){return allResolved(this)},Q.allSettled=function(promises){return Q(promises).allSettled()},Promise.prototype.allSettled=function(){return this.then(function(promises){return all(array_map(promises,function(promise){function regardless(){return promise.inspect()}return(promise=Q(promise)).then(regardless,regardless)}))})},Q.fail=Q.catch=function(object,rejected){return Q(object).then(void 0,rejected)},Promise.prototype.fail=Promise.prototype.catch=function(rejected){return this.then(void 0,rejected)},Q.progress=function(object,progressed){return Q(object).then(void 0,void 0,progressed)},Promise.prototype.progress=function(progressed){return this.then(void 0,void 0,progressed)},Q.fin=Q.finally=function(object,callback){return Q(object).finally(callback)},Promise.prototype.fin=Promise.prototype.finally=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall().then(function(){return value})},function(reason){return callback.fcall().then(function(){throw reason})})},Q.done=function(object,fulfilled,rejected,progress){return Q(object).done(fulfilled,rejected,progress)},Promise.prototype.done=function(fulfilled,rejected,progress){var onUnhandledError=function(error){Q.nextTick(function(){if(makeStackTraceLong(error,promise),!Q.onerror)throw error;Q.onerror(error)})},promise=fulfilled||rejected||progress?this.then(fulfilled,rejected,progress):this;"object"==typeof process&&process&&process.domain&&(onUnhandledError=process.domain.bind(onUnhandledError)),promise.then(void 0,onUnhandledError)},Q.timeout=function(object,ms,error){return Q(object).timeout(ms,error)},Promise.prototype.timeout=function(ms,error){var deferred=defer(),timeoutId=setTimeout(function(){error&&"string"!=typeof error||((error=new Error(error||"Timed out after "+ms+" ms")).code="ETIMEDOUT"),deferred.reject(error)},ms);return this.then(function(value){clearTimeout(timeoutId),deferred.resolve(value)},function(exception){clearTimeout(timeoutId),deferred.reject(exception)},deferred.notify),deferred.promise},Q.delay=function(object,timeout){return void 0===timeout&&(timeout=object,object=void 0),Q(object).delay(timeout)},Promise.prototype.delay=function(timeout){return this.then(function(value){var deferred=defer();return setTimeout(function(){deferred.resolve(value)},timeout),deferred.promise})},Q.nfapply=function(callback,args){return Q(callback).nfapply(args)},Promise.prototype.nfapply=function(args){var deferred=defer(),args=array_slice(args);return args.push(deferred.makeNodeResolver()),this.fapply(args).fail(deferred.reject),deferred.promise},Q.nfcall=function(callback){var args=array_slice(arguments,1);return Q(callback).nfapply(args)},Promise.prototype.nfcall=function(){var nodeArgs=array_slice(arguments),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfbind=Q.denodeify=function(callback){var baseArgs=array_slice(arguments,1);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(callback).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nfbind=Promise.prototype.denodeify=function(){var args=array_slice(arguments);return args.unshift(this),Q.denodeify.apply(void 0,args)},Q.nbind=function(callback,thisp){var baseArgs=array_slice(arguments,2);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(function(){return callback.apply(thisp,arguments)}).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nbind=function(){var args=array_slice(arguments,0);return args.unshift(this),Q.nbind.apply(void 0,args)},Q.nmapply=Q.npost=function(object,name,args){return Q(object).npost(name,args)},Promise.prototype.nmapply=Promise.prototype.npost=function(name,args){var args=array_slice(args||[]),deferred=defer();return args.push(deferred.makeNodeResolver()),this.dispatch("post",[name,args]).fail(deferred.reject),deferred.promise},Q.nsend=Q.nmcall=Q.ninvoke=function(object,name){var nodeArgs=array_slice(arguments,2),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(object).dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Promise.prototype.nsend=Promise.prototype.nmcall=Promise.prototype.ninvoke=function(name){var nodeArgs=array_slice(arguments,1),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nodeify=function(object,nodeback){return Q(object).nodeify(nodeback)},Promise.prototype.nodeify=function(nodeback){if(!nodeback)return this;this.then(function(value){Q.nextTick(function(){nodeback(null,value)})},function(error){Q.nextTick(function(){nodeback(error)})})},Q.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var qEndingLine=captureLine();return Q});var texts=["Raising the masts...","Securing the oarlocks...","Hoisting the anchor...","Swabbing the decks...","Debarnacling the keel...","Checking the cargo manifest...","Assembling the crew...","Inspecting the turnbuckles...","Furling the rollers...","Lashing the jib-boom...","Tying the rigging...","Reinforcing the hull...","Bailing the bilge...","Feeding the parrot...","Consulting the map...","Calibrating the compass...","Polishing the spyglass...","Latching the portholes..."],intervalID=($("#loader p").text(texts[Math.floor(Math.random()*texts.length)]),setInterval(function(){$("#loader p").text(texts[Math.floor(Math.random()*texts.length)])},1300)),ConsoleBackend=($("#loader").data("intervalID",intervalID),((global,factory)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global=global||self).CodeMirror=factory()})(this,function(){var userAgent=navigator.userAgent,platform=navigator.platform,gecko=/gecko\/\d/i.test(userAgent),ie_upto10=/MSIE \d/.test(userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent),edge=/Edge\/(\d+)/.exec(userAgent),ie=ie_upto10||ie_11up||edge,ie_version=ie&&(ie_upto10?document.documentMode||6:+(edge||ie_11up)[1]),webkit=!edge&&/WebKit\//.test(userAgent),ie_upto10=webkit&&/Qt\/\d+\.\d+/.test(userAgent),chrome=!edge&&/Chrome\//.test(userAgent),presto=/Opera\//.test(userAgent),safari=/Apple Computer/.test(navigator.vendor),mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent),phantom=/PhantomJS/.test(userAgent),ios=!edge&&/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent),android=/Android/.test(userAgent),mobile=ios||android||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent),mac=ios||/Mac/.test(platform),chromeOS=/\bCrOS\b/.test(userAgent),windows=/win/i.test(platform),ie_11up=presto&&userAgent.match(/Version\/(\d*\.\d*)/),flipCtrlCmd=((ie_11up=ie_11up&&Number(ie_11up[1]))&&15<=ie_11up&&(webkit=!(presto=!1)),mac&&(ie_upto10||presto&&(null==ie_11up||ie_11up<12.11))),captureRightClick=gecko||ie&&9<=ie_version;function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}var rmClass=function(node,cls){var after,current=node.className,cls=classTest(cls).exec(current);cls&&(after=current.slice(cls.index+cls[0].length),node.className=current.slice(0,cls.index)+(after?cls[1]+after:""))};function removeChildren(e){for(var count=e.childNodes.length;0<count;--count)e.removeChild(e.firstChild);return e}function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}function elt(tag,content,className,style){var e=document.createElement(tag);if(className&&(e.className=className),style&&(e.style.cssText=style),"string"==typeof content)e.appendChild(document.createTextNode(content));else if(content)for(var i=0;i<content.length;++i)e.appendChild(content[i]);return e}function eltP(tag,content,className,style){tag=elt(tag,content,className,style);return tag.setAttribute("role","presentation"),tag}function contains(parent,child){if(3==child.nodeType&&(child=child.parentNode),parent.contains)return parent.contains(child);do{if((child=11==child.nodeType?child.host:child)==parent)return!0}while(child=child.parentNode)}function activeElt(){var activeElement;try{activeElement=document.activeElement}catch(e){activeElement=document.body||null}for(;activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement;)activeElement=activeElement.shadowRoot.activeElement;return activeElement}function addClass(node,cls){var current=node.className;classTest(cls).test(current)||(node.className+=(current?" ":"")+cls)}function joinClasses(a,b){for(var as=a.split(" "),i=0;i<as.length;i++)as[i]&&!classTest(as[i]).test(b)&&(b+=" "+as[i]);return b}var range=document.createRange?function(node,start,end,endNode){var r=document.createRange();return r.setEnd(endNode||node,end),r.setStart(node,start),r}:function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",end),r.moveStart("character",start),r},selectInput=function(node){node.select()};function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}function copyObj(obj,target,overwrite){for(var prop in target=target||{},obj)!obj.hasOwnProperty(prop)||!1===overwrite&&target.hasOwnProperty(prop)||(target[prop]=obj[prop]);return target}function countColumn(string,end,tabSize,startIndex,startValue){null==end&&-1==(end=string.search(/[^\s\u00a0]/))&&(end=string.length);for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i);if(nextTab<0||end<=nextTab)return n+(end-i);n=(n+=nextTab-i)+(tabSize-n%tabSize),i=nextTab+1}}ios?selectInput=function(node){node.selectionStart=0,node.selectionEnd=node.value.length}:ie&&(selectInput=function(node){try{node.select()}catch(_e){}});function Delayed(){this.id=null,this.f=null,this.time=0,this.handler=bind(this.onTimeout,this)}function indexOf(array,elt){for(var i=0;i<array.length;++i)if(array[i]==elt)return i;return-1}Delayed.prototype.onTimeout=function(self){self.id=0,self.time<=+new Date?self.f():setTimeout(self.handler,self.time-+new Date)};var scrollerGap=50,Pass={toString:function(){return"CodeMirror.Pass"}},sel_dontScroll={scroll:!(Delayed.prototype.set=function(ms,f){this.f=f;f=+new Date+ms;(!this.id||f<this.time)&&(clearTimeout(this.id),this.id=setTimeout(this.handler,ms),this.time=f)})},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"};function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos),skipped=(nextTab=-1==nextTab?string.length:nextTab)-pos;if(nextTab==string.length||goal<=col+skipped)return pos+Math.min(skipped,goal-col);if(col+=nextTab-pos,pos=nextTab+1,goal<=(col+=tabSize-col%tabSize))return pos}}var spaceStrs=[""];function spaceStr(n){for(;spaceStrs.length<=n;)spaceStrs.push(lst(spaceStrs)+" ");return spaceStrs[n]}function lst(arr){return arr[arr.length-1]}function map(array,f){for(var out=[],i=0;i<array.length;i++)out[i]=f(array[i],i);return out}function nothing(){}function createObj(base,props){base=Object.create?Object.create(base):(nothing.prototype=base,new nothing);return props&©Obj(props,base),base}var nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;function isWordCharBasic(ch){return/\w/.test(ch)||""<ch&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))}function isWordChar(ch,helper){return helper?!!(-1<helper.source.indexOf("\\w")&&isWordCharBasic(ch))||helper.test(ch):isWordCharBasic(ch)}function isEmpty(obj){for(var n in obj)if(obj.hasOwnProperty(n)&&obj[n])return;return 1}var extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function isExtendingChar(ch){return 768<=ch.charCodeAt(0)&&extendingChars.test(ch)}function skipExtendingChars(str,pos,dir){for(;(dir<0?0<pos:pos<str.length)&&isExtendingChar(str.charAt(pos));)pos+=dir;return pos}function findFirst(pred,from,to){for(var dir=to<from?-1:1;;){if(from==to)return from;var midF=(from+to)/2,midF=dir<0?Math.ceil(midF):Math.floor(midF);if(midF==from)return pred(midF)?from:to;pred(midF)?to=midF:from=midF+dir}}var bidiOther=null;function getBidiPartAt(order,ch,sticky){var found;bidiOther=null;for(var i=0;i<order.length;++i){var cur=order[i];if(cur.from<ch&&cur.to>ch)return i;cur.to==ch&&(cur.from!=cur.to&&"before"==sticky?found=i:bidiOther=i),cur.from==ch&&(cur.from!=cur.to&&"before"!=sticky?found=i:bidiOther=i)}return null!=found?found:bidiOther}bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/;var bidiRE,isNeutral,isStrong,countsAsLeft,countsAsNum,bidiOrdering=function(str,direction){var outerType="ltr"==direction?"L":"R";if(0==str.length||"ltr"==direction&&!bidiRE.test(str))return!1;for(var code,len=str.length,types=[],i=0;i<len;++i)types.push((code=str.charCodeAt(i))<=247?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(code):1424<=code&&code<=1524?"R":1536<=code&&code<=1785?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(code-1536):1774<=code&&code<=2220?"r":8192<=code&&code<=8203?"w":8204==code?"b":"L");for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1];"m"==type?types[i$1]=prev:prev=type}for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2];"1"==type$1&&"r"==cur?types[i$2]="n":isStrong.test(type$1)&&"r"==(cur=type$1)&&(types[i$2]="R")}for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3];"+"==type$2&&"1"==prev$1&&"1"==types[i$3+1]?types[i$3]="1":","!=type$2||prev$1!=types[i$3+1]||"1"!=prev$1&&"n"!=prev$1||(types[i$3]=prev$1),prev$1=type$2}for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4];if(","==type$3)types[i$4]="N";else if("%"==type$3){for(var end=void 0,end=i$4+1;end<len&&"%"==types[end];++end);for(var replace=i$4&&"!"==types[i$4-1]||end<len&&"1"==types[end]?"1":"N",j=i$4;j<end;++j)types[j]=replace;i$4=end-1}}for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5];"L"==cur$1&&"1"==type$4?types[i$5]="L":isStrong.test(type$4)&&(cur$1=type$4)}for(var i$6=0;i$6<len;++i$6)if(isNeutral.test(types[i$6])){for(var end$1=void 0,end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1);for(var before="L"==(i$6?types[i$6-1]:outerType),replace$1=before==("L"==(end$1<len?types[end$1]:outerType))?before?"L":"R":outerType,j$1=i$6;j$1<end$1;++j$1)types[j$1]=replace$1;i$6=end$1-1}for(var m,order=[],i$7=0;i$7<len;)if(countsAsLeft.test(types[i$7])){var start=i$7;for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7);order.push(new BidiSpan(0,start,i$7))}else{var pos=i$7,at=order.length,isRTL="rtl"==direction?1:0;for(++i$7;i$7<len&&"L"!=types[i$7];++i$7);for(var j$2=pos;j$2<i$7;)if(countsAsNum.test(types[j$2])){pos<j$2&&(order.splice(at,0,new BidiSpan(1,pos,j$2)),at+=isRTL);var nstart=j$2;for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2);order.splice(at,0,new BidiSpan(2,nstart,j$2)),at+=isRTL,pos=j$2}else++j$2;pos<i$7&&order.splice(at,0,new BidiSpan(1,pos,i$7))}return"ltr"==direction&&(1==order[0].level&&(m=str.match(/^\s+/))&&(order[0].from=m[0].length,order.unshift(new BidiSpan(0,0,m[0].length))),1==lst(order).level)&&(m=str.match(/\s+$/))&&(lst(order).to-=m[0].length,order.push(new BidiSpan(0,len-m[0].length,len))),"rtl"==direction?order.reverse():order};function BidiSpan(level,from,to){this.level=level,this.from=from,this.to=to}function getOrder(line,direction){var order=line.order;return order=null==order?line.order=bidiOrdering(line.text,direction):order}var noHandlers=[],on=function(emitter,type,f){emitter.addEventListener?emitter.addEventListener(type,f,!1):emitter.attachEvent?emitter.attachEvent("on"+type,f):(emitter=emitter._handlers||(emitter._handlers={}))[type]=(emitter[type]||noHandlers).concat(f)};function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers}function off(emitter,type,f){var arr;emitter.removeEventListener?emitter.removeEventListener(type,f,!1):emitter.detachEvent?emitter.detachEvent("on"+type,f):(arr=(emitter=emitter._handlers)&&emitter[type])&&-1<(f=indexOf(arr,f))&&(emitter[type]=arr.slice(0,f).concat(arr.slice(f+1)))}function signal(emitter,type){var handlers=getHandlers(emitter,type);if(handlers.length)for(var args=Array.prototype.slice.call(arguments,2),i=0;i<handlers.length;++i)handlers[i].apply(null,args)}function signalDOMEvent(cm,e,override){return"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}}),signal(cm,override||e.type,cm,e),e_defaultPrevented(e)||e.codemirrorIgnore}function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(arr)for(var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]),i=0;i<arr.length;++i)-1==indexOf(set,arr[i])&&set.push(arr[i])}function hasHandler(emitter,type){return 0<getHandlers(emitter,type).length}function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)},ctor.prototype.off=function(type,f){off(this,type,f)}}function e_preventDefault(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function e_stopPropagation(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function e_defaultPrevented(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function e_stop(e){e_preventDefault(e),e_stopPropagation(e)}function e_target(e){return e.target||e.srcElement}function e_button(e){var b=e.which;return null==b&&(1&e.button?b=1:2&e.button?b=3:4&e.button&&(b=2)),b=mac&&e.ctrlKey&&1==b?3:b}var zwspSupported,badBidiRects,dragAndDrop=!(ie&&ie_version<9)&&("draggable"in(edge=elt("div"))||"dragDrop"in edge);var splitLinesAuto=3!="\n\nb".split(/\n/).length?function(string){for(var pos=0,result=[],l=string.length;pos<=l;){var nl=string.indexOf("\n",pos),line=(-1==nl&&(nl=string.length),string.slice(pos,"\r"==string.charAt(nl-1)?nl-1:nl)),rt=line.indexOf("\r");-1!=rt?(result.push(line.slice(0,rt)),pos+=rt+1):(result.push(line),pos=nl+1)}return result}:function(string){return string.split(/\r\n?|\n/)},hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}catch(e){return!1}}:function(te){var range;try{range=te.ownerDocument.selection.createRange()}catch(e){}return!(!range||range.parentElement()!=te)&&0!=range.compareEndPoints("StartToEnd",range)},hasCopyEvent="oncopy"in(platform=elt("div"))||(platform.setAttribute("oncopy","return;"),"function"==typeof platform.oncopy),badZoomedRects=null;var modes={},mimeModes={};function resolveMode(spec){if("string"==typeof spec&&mimeModes.hasOwnProperty(spec))spec=mimeModes[spec];else if(spec&&"string"==typeof spec.name&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];(spec=createObj(found="string"==typeof found?{name:found}:found,spec)).name=found.name}else{if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec))return resolveMode("application/xml");if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec))return resolveMode("application/json")}return"string"==typeof spec?{name:spec}:spec||{name:"null"}}function getMode(options,spec){spec=resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)return getMode(options,"text/plain");var modeObj=mfactory(options,spec);if(modeExtensions.hasOwnProperty(spec.name)){var prop,exts=modeExtensions[spec.name];for(prop in exts)exts.hasOwnProperty(prop)&&(modeObj.hasOwnProperty(prop)&&(modeObj["_"+prop]=modeObj[prop]),modeObj[prop]=exts[prop])}if(modeObj.name=spec.name,spec.helperType&&(modeObj.helperType=spec.helperType),spec.modeProps)for(var prop$1 in spec.modeProps)modeObj[prop$1]=spec.modeProps[prop$1];return modeObj}var modeExtensions={};function extendMode(mode,properties){copyObj(properties,modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:modeExtensions[mode]={})}function copyState(mode,state){if(!0===state)return state;if(mode.copyState)return mode.copyState(state);var n,nstate={};for(n in state){var val=state[n];val instanceof Array&&(val=val.concat([])),nstate[n]=val}return nstate}function innerMode(mode,state){for(var info;mode.innerMode&&(info=mode.innerMode(state))&&info.mode!=mode;)state=info.state,mode=info.mode;return info||{mode:mode,state:state}}function startState(mode,a1,a2){return!mode.startState||mode.startState(a1,a2)}var StringStream=function(string,tabSize,lineOracle){this.pos=this.start=0,this.string=string,this.tabSize=tabSize||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=lineOracle};function getLine(doc,n){if((n-=doc.first)<0||n>=doc.size)throw new Error("There is no line "+(n+doc.first)+" in the document.");for(var chunk=doc;!chunk.lines;)for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(n<sz){chunk=child;break}n-=sz}return chunk.lines[n]}function getBetween(doc,start,end){var out=[],n=start.line;return doc.iter(start.line,end.line+1,function(line){line=line.text;n==end.line&&(line=line.slice(0,end.ch)),n==start.line&&(line=line.slice(start.ch)),out.push(line),++n}),out}function getLines(doc,from,to){var out=[];return doc.iter(from,to,function(line){out.push(line.text)}),out}function updateLineHeight(line,height){var diff=height-line.height;if(diff)for(var n=line;n;n=n.parent)n.height+=diff}function lineNo(line){if(null==line.parent)return null;for(var cur=line.parent,no=indexOf(cur.lines,line),chunk=cur.parent;chunk;chunk=(cur=chunk).parent)for(var i=0;chunk.children[i]!=cur;++i)no+=chunk.children[i].chunkSize();return no+cur.first}function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height;if(h<ch){chunk=child;continue outer}h-=ch,n+=child.chunkSize()}return n}while(!chunk.lines);for(var i=0;i<chunk.lines.length;++i){var lh=chunk.lines[i].height;if(h<lh)break;h-=lh}return n+i}function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}function Pos(line,ch,sticky){if(void 0===sticky&&(sticky=null),!(this instanceof Pos))return new Pos(line,ch,sticky);this.line=line,this.ch=ch,this.sticky=sticky}function cmp(a,b){return a.line-b.line||a.ch-b.ch}function equalCursorPos(a,b){return a.sticky==b.sticky&&0==cmp(a,b)}function copyPos(x){return Pos(x.line,x.ch)}function maxPos(a,b){return cmp(a,b)<0?b:a}function minPos(a,b){return cmp(a,b)<0?a:b}function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}function clipPos(doc,pos){var last;return pos.line<doc.first?Pos(doc.first,0):(last=doc.first+doc.size-1)<pos.line?Pos(last,getLine(doc,last).text.length):((pos,linelen)=>{var ch=pos.ch;return null==ch||linelen<ch?Pos(pos.line,linelen):ch<0?Pos(pos.line,0):pos})(pos,getLine(doc,pos.line).text.length)}function clipPosArray(doc,array){for(var out=[],i=0;i<array.length;i++)out[i]=clipPos(doc,array[i]);return out}StringStream.prototype.eol=function(){return this.pos>=this.string.length},StringStream.prototype.sol=function(){return this.pos==this.lineStart},StringStream.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},StringStream.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},StringStream.prototype.eat=function(match){var ch=this.string.charAt(this.pos),match="string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch));if(match)return++this.pos,ch},StringStream.prototype.eatWhile=function(match){for(var start=this.pos;this.eat(match););return this.pos>start},StringStream.prototype.eatSpace=function(){for(var start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>start},StringStream.prototype.skipToEnd=function(){this.pos=this.string.length},StringStream.prototype.skipTo=function(ch){ch=this.string.indexOf(ch,this.pos);if(-1<ch)return this.pos=ch,!0},StringStream.prototype.backUp=function(n){this.pos-=n},StringStream.prototype.column=function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.indentation=function(){return countColumn(this.string,null,this.tabSize)-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.match=function(pattern,consume,caseInsensitive){var match;return"string"!=typeof pattern?(match=this.string.slice(this.pos).match(pattern))&&0<match.index?null:(match&&!1!==consume&&(this.pos+=match[0].length),match):(match=function(str){return caseInsensitive?str.toLowerCase():str})(this.string.substr(this.pos,pattern.length))==match(pattern)?(!1!==consume&&(this.pos+=pattern.length),!0):void 0},StringStream.prototype.current=function(){return this.string.slice(this.start,this.pos)},StringStream.prototype.hideFirstChars=function(n,inner){this.lineStart+=n;try{return inner()}finally{this.lineStart-=n}},StringStream.prototype.lookAhead=function(n){var oracle=this.lineOracle;return oracle&&oracle.lookAhead(n)},StringStream.prototype.baseToken=function(){var oracle=this.lineOracle;return oracle&&oracle.baseToken(this.pos)};var SavedContext=function(state,lookAhead){this.state=state,this.lookAhead=lookAhead},Context=function(doc,state,line,lookAhead){this.state=state,this.doc=doc,this.line=line,this.maxLookAhead=lookAhead||0,this.baseTokens=null,this.baseTokenPos=1};function highlightLine(cm,line,context,forceToEnd){for(var st=[cm.state.modeGen],lineClasses={},state=(runMode(cm,line.text,cm.doc.mode,context,function(end,style){st.push(end,style)},lineClasses,forceToEnd),context.state),o=0;o<cm.state.overlays.length;++o)(o=>{context.baseTokens=st;var overlay=cm.state.overlays[o],i=1,at=0;context.state=!0,runMode(cm,line.text,overlay.mode,context,function(end,style){for(var start=i;at<end;){var i_end=st[i];end<i_end&&st.splice(i,1,end,st[i+1],i_end),i+=2,at=Math.min(end,i_end)}if(style)if(overlay.opaque)st.splice(start,i-start,end,"overlay "+style),i=start+2;else for(;start<i;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"overlay "+style}},lineClasses),context.state=state,context.baseTokens=null,context.baseTokenPos=1})(o);return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}function getLineStyles(cm,line,updateFrontier){var context,resetState,result;return line.styles&&line.styles[0]==cm.state.modeGen||(context=getContextBefore(cm,lineNo(line)),resetState=line.text.length>cm.options.maxHighlightLength&©State(cm.doc.mode,context.state),result=highlightLine(cm,line,context),resetState&&(context.state=resetState),line.stateAfter=context.save(!resetState),line.styles=result.styles,result.classes?line.styleClasses=result.classes:line.styleClasses&&(line.styleClasses=null),updateFrontier===cm.doc.highlightFrontier&&(cm.doc.modeFrontier=Math.max(cm.doc.modeFrontier,++cm.doc.highlightFrontier))),line.styles}function getContextBefore(cm,n,precise){var start,saved,context,doc=cm.doc,display=cm.display;return doc.mode.startState?(start=((cm,n,precise)=>{for(var minindent,minline,doc=cm.doc,lim=precise?-1:n-(cm.doc.mode.innerMode?1e3:100),search=n;lim<search;--search){if(search<=doc.first)return doc.first;var line=getLine(doc,search-1),after=line.stateAfter;if(after&&(!precise||search+(after instanceof SavedContext?after.lookAhead:0)<=doc.modeFrontier))return search;after=countColumn(line.text,null,cm.options.tabSize);(null==minline||after<minindent)&&(minline=search-1,minindent=after)}return minline})(cm,n,precise),saved=doc.first<start&&getLine(doc,start-1).stateAfter,context=saved?Context.fromSaved(doc,saved,start):new Context(doc,startState(doc.mode),start),doc.iter(start,n,function(line){processLine(cm,line.text,context);var pos=context.line;line.stateAfter=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo?context.save():null,context.nextLine()}),precise&&(doc.modeFrontier=context.line),context):new Context(doc,!0,n)}function processLine(cm,text,context,startAt){var mode=cm.doc.mode,stream=new StringStream(text,cm.options.tabSize,context);for(stream.start=stream.pos=startAt||0,""==text&&callBlankLine(mode,context.state);!stream.eol();)readToken(mode,stream,context.state),stream.start=stream.pos}function callBlankLine(mode,state){return mode.blankLine?mode.blankLine(state):mode.innerMode&&(mode=innerMode(mode,state)).mode.blankLine?mode.mode.blankLine(mode.state):void 0}function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){inner&&(inner[0]=innerMode(mode,state).mode);var style=mode.token(stream,state);if(stream.pos>stream.start)return style}throw new Error("Mode "+mode.name+" failed to advance stream.")}Context.prototype.lookAhead=function(n){var line=this.doc.getLine(this.line+n);return null!=line&&n>this.maxLookAhead&&(this.maxLookAhead=n),line},Context.prototype.baseToken=function(n){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=n;)this.baseTokenPos+=2;var type=this.baseTokens[this.baseTokenPos+1];return{type:type&&type.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-n}},Context.prototype.nextLine=function(){this.line++,0<this.maxLookAhead&&this.maxLookAhead--},Context.fromSaved=function(doc,saved,line){return saved instanceof SavedContext?new Context(doc,copyState(doc.mode,saved.state),line,saved.lookAhead):new Context(doc,copyState(doc.mode,saved),line)},Context.prototype.save=function(copy){copy=!1!==copy?copyState(this.doc.mode,this.state):this.state;return 0<this.maxLookAhead?new SavedContext(copy,this.maxLookAhead):copy};var Token=function(stream,type,state){this.start=stream.start,this.end=stream.pos,this.string=stream.current(),this.type=type||null,this.state=state};function takeToken(cm,pos,precise,asArray){var style,tokens,doc=cm.doc,mode=doc.mode,line=getLine(doc,(pos=clipPos(doc,pos)).line),context=getContextBefore(cm,pos.line,precise),stream=new StringStream(line.text,cm.options.tabSize,context);for(asArray&&(tokens=[]);(asArray||stream.pos<pos.ch)&&!stream.eol();)stream.start=stream.pos,style=readToken(mode,stream,context.state),asArray&&tokens.push(new Token(stream,style,copyState(doc.mode,context.state)));return asArray?tokens:new Token(stream,style,context.state)}function extractLineClasses(type,output){if(type)for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass)break;type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";null==output[prop]?output[prop]=lineClass[2]:new RegExp("(?:^|\\s)"+lineClass[2]+"(?:$|\\s)").test(output[prop])||(output[prop]+=" "+lineClass[2])}return type}function runMode(cm,text,mode,context,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans,curStart=(null==flattenSpans&&(flattenSpans=cm.options.flattenSpans),0),curStyle=null,stream=new StringStream(text,cm.options.tabSize,context),inner=cm.options.addModeClass&&[null];for(""==text&&extractLineClasses(callBlankLine(mode,context.state),lineClasses);!stream.eol();){var mName,style=stream.pos>cm.options.maxHighlightLength?(flattenSpans=!1,forceToEnd&&processLine(cm,text,context,stream.pos),stream.pos=text.length,null):extractLineClasses(readToken(mode,stream,context.state,inner),lineClasses);if(inner&&(mName=inner[0].name)&&(style="m-"+(style?mName+" "+style:mName)),!flattenSpans||curStyle!=style){for(;curStart<stream.start;)f(curStart=Math.min(stream.start,curStart+5e3),curStyle);curStyle=style}stream.start=stream.pos}for(;curStart<stream.pos;){var pos=Math.min(stream.pos,curStart+5e3);f(pos,curStyle),curStart=pos}}var sawReadOnlySpans=!1,sawCollapsedSpans=!1;function MarkedSpan(marker,from,to){this.marker=marker,this.from=from,this.to=to}function getMarkedSpanFor(spans,marker){if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker)return span}}function stretchSpansOverChange(doc,change){if(change.full)return null;var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans,doc=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!doc)return null;var startCh=change.from.ch,endCh=change.to.ch,isInsert=0==cmp(change.from,change.to),first=((old,startCh,isInsert)=>{var nw;if(old)for(var i=0;i<old.length;++i){var endsAfter,span=old[i],marker=span.marker;!(null==span.from||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh))&&(span.from!=startCh||"bookmark"!=marker.type||isInsert&&span.marker.insertLeft)||(endsAfter=null==span.to||(marker.inclusiveRight?span.to>=startCh:span.to>startCh),(nw=nw||[]).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to)))}return nw})(oldFirst,startCh,isInsert),last=((old,endCh,isInsert)=>{var nw;if(old)for(var i=0;i<old.length;++i){var startsBefore,span=old[i],marker=span.marker;!(null==span.to||(marker.inclusiveRight?span.to>=endCh:span.to>endCh))&&(span.from!=endCh||"bookmark"!=marker.type||isInsert&&!span.marker.insertLeft)||(startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh),(nw=nw||[]).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,null==span.to?null:span.to-endCh)))}return nw})(doc,endCh,isInsert),sameLine=1==change.text.length,offset=lst(change.text).length+(sameLine?startCh:0);if(first)for(var i=0;i<first.length;++i){var found,span=first[i];null==span.to&&((found=getMarkedSpanFor(last,span.marker))?sameLine&&(span.to=null==found.to?null:found.to+offset):span.to=startCh)}if(last)for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1];null!=span$1.to&&(span$1.to+=offset),null==span$1.from?getMarkedSpanFor(first,span$1.marker)||(span$1.from=offset,sameLine&&(first=first||[]).push(span$1)):(span$1.from+=offset,sameLine&&(first=first||[]).push(span$1))}first=first&&clearEmptySpans(first),last&&last!=first&&(last=clearEmptySpans(last));var newMarkers=[first];if(!sameLine){var gapMarkers,gap=change.text.length-2;if(0<gap&&first)for(var i$2=0;i$2<first.length;++i$2)null==first[i$2].to&&(gapMarkers=gapMarkers||[]).push(new MarkedSpan(first[i$2].marker,null,null));for(var i$3=0;i$3<gap;++i$3)newMarkers.push(gapMarkers);newMarkers.push(last)}return newMarkers}function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];null!=span.from&&span.from==span.to&&!1!==span.marker.clearWhenEmpty&&spans.splice(i--,1)}return spans.length?spans:null}function detachMarkedSpans(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.detachLine(line);line.markedSpans=null}}function attachMarkedSpans(line,spans){if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.attachLine(line);line.markedSpans=spans}}function extraLeft(marker){return marker.inclusiveLeft?-1:0}function extraRight(marker){return marker.inclusiveRight?1:0}function compareCollapsedMarkers(a,b){var bPos,fromCmp,lenDiff=a.lines.length-b.lines.length;return 0!=lenDiff?lenDiff:(lenDiff=a.find(),bPos=b.find(),(fromCmp=cmp(lenDiff.from,bPos.from)||extraLeft(a)-extraLeft(b))?-fromCmp:cmp(lenDiff.to,bPos.to)||extraRight(a)-extraRight(b)||b.id-a.id)}function collapsedSpanAtSide(line,start){var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i)(sp=sps[i]).marker.collapsed&&null==(start?sp.from:sp.to)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker);return found}function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,!0)}function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,!1)}function conflictingCollapsedRange(doc,lineNo,from,to,marker){var doc=getLine(doc,lineNo),sps=sawCollapsedSpans&&doc.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed){var found=sp.marker.find(0),fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker),toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(!(0<=fromCmp&&toCmp<=0||fromCmp<=0&&0<=toCmp)&&(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?0<=cmp(found.to,from):0<cmp(found.to,from))||0<=fromCmp&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0)))return 1}}}function visualLine(line){for(var merged;merged=collapsedSpanAtStart(line);)line=merged.find(-1,!0).line;return line}function visualLineNo(doc,lineN){var doc=getLine(doc,lineN),vis=visualLine(doc);return doc==vis?lineN:lineNo(vis)}function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine())return lineN;var merged,line=getLine(doc,lineN);if(!lineIsHidden(doc,line))return lineN;for(;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return lineNo(line)+1}function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i)if((sp=sps[i]).marker.collapsed){if(null==sp.from)return!0;if(!sp.marker.widgetNode&&0==sp.from&&sp.marker.inclusiveLeft&&function lineIsHiddenInner(doc,line,span){{var end;if(null==span.to)return end=span.marker.find(1,!0),lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}if(span.marker.inclusiveRight&&span.to==line.text.length)return!0;for(var sp=void 0,i=0;i<line.markedSpans.length;++i)if((sp=line.markedSpans[i]).marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(null==sp.to||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp))return!0}(doc,line,sp))return!0}}function heightAtLine(lineObj){for(var h=0,chunk=(lineObj=visualLine(lineObj)).parent,i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj)break;h+=line.height}for(var p=chunk.parent;p;p=(chunk=p).parent)for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1];if(cur==chunk)break;h+=cur.height}return h}function lineLength(line){if(0==line.height)return 0;for(var merged,len=line.text.length,cur=line;merged=collapsedSpanAtStart(cur);){var found=merged.find(0,!0),cur=found.from.line;len+=found.from.ch-found.to.ch}for(cur=line;merged=collapsedSpanAtEnd(cur);)var found$1=merged.find(0,!0),len=(len-=cur.text.length-found$1.from.ch)+((cur=found$1.to.line).text.length-found$1.to.ch);return len}function findMaxLine(cm){var d=cm.display,cm=cm.doc;d.maxLine=getLine(cm,cm.first),d.maxLineLength=lineLength(d.maxLine),d.maxLineChanged=!0,cm.iter(function(line){var len=lineLength(line);len>d.maxLineLength&&(d.maxLineLength=len,d.maxLine=line)})}var Line=function(text,markedSpans,estimateHeight){this.text=text,attachMarkedSpans(this,markedSpans),this.height=estimateHeight?estimateHeight(this):1};Line.prototype.lineNo=function(){return lineNo(this)},eventMixin(Line);var styleToClassCache={},styleToClassCacheWithMode={};function interpretTokenStyle(style,options){return!style||/^\s*$/.test(style)?null:(options=options.addModeClass?styleToClassCacheWithMode:styleToClassCache)[style]||(options[style]=style.replace(/\S+/g,"cm-$&"))}function buildLineContent(cm,lineView){var content=eltP("span",null,null,webkit?"padding-right: .1px":null),builder={pre:eltP("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:!1,splitSpaces:cm.getOption("lineWrapping")};lineView.measure={};for(var r0,txt,i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=void 0,measure=(builder.pos=0,builder.addToken=buildToken,measure=cm.display.measure,txt=r0=void 0,(null!=badBidiRects?badBidiRects:(txt=removeChildrenAndAdd(measure,document.createTextNode("AخA")),r0=range(txt,0,1).getBoundingClientRect(),txt=range(txt,1,2).getBoundingClientRect(),removeChildren(measure),r0&&r0.left!=r0.right&&(badBidiRects=txt.right-r0.right<3)))&&(order=getOrder(line,cm.doc.direction))&&(builder.addToken=((inner,order)=>function(builder,text,style,startStyle,endStyle,css,attributes){style=style?style+" cm-force-border":"cm-force-border";for(var start=builder.pos,end=start+text.length;;){for(var part=void 0,i=0;i<order.length&&!((part=order[i]).to>start&&part.from<=start);i++);if(part.to>=end)return inner(builder,text,style,startStyle,endStyle,css,attributes);inner(builder,text.slice(0,part.to-start),style,startStyle,null,css,attributes),startStyle=null,text=text.slice(part.to-start),start=part.to}})(builder.addToken,order)),builder.map=[],lineView!=cm.display.externalMeasured&&lineNo(line));((line,builder,styles)=>{var spans=line.markedSpans,allText=line.text,at=0;if(spans)for(var style,css,spanStyle,spanEndStyle,spanStartStyle,collapsed,attributes,len=allText.length,pos=0,i=1,text="",nextChange=0;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=css="",collapsed=attributes=null,nextChange=1/0;for(var foundBookmarks=[],endStyles=void 0,j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;if("bookmark"==m.type&&sp.from==pos&&m.widgetNode)foundBookmarks.push(m);else if(sp.from<=pos&&(null==sp.to||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(null!=sp.to&&sp.to!=pos&&nextChange>sp.to&&(nextChange=sp.to,spanEndStyle=""),m.className&&(spanStyle+=" "+m.className),m.css&&(css=(css?css+";":"")+m.css),m.startStyle&&sp.from==pos&&(spanStartStyle+=" "+m.startStyle),m.endStyle&&sp.to==nextChange&&(endStyles=endStyles||[]).push(m.endStyle,sp.to),m.title&&((attributes=attributes||{}).title=m.title),m.attributes)for(var attr in m.attributes)(attributes=attributes||{})[attr]=m.attributes[attr];m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)&&(collapsed=sp)}else sp.from>pos&&nextChange>sp.from&&(nextChange=sp.from)}if(endStyles)for(var j$1=0;j$1<endStyles.length;j$1+=2)endStyles[j$1+1]==nextChange&&(spanEndStyle+=" "+endStyles[j$1]);if(!collapsed||collapsed.from==pos)for(var j$2=0;j$2<foundBookmarks.length;++j$2)buildCollapsedSpan(builder,0,foundBookmarks[j$2]);if(collapsed&&(collapsed.from||0)==pos){if(buildCollapsedSpan(builder,(null==collapsed.to?len+1:collapsed.to)-pos,collapsed.marker,null==collapsed.from),null==collapsed.to)return;collapsed.to==pos&&(collapsed=!1)}}if(len<=pos)break;for(var upto=Math.min(len,nextChange);;){if(text){var tokenText,end=pos+text.length;if(collapsed||(tokenText=upto<end?text.slice(0,upto-pos):text,builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",css,attributes)),upto<=end){text=text.slice(upto-pos),pos=upto;break}pos=end,spanStartStyle=""}text=allText.slice(at,at=styles[i++]),style=interpretTokenStyle(styles[i++],builder.cm.options)}}else for(var i$1=1;i$1<styles.length;i$1+=2)builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options))})(line,builder,getLineStyles(cm,line,measure)),line.styleClasses&&(line.styleClasses.bgClass&&(builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||"")),line.styleClasses.textClass)&&(builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||"")),0==builder.map.length&&builder.map.push(0,0,builder.content.appendChild((measure=>{var test;return(measure=(zwspSupported=null==zwspSupported&&(test=elt("span",""),removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")])),0!=measure.firstChild.offsetHeight)?test.offsetWidth<=1&&2<test.offsetHeight&&!(ie&&ie_version<8):zwspSupported)?elt("span",""):elt("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")).setAttribute("cm-text",""),measure})(cm.display.measure))),0==i?(lineView.measure.map=builder.map,lineView.measure.cache={}):((lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map),(lineView.measure.caches||(lineView.measure.caches=[])).push({}))}return webkit&&(content=builder.content.lastChild,/\bcm-tab\b/.test(content.className)||content.querySelector&&content.querySelector(".cm-tab"))&&(builder.content.className="cm-tab-wrap-hack"),signal(cm,"renderLine",cm,lineView.line,builder.pre),builder.pre.className&&(builder.textClass=joinClasses(builder.pre.className,builder.textClass||"")),builder}function defaultSpecialCharPlaceholder(ch){var token=elt("span","•","cm-invalidchar");return token.title="\\u"+ch.charCodeAt(0).toString(16),token.setAttribute("aria-label",token.title),token}function buildToken(builder,text,style,startStyle,endStyle,css,attributes){if(text){var displayText=builder.splitSpaces?((text,trailingBefore)=>{if(1<text.length&&!/ /.test(text))return text;for(var spaceBefore=trailingBefore,result="",i=0;i<text.length;i++){var ch=text.charAt(i);" "!=ch||!spaceBefore||i!=text.length-1&&32!=text.charCodeAt(i+1)||(ch=" "),result+=ch,spaceBefore=" "==ch}return result})(text,builder.trailingSpace):text,special=builder.cm.state.specialChars,mustWrap=!1;if(special.test(text))for(var content=document.createDocumentFragment(),pos=0;;){special.lastIndex=pos;var m=special.exec(text),skipped=m?m.index-pos:text.length-pos;if(skipped&&(txt=document.createTextNode(displayText.slice(pos,pos+skipped)),ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt),builder.map.push(builder.pos,builder.pos+skipped,txt),builder.col+=skipped,builder.pos+=skipped),!m)break;pos+=1+skipped;var txt=void 0;"\t"==m[0]?(skipped=builder.cm.options.tabSize,(txt=content.appendChild(elt("span",spaceStr(skipped=skipped-builder.col%skipped),"cm-tab"))).setAttribute("role","presentation"),txt.setAttribute("cm-text","\t"),builder.col+=skipped):("\r"==m[0]||"\n"==m[0]?(txt=content.appendChild(elt("span","\r"==m[0]?"␍":"","cm-invalidchar"))).setAttribute("cm-text",m[0]):((txt=builder.cm.options.specialCharPlaceholder(m[0])).setAttribute("cm-text",m[0]),ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt)),builder.col+=1),builder.map.push(builder.pos,builder.pos+1,txt),builder.pos++}else builder.col+=text.length,content=document.createTextNode(displayText),builder.map.push(builder.pos,builder.pos+text.length,content),ie&&ie_version<9&&(mustWrap=!0),builder.pos+=text.length;if(builder.trailingSpace=32==displayText.charCodeAt(text.length-1),style||startStyle||endStyle||mustWrap||css||attributes){var mustWrap=style||"",token=(startStyle&&(mustWrap+=startStyle),endStyle&&(mustWrap+=endStyle),elt("span",[content],mustWrap,css));if(attributes)for(var attr in attributes)attributes.hasOwnProperty(attr)&&"style"!=attr&&"class"!=attr&&token.setAttribute(attr,attributes[attr]);return builder.content.appendChild(token)}builder.content.appendChild(content)}}function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;widget&&builder.map.push(builder.pos,builder.pos+size,widget),!ignoreWidget&&builder.cm.display.input.needsContentAttribute&&(widget=widget||builder.content.appendChild(document.createElement("span"))).setAttribute("cm-marker",marker.id),widget&&(builder.cm.display.input.setUneditable(widget),builder.content.appendChild(widget)),builder.pos+=size,builder.trailingSpace=!1}function LineView(doc,line,lineN){this.line=line,this.rest=(line=>{for(var merged,lines;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line,(lines=lines||[]).push(line);return lines})(line),this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1,this.node=this.text=null,this.hidden=lineIsHidden(doc,line)}function buildViewArray(cm,from,to){for(var array=[],pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos),nextPos=pos+view.size;array.push(view)}return array}var operationGroup=null;function finishOperation(op,endCb){op=op.ownsGroup;if(op)try{(group=>{var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)callbacks[i].call(null);for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)for(;op.cursorActivityCalled<op.cursorActivityHandlers.length;)op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}while(i<callbacks.length)})(op)}finally{operationGroup=null,endCb(op)}}var orphanDelayedCallbacks=null;function signalLater(emitter,type){var arr=getHandlers(emitter,type);if(arr.length)for(var list,args=Array.prototype.slice.call(arguments,2),i=(operationGroup?list=operationGroup.delayedCallbacks:orphanDelayedCallbacks?list=orphanDelayedCallbacks:(list=orphanDelayedCallbacks=[],setTimeout(fireOrphanDelayed,0)),0);i<arr.length;++i)(i=>{list.push(function(){return arr[i].apply(null,args)})})(i)}function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i)delayed[i]()}function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];"text"==type?((cm,lineView)=>{var cls=lineView.text.className,built=getLineContent(cm,lineView);lineView.text==lineView.node&&(lineView.node=built.pre),lineView.text.parentNode.replaceChild(built.pre,lineView.text),lineView.text=built.pre,built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass?(lineView.bgClass=built.bgClass,lineView.textClass=built.textClass,updateLineClasses(cm,lineView)):cls&&(lineView.text.className=cls)})(cm,lineView):"gutter"==type?updateLineGutter(cm,lineView,lineN,dims):"class"==type?updateLineClasses(cm,lineView):"widget"==type&&((cm,lineView,dims)=>{lineView.alignable&&(lineView.alignable=null);for(var isWidget=classTest("CodeMirror-linewidget"),node=lineView.node.firstChild,next=void 0;node;node=next)next=node.nextSibling,isWidget.test(node.className)&&lineView.node.removeChild(node);insertLineWidgets(cm,lineView,dims)})(cm,lineView,dims)}lineView.changes=null}function ensureLineWrapped(lineView){return lineView.node==lineView.text&&(lineView.node=elt("div",null,null,"position: relative"),lineView.text.parentNode&&lineView.text.parentNode.replaceChild(lineView.node,lineView.text),lineView.node.appendChild(lineView.text),ie)&&ie_version<8&&(lineView.node.style.zIndex=2),lineView.node}function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;return ext&&ext.line==lineView.line?(cm.display.externalMeasured=null,lineView.measure=ext.measure,ext.built):buildLineContent(cm,lineView)}function updateLineClasses(cm,lineView){((cm,lineView)=>{var wrap,cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;cls&&(cls+=" CodeMirror-linebackground"),lineView.background?cls?lineView.background.className=cls:(lineView.background.parentNode.removeChild(lineView.background),lineView.background=null):cls&&(wrap=ensureLineWrapped(lineView),lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild),cm.display.input.setUneditable(lineView.background))})(cm,lineView),lineView.line.wrapClass?ensureLineWrapped(lineView).className=lineView.line.wrapClass:lineView.node!=lineView.text&&(lineView.node.className="");cm=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=cm||""}function updateLineGutter(cm,lineView,lineN,dims){lineView.gutter&&(lineView.node.removeChild(lineView.gutter),lineView.gutter=null),lineView.gutterBackground&&(lineView.node.removeChild(lineView.gutterBackground),lineView.gutterBackground=null),lineView.line.gutterClass&&(wrap=ensureLineWrapped(lineView),lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,"left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+dims.gutterTotalWidth+"px"),cm.display.input.setUneditable(lineView.gutterBackground),wrap.insertBefore(lineView.gutterBackground,lineView.text));var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap=ensureLineWrapped(lineView),gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper","left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px");if(cm.display.input.setUneditable(gutterWrap),wrap.insertBefore(gutterWrap,lineView.text),lineView.line.gutterClass&&(gutterWrap.className+=" "+lineView.line.gutterClass),!cm.options.lineNumbers||markers&&markers["CodeMirror-linenumbers"]||(lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+dims.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+cm.display.lineNumInnerWidth+"px"))),markers)for(var k=0;k<cm.display.gutterSpecs.length;++k){var id=cm.display.gutterSpecs[k].className,found=markers.hasOwnProperty(id)&&markers[id];found&&gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt","left: "+dims.gutterLeft[id]+"px; width: "+dims.gutterWidth[id]+"px"))}}}function insertLineWidgets(cm,lineView,dims){if(insertLineWidgetsFor(cm,lineView.line,lineView,dims,!0),lineView.rest)for(var i=0;i<lineView.rest.length;i++)insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,!1)}function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(line.widgets)for(var wrap=ensureLineWrapped(lineView),i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget"+(widget.className?" "+widget.className:""));widget.handleMouseEvents||node.setAttribute("cm-ignore-events","true"),((widget,node,lineView,dims)=>{widget.noHScroll&&((lineView.alignable||(lineView.alignable=[])).push(node),lineView=dims.wrapperWidth,node.style.left=dims.fixedPos+"px",widget.coverGutter||(lineView-=dims.gutterTotalWidth,node.style.paddingLeft=dims.gutterTotalWidth+"px"),node.style.width=lineView+"px"),widget.coverGutter&&(node.style.zIndex=5,node.style.position="relative",widget.noHScroll||(node.style.marginLeft=-dims.gutterTotalWidth+"px"))})(widget,node,lineView,dims),cm.display.input.setUneditable(node),allowAbove&&widget.above?wrap.insertBefore(node,lineView.gutter||lineView.text):wrap.appendChild(node),signalLater(widget,"redraw")}}function widgetHeight(widget){var cm,parentStyle;return null!=widget.height?widget.height:(cm=widget.doc.cm)?(contains(document.body,widget.node)||(parentStyle="position: relative;",widget.coverGutter&&(parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;"),widget.noHScroll&&(parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;"),removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))),widget.height=widget.node.parentNode.offsetHeight):0}function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==display.sizer&&n!=display.mover)return 1}function paddingTop(display){return display.lineSpace.offsetTop}function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}function paddingH(display){var e;return display.cachedPaddingH||(e=removeChildrenAndAdd(display.measure,elt("pre","x","CodeMirror-line-like")),e=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,e={left:parseInt(e.paddingLeft),right:parseInt(e.paddingRight)},isNaN(e.left)||isNaN(e.right)||(display.cachedPaddingH=e),e)}function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}function mapFromLineView(lineView,line,lineN){if(lineView.line==line)return{map:lineView.measure.map,cache:lineView.measure.cache};for(var i=0;i<lineView.rest.length;i++)if(lineView.rest[i]==line)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]};for(var i$1=0;i$1<lineView.rest.length;i$1++)if(lineNo(lineView.rest[i$1])>lineN)return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:!0}}function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}function findViewForLine(cm,lineN){return lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo?cm.display.view[findViewIndex(cm,lineN)]:(cm=cm.display.externalMeasured)&&lineN>=cm.lineN&&lineN<cm.lineN+cm.size?cm:void 0}function prepareMeasureForLine(cm,line){var lineN=lineNo(line),view=findViewForLine(cm,lineN),cm=(view&&!view.text?view=null:view&&view.changes&&(updateLineForChanges(cm,view,lineN,getDimensions(cm)),cm.curOp.forceUpdate=!0),mapFromLineView(view=view||((cm,line)=>{var lineN=lineNo(line=visualLine(line)),lineN=((line=cm.display.externalMeasured=new LineView(cm.doc,line,lineN)).lineN=lineN,line.built=buildLineContent(cm,line));return line.text=lineN.pre,removeChildrenAndAdd(cm.display.lineMeasure,lineN.pre),line})(cm,line),line,lineN));return{line:line,view:view,rect:null,map:cm.map,cache:cm.cache,before:cm.before,hasHeights:!1}}function measureCharPrepared(cm,prepared,ch,bias,varHeight){var found,key=(ch=prepared.before?-1:ch)+(bias||"");return prepared.cache.hasOwnProperty(key)?found=prepared.cache[key]:(prepared.rect||(prepared.rect=prepared.view.text.getBoundingClientRect()),prepared.hasHeights||(((cm,lineView,rect)=>{var wrapping=cm.options.lineWrapping,cm=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=cm){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=cm;for(var rects=lineView.text.firstChild.getClientRects(),i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];2<Math.abs(cur.bottom-next.bottom)&&heights.push((cur.bottom+next.top)/2-rect.top)}}heights.push(rect.bottom-rect.top)}})(cm,prepared.view,prepared.rect),prepared.hasHeights=!0),(found=((cm,prepared,ch,bias)=>{var rect,place=nodeAndOffsetInLineMap(prepared.map,ch,bias),node=place.node,start=place.start,end=place.end,collapse=place.collapse;if(3==node.nodeType){for(var i$1=0;i$1<4;i$1++){for(;start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start));)--start;for(;place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end));)++end;if((rect=ie&&ie_version<9&&0==start&&end==place.coverEnd-place.coverStart?node.parentNode.getBoundingClientRect():((rects,bias)=>{var rect=nullRect;if("left"==bias)for(var i=0;i<rects.length&&(rect=rects[i]).left==rect.right;i++);else for(var i$1=rects.length-1;0<=i$1&&(rect=rects[i$1]).left==rect.right;i$1--);return rect})(range(node,start,end).getClientRects(),bias)).left||rect.right||0==start)break;end=start,start-=1,collapse="right"}ie&&ie_version<11&&(rect=((measure,rect)=>{var scaleY;return window.screen&&null!=screen.logicalXDPI&&screen.logicalXDPI!=screen.deviceXDPI&&(measure=>{var normal;return null!=badZoomedRects?badZoomedRects:(normal=(measure=removeChildrenAndAdd(measure,elt("span","x"))).getBoundingClientRect(),measure=range(measure,0,1).getBoundingClientRect(),badZoomedRects=1<Math.abs(normal.left-measure.left))})(measure)?(measure=screen.logicalXDPI/screen.deviceXDPI,scaleY=screen.logicalYDPI/screen.deviceYDPI,{left:rect.left*measure,right:rect.right*measure,top:rect.top*scaleY,bottom:rect.bottom*scaleY}):rect})(cm.display.measure,rect))}else 0<start&&(collapse=bias="right"),rect=cm.options.lineWrapping&&1<(ch=node.getClientRects()).length?ch["right"==bias?ch.length-1:0]:node.getBoundingClientRect();!(ie&&ie_version<9)||start||rect&&(rect.left||rect.right)||(ch=node.parentNode.getClientRects()[0],rect=ch?{left:ch.left,right:ch.left+charWidth(cm.display),top:ch.top,bottom:ch.bottom}:nullRect);for(var ch=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top,mid=(ch+rbot)/2,heights=prepared.view.measure.heights,i=0;i<heights.length-1&&!(mid<heights[i]);i++);var top=i?heights[i-1]:0,bot=heights[i],top={left:("right"==collapse?rect.right:rect.left)-prepared.rect.left,right:("left"==collapse?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};return rect.left||rect.right||(top.bogus=!0),cm.options.singleCursorHeightPerLine||(top.rtop=ch,top.rbottom=rbot),top})(cm,prepared,ch,bias)).bogus||(prepared.cache[key]=found)),{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}var measureText,nullRect={left:0,right:0,top:0,bottom:0};function nodeAndOffsetInLineMap(map,ch,bias){for(var node,start,end,collapse,mStart,mEnd,i=0;i<map.length;i+=3)if(mEnd=map[i+1],ch<(mStart=map[i])?(start=0,end=1,collapse="left"):ch<mEnd?end=(start=ch-mStart)+1:(i==map.length-3||ch==mEnd&&map[i+3]>ch)&&(start=(end=mEnd-mStart)-1,mEnd<=ch)&&(collapse="right"),null!=start){if(node=map[i+2],mStart==mEnd&&bias==(node.insertLeft?"left":"right")&&(collapse=bias),"left"==bias&&0==start)for(;i&&map[i-2]==map[i-3]&&map[i-1].insertLeft;)node=map[2+(i-=3)],collapse="left";if("right"==bias&&start==mEnd-mStart)for(;i<map.length-3&&map[i+3]==map[i+4]&&!map[i+5].insertLeft;)node=map[(i+=3)+2],collapse="right";break}return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}function clearLineMeasurementCacheFor(lineView){if(lineView.measure&&(lineView.measure.cache={},lineView.measure.heights=null,lineView.rest))for(var i=0;i<lineView.rest.length;i++)lineView.measure.caches[i]={}}function clearLineMeasurementCache(cm){cm.display.externalMeasure=null,removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)clearLineMeasurementCacheFor(cm.display.view[i])}function clearCaches(cm){clearLineMeasurementCache(cm),cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null,cm.options.lineWrapping||(cm.display.maxLineChanged=!0),cm.display.lineNumChars=null}function pageScrollX(){return chrome&&android?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function pageScrollY(){return chrome&&android?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):window.pageYOffset||(document.documentElement||document.body).scrollTop}function widgetTopHeight(lineObj){var height=0;if(lineObj.widgets)for(var i=0;i<lineObj.widgets.length;++i)lineObj.widgets[i].above&&(height+=widgetHeight(lineObj.widgets[i]));return height}function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){return includeWidgets||(includeWidgets=widgetTopHeight(lineObj),rect.top+=includeWidgets,rect.bottom+=includeWidgets),"line"!=context&&(context=context||"local",includeWidgets=heightAtLine(lineObj),"local"==context?includeWidgets+=paddingTop(cm.display):includeWidgets-=cm.display.viewOffset,"page"!=context&&"window"!=context||(includeWidgets+=(lineObj=cm.display.lineSpace.getBoundingClientRect()).top+("window"==context?0:pageScrollY()),cm=lineObj.left+("window"==context?0:pageScrollX()),rect.left+=cm,rect.right+=cm),rect.top+=includeWidgets,rect.bottom+=includeWidgets),rect}function fromCoordSystem(cm,coords,context){var left;return"div"==context?coords:(left=coords.left,coords=coords.top,"page"==context?(left-=pageScrollX(),coords-=pageScrollY()):"local"!=context&&context||(left+=(context=cm.display.sizer.getBoundingClientRect()).left,coords+=context.top),{left:left-(context=cm.display.lineSpace.getBoundingClientRect()).left,top:coords-context.top})}function charCoords(cm,pos,context,lineObj,bias){return intoCoordSystem(cm,lineObj=lineObj||getLine(cm.doc,pos.line),measureChar(cm,lineObj,pos.ch,bias),context)}function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){function get(ch,right){ch=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);return right?ch.left=ch.right:ch.right=ch.left,intoCoordSystem(cm,lineObj,ch,context)}lineObj=lineObj||getLine(cm.doc,pos.line),preparedMeasure=preparedMeasure||prepareMeasureForLine(cm,lineObj);var other,partPos,order=getOrder(lineObj,cm.doc.direction),ch=pos.ch,pos=pos.sticky;return ch>=lineObj.text.length?(ch=lineObj.text.length,pos="before"):ch<=0&&(ch=0,pos="after"),order?(partPos=getBidiPartAt(order,ch,pos),other=bidiOther,partPos=getBidi(ch,partPos,"before"==pos),null!=other&&(partPos.other=getBidi(ch,other,"before"!=pos)),partPos):get("before"==pos?ch-1:ch,"before"==pos);function getBidi(ch,partPos,invert){return get(invert?ch-1:ch,1==order[partPos].level!=invert)}}function estimateCoords(cm,pos){var left=0,pos=(pos=clipPos(cm.doc,pos),cm.options.lineWrapping||(left=charWidth(cm.display)*pos.ch),getLine(cm.doc,pos.line)),cm=heightAtLine(pos)+paddingTop(cm.display);return{left:left,right:left,top:cm,bottom:cm+pos.height}}function PosWithInfo(line,ch,sticky,outside,xRel){line=Pos(line,ch,sticky);return line.xRel=xRel,outside&&(line.outside=outside),line}function coordsChar(cm,x,y){var doc=cm.doc;if((y+=cm.display.viewOffset)<0)return PosWithInfo(doc.first,0,null,-1,-1);var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(last<lineN)return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,null,1,1);x<0&&(x=0);for(var lineObj=getLine(doc,lineN);;){var found=((cm,lineObj,lineNo,x,y)=>{y-=heightAtLine(lineObj);var atLeft,atStart,preparedMeasure=prepareMeasureForLine(cm,lineObj),widgetHeight=widgetTopHeight(lineObj),begin=0,end=lineObj.text.length,ltr=!0,chAround=((order=getOrder(lineObj,cm.doc.direction))&&(ltr=1!=(order=(cm.options.lineWrapping?function(cm,lineObj,_lineNo,preparedMeasure,order,x,y){var y=wrappedLineExtent(cm,lineObj,preparedMeasure,y),begin=y.begin,end=y.end;/\s/.test(lineObj.text.charAt(end-1))&&end--;for(var part=null,closestDist=null,i=0;i<order.length;i++){var endX,p=order[i];p.from>=end||p.to<=begin||(endX=measureCharPrepared(cm,preparedMeasure,1!=p.level?Math.min(end,p.to)-1:Math.max(begin,p.from)).right,endX=endX<x?x-endX+1e9:endX-x,(!part||endX<closestDist)&&(part=p,closestDist=endX))}part=part||order[order.length-1];part.from<begin&&(part={from:begin,to:part.to,level:part.level});part.to>end&&(part={from:part.from,to:end,level:part.level});return part}:function(cm,lineObj,lineNo,preparedMeasure,order,x,y){var index=findFirst(function(i){var i=order[i],ltr=1!=i.level;return boxIsAfter(cursorCoords(cm,Pos(lineNo,ltr?i.to:i.from,ltr?"before":"after"),"line",lineObj,preparedMeasure),x,y,!0)},0,order.length-1),part=order[index];{var ltr;0<index&&(ltr=1!=part.level,boxIsAfter(ltr=cursorCoords(cm,Pos(lineNo,ltr?part.from:part.to,ltr?"after":"before"),"line",lineObj,preparedMeasure),x,y,!0))&<r.top>y&&(part=order[index-1])}return part})(cm,lineObj,lineNo,preparedMeasure,order,x,y)).level,begin=ltr?order.from:order.to-1,end=ltr?order.to:order.from-1),null),boxAround=null,order=findFirst(function(ch){var box=measureCharPrepared(cm,preparedMeasure,ch);return box.top+=widgetHeight,box.bottom+=widgetHeight,boxIsAfter(box,x,y,!1)&&(box.top<=y&&box.left<=x&&(chAround=ch,boxAround=box),1)},begin,end),outside=!1;return boxAround?(atLeft=x-boxAround.left<boxAround.right-x,order=chAround+((atStart=atLeft==ltr)?0:1),atStart=atStart?"after":"before",atLeft=atLeft?boxAround.left:boxAround.right):(ltr||order!=end&&order!=begin||order++,atStart=0==order||order!=lineObj.text.length&&measureCharPrepared(cm,preparedMeasure,order-(ltr?1:0)).bottom+widgetHeight<=y==ltr?"after":"before",end=cursorCoords(cm,Pos(lineNo,order,atStart),"line",lineObj,preparedMeasure),atLeft=end.left,outside=y<end.top?-1:y>=end.bottom?1:0),order=skipExtendingChars(lineObj.text,order,1),PosWithInfo(lineNo,order,atStart,outside,x-atLeft)})(cm,lineObj,lineN,x,y),collapsed=((line,ch)=>{var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];sp.marker.collapsed&&(null==sp.from||sp.from<ch)&&(null==sp.to||sp.to>ch)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker)}return found})(lineObj,found.ch+(0<found.xRel||0<found.outside?1:0));if(!collapsed)return found;found=collapsed.find(1);if(found.line==lineN)return found;lineObj=getLine(doc,lineN=found.line)}}function wrappedLineExtent(cm,lineObj,preparedMeasure,y){y-=widgetTopHeight(lineObj);var lineObj=lineObj.text.length,begin=findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch-1).bottom<=y},lineObj,0);return{begin:begin,end:findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch).top>y},begin,lineObj)}}function wrappedLineExtentChar(cm,lineObj,preparedMeasure,target){return wrappedLineExtent(cm,lineObj,preparedMeasure=preparedMeasure||prepareMeasureForLine(cm,lineObj),intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,target),"line").top)}function boxIsAfter(box,x,y,left){return!(box.bottom<=y)&&(box.top>y||(left?box.left:box.right)>x)}function textHeight(display){if(null!=display.cachedTextHeight)return display.cachedTextHeight;if(null==measureText){measureText=elt("pre",null,"CodeMirror-line-like");for(var i=0;i<49;++i)measureText.appendChild(document.createTextNode("x")),measureText.appendChild(elt("br"));measureText.appendChild(document.createTextNode("x"))}removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;return 3<height&&(display.cachedTextHeight=height),removeChildren(display.measure),height||1}function charWidth(display){var pre,anchor;return null!=display.cachedCharWidth?display.cachedCharWidth:(anchor=elt("span","xxxxxxxxxx"),pre=elt("pre",[anchor],"CodeMirror-line-like"),removeChildrenAndAdd(display.measure,pre),2<(anchor=((pre=anchor.getBoundingClientRect()).right-pre.left)/10)&&(display.cachedCharWidth=anchor),anchor||10)}function getDimensions(cm){for(var d=cm.display,left={},width={},gutterLeft=d.gutters.clientLeft,n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){var id=cm.display.gutterSpecs[i].className;left[id]=n.offsetLeft+n.clientLeft+gutterLeft,width[id]=n.clientWidth}return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping,perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line))return 0;var widgetsHeight=0;if(line.widgets)for(var i=0;i<line.widgets.length;i++)line.widgets[i].height&&(widgetsHeight+=line.widgets[i].height);return wrapping?widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th:widgetsHeight+th}}function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);estHeight!=line.height&&updateLineHeight(line,estHeight)})}function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&"true"==e_target(e).getAttribute("cm-not-content"))return null;var x,y,liberal=display.lineSpace.getBoundingClientRect();try{x=e.clientX-liberal.left,y=e.clientY-liberal.top}catch(e$1){return null}display=coordsChar(cm,x,y);return forRect&&0<display.xRel&&(e=getLine(cm.doc,display.line).text).length==display.ch&&(liberal=countColumn(e,e.length,cm.options.tabSize)-e.length,display=Pos(display.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-liberal))),display}function findViewIndex(cm,n){if(n>=cm.display.viewTo)return null;if((n-=cm.display.viewFrom)<0)return null;for(var view=cm.display.view,i=0;i<view.length;i++)if((n-=view[i].size)<0)return i}function regChange(cm,from,to,lendiff){null==from&&(from=cm.doc.first),null==to&&(to=cm.doc.first+cm.doc.size);var cutBot,display=cm.display,cut=((lendiff=lendiff||0)&&to<display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>from)&&(display.updateLineNumbers=from),cm.curOp.viewChanged=!0,from>=display.viewTo?sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo&&resetView(cm):to<=display.viewFrom?sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom?resetView(cm):(display.viewFrom+=lendiff,display.viewTo+=lendiff):from<=display.viewFrom&&to>=display.viewTo?resetView(cm):from<=display.viewFrom?(cut=viewCuttingPoint(cm,to,to+lendiff,1))?(display.view=display.view.slice(cut.index),display.viewFrom=cut.lineN,display.viewTo+=lendiff):resetView(cm):to>=display.viewTo?(cut=viewCuttingPoint(cm,from,from,-1))?(display.view=display.view.slice(0,cut.index),display.viewTo=cut.lineN):resetView(cm):(cut=viewCuttingPoint(cm,from,from,-1),cutBot=viewCuttingPoint(cm,to,to+lendiff,1),cut&&cutBot?(display.view=display.view.slice(0,cut.index).concat(buildViewArray(cm,cut.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index)),display.viewTo+=lendiff):resetView(cm)),display.externalMeasured);cut&&(to<cut.lineN?cut.lineN+=lendiff:from<cut.lineN+cut.size&&(display.externalMeasured=null))}function regLineChange(cm,line,type){cm.curOp.viewChanged=!0;var display=cm.display,ext=cm.display.externalMeasured;ext&&line>=ext.lineN&&line<ext.lineN+ext.size&&(display.externalMeasured=null),line<display.viewFrom||line>=display.viewTo||null!=(ext=display.view[findViewIndex(cm,line)]).node&&-1==indexOf(display=ext.changes||(ext.changes=[]),type)&&display.push(type)}function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first,cm.display.view=[],cm.display.viewOffset=0}function viewCuttingPoint(cm,oldN,newN,dir){var diff,index=findViewIndex(cm,oldN),view=cm.display.view;if(sawCollapsedSpans&&newN!=cm.doc.first+cm.doc.size){for(var n=cm.display.viewFrom,i=0;i<index;i++)n+=view[i].size;if(n!=oldN){if(0<dir){if(index==view.length-1)return null;diff=n+view[index].size-oldN,index++}else diff=n-oldN;oldN+=diff,newN+=diff}for(;visualLineNo(cm.doc,newN)!=newN;){if(index==(dir<0?0:view.length-1))return null;newN+=dir*view[index-(dir<0?1:0)].size,index+=dir}}return{index:index,lineN:newN}}function countDirtyView(cm){for(var view=cm.display.view,dirty=0,i=0;i<view.length;i++){var lineView=view[i];lineView.hidden||lineView.node&&!lineView.changes||++dirty}return dirty}function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())}function prepareSelection(cm,primary){void 0===primary&&(primary=!0);for(var range,collapsed,doc=cm.doc,result={},curFragment=result.cursors=document.createDocumentFragment(),selFragment=result.selection=document.createDocumentFragment(),i=0;i<doc.sel.ranges.length;i++)!primary&&i==doc.sel.primIndex||(range=doc.sel.ranges[i]).from().line>=cm.display.viewTo||range.to().line<cm.display.viewFrom||(((collapsed=range.empty())||cm.options.showCursorWhenSelecting)&&drawSelectionCursor(cm,range.head,curFragment),collapsed)||((cm,range,output)=>{var toLine,display=cm.display,doc=cm.doc,fragment=document.createDocumentFragment(),padding=paddingH(cm.display),leftSide=padding.left,rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right,docLTR="ltr"==doc.direction;function add(left,top,width,bottom){top<0&&(top=0),top=Math.round(top),bottom=Math.round(bottom),fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(null==width?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"))}function drawForLine(line,fromArg,toArg){var start,end,lineObj=getLine(doc,line),lineLen=lineObj.text.length;function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}function wrapX(pos,dir,side){pos=wrappedLineExtentChar(cm,lineObj,null,pos),dir="ltr"==dir==("after"==side)?"left":"right";return coords("after"==side?pos.begin:pos.end-(/\s/.test(lineObj.text.charAt(pos.end-1))?2:1),dir)[dir]}var order=getOrder(lineObj,doc.direction);return((order,from,to,f)=>{if(!order)return f(from,to,"ltr",0);for(var found=!1,i=0;i<order.length;++i){var part=order[i];(part.from<to&&part.to>from||from==to&&part.to==from)&&(f(Math.max(part.from,from),Math.min(part.to,to),1==part.level?"rtl":"ltr",i),found=!0)}found||f(from,to,"ltr")})(order,fromArg||0,null==toArg?lineLen:toArg,function(from,to,dir,i){var left,topLeft,topRight,botLeft,right,ltr="ltr"==dir,fromPos=coords(from,ltr?"left":"right"),toPos=coords(to-1,ltr?"right":"left"),openStart=null==fromArg&&0==from,openEnd=null==toArg&&to==lineLen,first=0==i,i=!order||i==order.length-1;toPos.top-fromPos.top<=3?(left=(docLTR?openStart:openEnd)&&first?leftSide:(ltr?fromPos:toPos).left,right=(docLTR?openEnd:openStart)&&i?rightSide:(ltr?toPos:fromPos).right,add(left,fromPos.top,right-left,fromPos.bottom)):(right=ltr?(topLeft=docLTR&&openStart&&first?leftSide:fromPos.left,topRight=docLTR?rightSide:wrapX(from,dir,"before"),botLeft=docLTR?leftSide:wrapX(to,dir,"after"),docLTR&&openEnd&&i?rightSide:toPos.right):(topLeft=docLTR?wrapX(from,dir,"before"):leftSide,topRight=!docLTR&&openStart&&first?rightSide:fromPos.right,botLeft=!docLTR&&openEnd&&i?leftSide:toPos.left,docLTR?wrapX(to,dir,"after"):rightSide),add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom),fromPos.bottom<toPos.top&&add(leftSide,fromPos.bottom,null,toPos.top),add(botLeft,toPos.top,right-botLeft,toPos.bottom)),(!start||cmpCoords(fromPos,start)<0)&&(start=fromPos),cmpCoords(toPos,start)<0&&(start=toPos),(!end||cmpCoords(fromPos,end)<0)&&(end=fromPos),cmpCoords(toPos,end)<0&&(end=toPos)}),{start:start,end:end}}display=range.from(),padding=range.to(),display.line==padding.line?drawForLine(display.line,display.ch,padding.ch):(range=getLine(doc,display.line),toLine=getLine(doc,padding.line),toLine=visualLine(range)==visualLine(toLine),display=drawForLine(display.line,display.ch,toLine?range.text.length+1:null).end,range=drawForLine(padding.line,toLine?0:null,padding.ch).start,toLine&&(display.top<range.top-2?(add(display.right,display.top,null,display.bottom),add(leftSide,range.top,range.left,range.bottom)):add(display.right,display.top,range.left-display.right,display.bottom)),display.bottom<range.top&&add(leftSide,display.bottom,null,range.top)),output.appendChild(fragment)})(cm,range,selFragment);return result}function drawSelectionCursor(cm,head,output){var head=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine),cursor=output.appendChild(elt("div"," ","CodeMirror-cursor"));cursor.style.left=head.left+"px",cursor.style.top=head.top+"px",cursor.style.height=Math.max(0,head.bottom-head.top)*cm.options.cursorHeight+"px",head.other&&((cursor=output.appendChild(elt("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"))).style.display="",cursor.style.left=head.other.left+"px",cursor.style.top=head.other.top+"px",cursor.style.height=.85*(head.other.bottom-head.other.top)+"px")}function cmpCoords(a,b){return a.top-b.top||a.left-b.left}function restartBlink(cm){var display,on;cm.state.focused&&(display=cm.display,clearInterval(display.blinker),on=!0,display.cursorDiv.style.visibility="",0<cm.options.cursorBlinkRate?display.blinker=setInterval(function(){cm.hasFocus()||onBlur(cm),display.cursorDiv.style.visibility=(on=!on)?"":"hidden"},cm.options.cursorBlinkRate):cm.options.cursorBlinkRate<0&&(display.cursorDiv.style.visibility="hidden"))}function ensureFocus(cm){cm.hasFocus()||(cm.display.input.focus(),cm.state.focused)||onFocus(cm)}function delayBlurEvent(cm){cm.state.delayingBlurEvent=!0,setTimeout(function(){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1,cm.state.focused)&&onBlur(cm)},100)}function onFocus(cm,e){cm.state.delayingBlurEvent&&!cm.state.draggingText&&(cm.state.delayingBlurEvent=!1),"nocursor"!=cm.options.readOnly&&(cm.state.focused||(signal(cm,"focus",cm,e),cm.state.focused=!0,addClass(cm.display.wrapper,"CodeMirror-focused"),cm.curOp||cm.display.selForContextMenu==cm.doc.sel||(cm.display.input.reset(),webkit&&setTimeout(function(){return cm.display.input.reset(!0)},20)),cm.display.input.receivedFocus()),restartBlink(cm))}function onBlur(cm,e){cm.state.delayingBlurEvent||(cm.state.focused&&(signal(cm,"blur",cm,e),cm.state.focused=!1,rmClass(cm.display.wrapper,"CodeMirror-focused")),clearInterval(cm.display.blinker),setTimeout(function(){cm.state.focused||(cm.display.shift=!1)},150))}function updateHeightsInViewport(cm){for(var display=cm.display,prevBottom=display.lineDiv.offsetTop,i=0;i<display.view.length;i++){var cur=display.view[i],wrapping=cm.options.lineWrapping,height=void 0,width=0;if(!cur.hidden){ie&&ie_version<8?(height=(bot=cur.node.offsetTop+cur.node.offsetHeight)-prevBottom,prevBottom=bot):(height=(bot=cur.node.getBoundingClientRect()).bottom-bot.top,!wrapping&&cur.text.firstChild&&(width=cur.text.firstChild.getBoundingClientRect().right-bot.left-1));var bot,wrapping=cur.line.height-height;if((.005<wrapping||wrapping<-.005)&&(updateLineHeight(cur.line,height),updateWidgetHeight(cur.line),cur.rest))for(var j=0;j<cur.rest.length;j++)updateWidgetHeight(cur.rest[j]);width>cm.display.sizerWidth&&(wrapping=Math.ceil(width/charWidth(cm.display)))>cm.display.maxLineLength&&(cm.display.maxLineLength=wrapping,cm.display.maxLine=cur.line,cm.display.maxLineChanged=!0)}}}function updateWidgetHeight(line){if(line.widgets)for(var i=0;i<line.widgets.length;++i){var w=line.widgets[i],parent=w.node.parentNode;parent&&(w.height=parent.offsetHeight)}}function visibleLines(display,doc,viewport){var ensureFrom,top=viewport&&null!=viewport.top?Math.max(0,viewport.top):display.scroller.scrollTop,top=Math.floor(top-paddingTop(display)),bottom=viewport&&null!=viewport.bottom?viewport.bottom:top+display.wrapper.clientHeight,top=lineAtHeight(doc,top),bottom=lineAtHeight(doc,bottom);return viewport&&viewport.ensure&&(ensureFrom=viewport.ensure.from.line,viewport=viewport.ensure.to.line,ensureFrom<top?bottom=lineAtHeight(doc,heightAtLine(getLine(doc,top=ensureFrom))+display.wrapper.clientHeight):Math.min(viewport,doc.lastLine())>=bottom&&(top=lineAtHeight(doc,heightAtLine(getLine(doc,viewport))-display.wrapper.clientHeight),bottom=viewport)),{from:top,to:Math.max(bottom,top+1)}}function calculateScrollPos(cm,rect){var display=cm.display,snapMargin=textHeight(cm.display),screentop=(rect.top<0&&(rect.top=0),(cm.curOp&&null!=cm.curOp.scrollTop?cm.curOp:display.scroller).scrollTop),screen=displayHeight(cm),result={},docBottom=(screen<rect.bottom-rect.top&&(rect.bottom=rect.top+screen),cm.doc.height+paddingVert(display)),atBottom=docBottom-snapMargin<rect.bottom,atBottom=(rect.top<screentop?result.scrollTop=rect.top<snapMargin?0:rect.top:rect.bottom>screentop+screen&&(snapMargin=Math.min(rect.top,(atBottom?docBottom:rect.bottom)-screen))!=screentop&&(result.scrollTop=snapMargin),cm.options.fixedGutter?0:display.gutters.offsetWidth),docBottom=cm.curOp&&null!=cm.curOp.scrollLeft?cm.curOp.scrollLeft:display.scroller.scrollLeft-atBottom,screen=displayWidth(cm)-display.gutters.offsetWidth,screentop=screen<rect.right-rect.left;return screentop&&(rect.right=rect.left+screen),rect.left<10?result.scrollLeft=0:rect.left<docBottom?result.scrollLeft=Math.max(0,rect.left+atBottom-(screentop?0:10)):rect.right>screen+docBottom-3&&(result.scrollLeft=rect.right+(screentop?0:10)-screen),result}function addToScrollTop(cm,top){null!=top&&(resolveScrollToPos(cm),cm.curOp.scrollTop=(null==cm.curOp.scrollTop?cm.doc:cm.curOp).scrollTop+top)}function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor();cm.curOp.scrollToPos={from:cur,to:cur,margin:cm.options.cursorScrollMargin}}function scrollToCoords(cm,x,y){null==x&&null==y||resolveScrollToPos(cm),null!=x&&(cm.curOp.scrollLeft=x),null!=y&&(cm.curOp.scrollTop=y)}function resolveScrollToPos(cm){var range=cm.curOp.scrollToPos;range&&(cm.curOp.scrollToPos=null,scrollToCoordsRange(cm,estimateCoords(cm,range.from),estimateCoords(cm,range.to),range.margin))}function scrollToCoordsRange(cm,from,to,margin){from=calculateScrollPos(cm,{left:Math.min(from.left,to.left),top:Math.min(from.top,to.top)-margin,right:Math.max(from.right,to.right),bottom:Math.max(from.bottom,to.bottom)+margin});scrollToCoords(cm,from.scrollLeft,from.scrollTop)}function updateScrollTop(cm,val){Math.abs(cm.doc.scrollTop-val)<2||(gecko||updateDisplaySimple(cm,{top:val}),setScrollTop(cm,val,!0),gecko&&updateDisplaySimple(cm),startWorker(cm,100))}function setScrollTop(cm,val,forceScroll){val=Math.max(0,Math.min(cm.display.scroller.scrollHeight-cm.display.scroller.clientHeight,val)),cm.display.scroller.scrollTop==val&&!forceScroll||(cm.doc.scrollTop=val,cm.display.scrollbars.setScrollTop(val),cm.display.scroller.scrollTop==val)||(cm.display.scroller.scrollTop=val)}function setScrollLeft(cm,val,isScroller,forceScroll){val=Math.max(0,Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth)),(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)&&!forceScroll||(cm.doc.scrollLeft=val,alignHorizontally(cm),cm.display.scroller.scrollLeft!=val&&(cm.display.scroller.scrollLeft=val),cm.display.scrollbars.setScrollLeft(val))}function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth,docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}function NativeScrollbars(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");vert.tabIndex=horiz.tabIndex=-1,place(vert),place(horiz),on(vert,"scroll",function(){vert.clientHeight&&scroll(vert.scrollTop,"vertical")}),on(horiz,"scroll",function(){horiz.clientWidth&&scroll(horiz.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,ie&&ie_version<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function NullScrollbars(){}NativeScrollbars.prototype.update=function(measure){var totalHeight,needsH=measure.scrollWidth>measure.clientWidth+1,needsV=measure.clientHeight+1<measure.scrollHeight,sWidth=measure.nativeBarWidth;return needsV?(this.vert.style.display="block",this.vert.style.bottom=needsH?sWidth+"px":"0",totalHeight=measure.viewHeight-(needsH?sWidth:0),this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"):(this.vert.style.display="",this.vert.firstChild.style.height="0"),needsH?(this.horiz.style.display="block",this.horiz.style.right=needsV?sWidth+"px":"0",this.horiz.style.left=measure.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,measure.scrollWidth-measure.clientWidth+(measure.viewWidth-measure.barLeft-(needsV?sWidth:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0"),!this.checkedZeroWidth&&0<measure.clientHeight&&(0==sWidth&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:needsV?sWidth:0,bottom:needsH?sWidth:0}},NativeScrollbars.prototype.setScrollLeft=function(pos){this.horiz.scrollLeft!=pos&&(this.horiz.scrollLeft=pos),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},NativeScrollbars.prototype.setScrollTop=function(pos){this.vert.scrollTop!=pos&&(this.vert.scrollTop=pos),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},NativeScrollbars.prototype.zeroWidthHack=function(){this.horiz.style.height=this.vert.style.width=mac&&!mac_geMountainLion?"12px":"18px",this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new Delayed,this.disableVert=new Delayed},NativeScrollbars.prototype.enableZeroWidthBar=function(bar,delay,type){bar.style.pointerEvents="auto",delay.set(1e3,function maybeDisable(){var box=bar.getBoundingClientRect();("vert"==type?document.elementFromPoint(box.right-1,(box.top+box.bottom)/2):document.elementFromPoint((box.right+box.left)/2,box.bottom-1))!=bar?bar.style.pointerEvents="none":delay.set(1e3,maybeDisable)})},NativeScrollbars.prototype.clear=function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz),parent.removeChild(this.vert)};function updateScrollbars(cm,measure){measure=measure||measureForScrollbars(cm);var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++)startWidth!=cm.display.barWidth&&cm.options.lineWrapping&&updateHeightsInViewport(cm),updateScrollbarsInner(cm,measureForScrollbars(cm)),startWidth=cm.display.barWidth,startHeight=cm.display.barHeight}function updateScrollbarsInner(cm,measure){var d=cm.display,sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px",d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px",d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent",sizes.right&&sizes.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=sizes.bottom+"px",d.scrollbarFiller.style.width=sizes.right+"px"):d.scrollbarFiller.style.display="",sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter?(d.gutterFiller.style.display="block",d.gutterFiller.style.height=sizes.bottom+"px",d.gutterFiller.style.width=measure.gutterWidth+"px"):d.gutterFiller.style.display=""}NullScrollbars.prototype.update=function(){return{bottom:0,right:0}},NullScrollbars.prototype.setScrollLeft=function(){},NullScrollbars.prototype.setScrollTop=function(){},NullScrollbars.prototype.clear=function(){};var scrollbarModel={native:NativeScrollbars,null:NullScrollbars};function initScrollbars(cm){cm.display.scrollbars&&(cm.display.scrollbars.clear(),cm.display.scrollbars.addClass)&&rmClass(cm.display.wrapper,cm.display.scrollbars.addClass),cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller),on(node,"mousedown",function(){cm.state.focused&&setTimeout(function(){return cm.display.input.focus()},0)}),node.setAttribute("cm-not-content","true")},function(pos,axis){("horizontal"==axis?setScrollLeft:updateScrollTop)(cm,pos)},cm),cm.display.scrollbars.addClass&&addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}var nextOpId=0;function startOperation(cm){cm.curOp={cm:cm,viewChanged:!1,startHeight:cm.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++nextOpId},cm=cm.curOp,operationGroup?operationGroup.ops.push(cm):cm.ownsGroup=operationGroup={ops:[cm],delayedCallbacks:[]}}function endOperation(cm){cm=cm.curOp;cm&&finishOperation(cm,function(group){for(var i=0;i<group.ops.length;i++)group.ops[i].cm.curOp=null;(group=>{for(var ops=group.ops,i=0;i<ops.length;i++)(op=>{var cm=op.cm,display=cm.display;(cm=>{var display=cm.display;!display.scrollbarsClipped&&display.scroller.offsetWidth&&(display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth,display.heightForcer.style.height=scrollGap(cm)+"px",display.sizer.style.marginBottom=-display.nativeBarWidth+"px",display.sizer.style.borderRightWidth=scrollGap(cm)+"px",display.scrollbarsClipped=!0)})(cm),op.updateMaxLine&&findMaxLine(cm),op.mustUpdate=op.viewChanged||op.forceUpdate||null!=op.scrollTop||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping,op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)})(ops[i]);for(var i$1=0;i$1<ops.length;i$1++)(op=>{op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)})(ops[i$1]);for(var i$2=0;i$2<ops.length;i$2++)(op=>{var cm=op.cm,display=cm.display;op.updatedDisplay&&updateHeightsInViewport(cm),op.barMeasure=measureForScrollbars(cm),display.maxLineChanged&&!cm.options.lineWrapping&&(op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3,cm.display.sizerWidth=op.adjustWidthTo,op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth),op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))),(op.updatedDisplay||op.selectionChanged)&&(op.preparedSelection=display.input.prepareSelection())})(ops[i$2]);for(var i$3=0;i$3<ops.length;i$3++){op=void 0;cm=void 0;takeFocus=void 0;var op=ops[i$3];var cm=op.cm,takeFocus=(null!=op.adjustWidthTo&&(cm.display.sizer.style.minWidth=op.adjustWidthTo+"px",op.maxScrollLeft<cm.doc.scrollLeft&&setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),!0),cm.display.maxLineChanged=!1),op.focus&&op.focus==activeElt());op.preparedSelection&&cm.display.input.showSelection(op.preparedSelection,takeFocus),!op.updatedDisplay&&op.startHeight==cm.doc.height||updateScrollbars(cm,op.barMeasure),op.updatedDisplay&&setDocumentHeight(cm,op.barMeasure),op.selectionChanged&&restartBlink(cm),cm.state.focused&&op.updateInput&&cm.display.input.reset(op.typing),takeFocus&&ensureFocus(op.cm)}for(var i$4=0;i$4<ops.length;i$4++)(op=>{var rect,cm=op.cm,display=cm.display,doc=cm.doc,hidden=(op.updatedDisplay&&postUpdateDisplay(cm,op.update),null==display.wheelStartX||null==op.scrollTop&&null==op.scrollLeft&&!op.scrollToPos||(display.wheelStartX=display.wheelStartY=null),null!=op.scrollTop&&setScrollTop(cm,op.scrollTop,op.forceScroll),null!=op.scrollLeft&&setScrollLeft(cm,op.scrollLeft,!0,!0),op.scrollToPos&&(rect=((cm,pos,end,margin)=>{null==margin&&(margin=0),cm.options.lineWrapping||pos!=end||(end="before"==(pos=pos.ch?Pos(pos.line,"before"==pos.sticky?pos.ch-1:pos.ch,"after"):pos).sticky?Pos(pos.line,pos.ch+1,"before"):pos);for(var limit=0;limit<5;limit++){var rect,changed=!1,coords=cursorCoords(cm,pos),endCoords=end&&end!=pos?cursorCoords(cm,end):coords,coords=calculateScrollPos(cm,rect={left:Math.min(coords.left,endCoords.left),top:Math.min(coords.top,endCoords.top)-margin,right:Math.max(coords.left,endCoords.left),bottom:Math.max(coords.bottom,endCoords.bottom)+margin}),endCoords=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(null!=coords.scrollTop&&(updateScrollTop(cm,coords.scrollTop),1<Math.abs(cm.doc.scrollTop-endCoords))&&(changed=!0),!(changed=null!=coords.scrollLeft&&(setScrollLeft(cm,coords.scrollLeft),1<Math.abs(cm.doc.scrollLeft-startLeft))?!0:changed))break}return rect})(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin),((cm,rect)=>{var display,doScroll,box;signalDOMEvent(cm,"scrollCursorIntoView")||(box=(display=cm.display).sizer.getBoundingClientRect(),doScroll=null,rect.top+box.top<0?doScroll=!0:rect.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)&&(doScroll=!1),null==doScroll)||phantom||(box=elt("div","",null,"position: absolute;\n top: "+(rect.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(rect.bottom-rect.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+rect.left+"px; width: "+Math.max(2,rect.right-rect.left)+"px;"),cm.display.lineSpace.appendChild(box),box.scrollIntoView(doScroll),cm.display.lineSpace.removeChild(box))})(cm,rect)),op.maybeHiddenMarkers),unhidden=op.maybeUnhiddenMarkers;if(hidden)for(var i=0;i<hidden.length;++i)hidden[i].lines.length||signal(hidden[i],"hide");if(unhidden)for(var i$1=0;i$1<unhidden.length;++i$1)unhidden[i$1].lines.length&&signal(unhidden[i$1],"unhide");display.wrapper.offsetHeight&&(doc.scrollTop=cm.display.scroller.scrollTop),op.changeObjs&&signal(cm,"changes",cm,op.changeObjs),op.update&&op.update.finish()})(ops[i$4])})(group)})}function runInOp(cm,f){if(cm.curOp)return f();startOperation(cm);try{return f()}finally{endOperation(cm)}}function operation(cm,f){return function(){if(cm.curOp)return f.apply(cm,arguments);startOperation(cm);try{return f.apply(cm,arguments)}finally{endOperation(cm)}}}function methodOp(f){return function(){if(this.curOp)return f.apply(this,arguments);startOperation(this);try{return f.apply(this,arguments)}finally{endOperation(this)}}}function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp)return f.apply(this,arguments);startOperation(cm);try{return f.apply(this,arguments)}finally{endOperation(cm)}}}function startWorker(cm,time){cm.doc.highlightFrontier<cm.display.viewTo&&cm.state.highlight.set(time,bind(highlightWorker,cm))}function highlightWorker(cm){var end,context,changedLines,doc=cm.doc;doc.highlightFrontier>=cm.display.viewTo||(end=+new Date+cm.options.workTime,context=getContextBefore(cm,doc.highlightFrontier),changedLines=[],doc.iter(context.line,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(context.line>=cm.display.viewFrom){for(var oldStyles=line.styles,resetState=line.text.length>cm.options.maxHighlightLength?copyState(doc.mode,context.state):null,highlighted=highlightLine(cm,line,context,!0),resetState=(resetState&&(context.state=resetState),line.styles=highlighted.styles,line.styleClasses),highlighted=highlighted.classes,ischange=(highlighted?line.styleClasses=highlighted:resetState&&(line.styleClasses=null),!oldStyles||oldStyles.length!=line.styles.length||resetState!=highlighted&&(!resetState||!highlighted||resetState.bgClass!=highlighted.bgClass||resetState.textClass!=highlighted.textClass)),i=0;!ischange&&i<oldStyles.length;++i)ischange=oldStyles[i]!=line.styles[i];ischange&&changedLines.push(context.line),line.stateAfter=context.save()}else line.text.length<=cm.options.maxHighlightLength&&processLine(cm,line.text,context),line.stateAfter=context.line%5==0?context.save():null;if(context.nextLine(),+new Date>end)return startWorker(cm,cm.options.workDelay),!0}),doc.highlightFrontier=context.line,doc.modeFrontier=Math.max(doc.modeFrontier,context.line),changedLines.length&&runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)regLineChange(cm,changedLines[i],"text")}))}var DisplayUpdate=function(cm,viewport,force){var display=cm.display;this.viewport=viewport,this.visible=visibleLines(display,cm.doc,viewport),this.editorIsHidden=!display.wrapper.offsetWidth,this.wrapperHeight=display.wrapper.clientHeight,this.wrapperWidth=display.wrapper.clientWidth,this.oldDisplayWidth=displayWidth(cm),this.force=force,this.dims=getDimensions(cm),this.events=[]};function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden)return resetView(cm),!1;if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&0==countDirtyView(cm))return!1;maybeUpdateLineNumberWidth(cm)&&(resetView(cm),update.dims=getDimensions(cm));var end=doc.first+doc.size,from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first),to=Math.min(end,update.visible.to+cm.options.viewportMargin),doc=(display.viewFrom<from&&from-display.viewFrom<20&&(from=Math.max(doc.first,display.viewFrom)),display.viewTo>to&&display.viewTo-to<20&&(to=Math.min(end,display.viewTo)),sawCollapsedSpans&&(from=visualLineNo(cm.doc,from),to=visualLineEndNo(cm.doc,to)),from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth),end=(((cm,from,to)=>{var display=cm.display;0==display.view.length||from>=display.viewTo||to<=display.viewFrom?(display.view=buildViewArray(cm,from,to),display.viewFrom=from):(display.viewFrom>from?display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view):display.viewFrom<from&&(display.view=display.view.slice(findViewIndex(cm,from))),display.viewFrom=from,display.viewTo<to?display.view=display.view.concat(buildViewArray(cm,display.viewTo,to)):display.viewTo>to&&(display.view=display.view.slice(0,findViewIndex(cm,to)))),display.viewTo=to})(cm,from,to),display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom)),cm.display.mover.style.top=display.viewOffset+"px",countDirtyView(cm));return!(!doc&&0==end&&!update.force&&display.renderedView==display.view&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)||(from=(cm=>{var active,sel;return!cm.hasFocus()&&(active=activeElt())&&contains(cm.display.lineDiv,active)?(active={activeElt:active},window.getSelection&&(sel=window.getSelection()).anchorNode&&sel.extend&&contains(cm.display.lineDiv,sel.anchorNode)&&(active.anchorNode=sel.anchorNode,active.anchorOffset=sel.anchorOffset,active.focusNode=sel.focusNode,active.focusOffset=sel.focusOffset),active):null})(cm),4<end&&(display.lineDiv.style.display="none"),((cm,updateNumbersFrom,dims)=>{var display=cm.display,lineNumbers=cm.options.lineNumbers,container=display.lineDiv,cur=container.firstChild;function rm(node){var next=node.nextSibling;return webkit&&mac&&cm.display.currentWheelTarget==node?node.style.display="none":node.parentNode.removeChild(node),next}for(var view=display.view,lineN=display.viewFrom,i=0;i<view.length;i++){var lineView=view[i];if(!lineView.hidden)if(lineView.node&&lineView.node.parentNode==container){for(;cur!=lineView.node;)cur=rm(cur);var updateNumber=lineNumbers&&null!=updateNumbersFrom&&updateNumbersFrom<=lineN&&lineView.lineNumber;lineView.changes&&(-1<indexOf(lineView.changes,"gutter")&&(updateNumber=!1),updateLineForChanges(cm,lineView,lineN,dims)),updateNumber&&(removeChildren(lineView.lineNumber),lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))),cur=lineView.node.nextSibling}else{updateNumber=((cm,lineView,lineN,dims)=>{var built=getLineContent(cm,lineView);return lineView.text=lineView.node=built.pre,built.bgClass&&(lineView.bgClass=built.bgClass),built.textClass&&(lineView.textClass=built.textClass),updateLineClasses(cm,lineView),updateLineGutter(cm,lineView,lineN,dims),insertLineWidgets(cm,lineView,dims),lineView.node})(cm,lineView,lineN,dims);container.insertBefore(updateNumber,cur)}lineN+=lineView.size}for(;cur;)cur=rm(cur)})(cm,display.updateLineNumbers,update.dims),4<end&&(display.lineDiv.style.display=""),display.renderedView=display.view,(to=from)&&to.activeElt&&to.activeElt!=activeElt()&&(to.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(to.activeElt.nodeName))&&to.anchorNode&&contains(document.body,to.anchorNode)&&contains(document.body,to.focusNode)&&(end=window.getSelection(),(from=document.createRange()).setEnd(to.anchorNode,to.anchorOffset),from.collapse(!1),end.removeAllRanges(),end.addRange(from),end.extend(to.focusNode,to.focusOffset)),removeChildren(display.cursorDiv),removeChildren(display.selectionDiv),display.gutters.style.height=display.sizer.style.minHeight=0,doc&&(display.lastWrapHeight=update.wrapperHeight,display.lastWrapWidth=update.wrapperWidth,startWorker(cm,400)),display.updateLineNumbers=null))}function postUpdateDisplay(cm,update){for(var viewport=update.viewport,first=!0;;first=!1){if(first&&cm.options.lineWrapping&&update.oldDisplayWidth!=displayWidth(cm))first&&(update.visible=visibleLines(cm.display,cm.doc,viewport));else if(viewport&&null!=viewport.top&&(viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)}),update.visible=visibleLines(cm.display,cm.doc,viewport),update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)break;if(!updateDisplayIfNeeded(cm,update))break;updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),update.force=!1}update.signal(cm,"update",cm),cm.display.viewFrom==cm.display.reportedViewFrom&&cm.display.viewTo==cm.display.reportedViewTo||(update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo),cm.display.reportedViewFrom=cm.display.viewFrom,cm.display.reportedViewTo=cm.display.viewTo)}function updateDisplaySimple(cm,viewport){var barMeasure,viewport=new DisplayUpdate(cm,viewport);updateDisplayIfNeeded(cm,viewport)&&(updateHeightsInViewport(cm),postUpdateDisplay(cm,viewport),barMeasure=measureForScrollbars(cm),updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),viewport.finish())}function updateGutterSpace(display){var width=display.gutters.offsetWidth;display.sizer.style.marginLeft=width+"px"}function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px",cm.display.heightForcer.style.top=measure.docHeight+"px",cm.display.gutters.style.height=measure.docHeight+cm.display.barHeight+scrollGap(cm)+"px"}function alignHorizontally(cm){var display=cm.display,view=display.view;if(display.alignWidgets||display.gutters.firstChild&&cm.options.fixedGutter){for(var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft,gutterW=display.gutters.offsetWidth,left=comp+"px",i=0;i<view.length;i++)if(!view[i].hidden){cm.options.fixedGutter&&(view[i].gutter&&(view[i].gutter.style.left=left),view[i].gutterBackground)&&(view[i].gutterBackground.style.left=left);var align=view[i].alignable;if(align)for(var j=0;j<align.length;j++)align[j].style.left=left}cm.options.fixedGutter&&(display.gutters.style.left=comp+gutterW+"px")}}function maybeUpdateLineNumberWidth(cm){var doc,display,innerW,test;return cm.options.lineNumbers&&(doc=lineNumberFor(cm.options,(doc=cm.doc).first+doc.size-1)).length!=(display=cm.display).lineNumChars?(innerW=(test=display.measure.appendChild(elt("div",[elt("div",doc)],"CodeMirror-linenumber CodeMirror-gutter-elt"))).firstChild.offsetWidth,test=test.offsetWidth-innerW,display.lineGutter.style.width="",display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-test)+1,display.lineNumWidth=display.lineNumInnerWidth+test,display.lineNumChars=display.lineNumInnerWidth?doc.length:-1,display.lineGutter.style.width=display.lineNumWidth+"px",updateGutterSpace(cm.display),1):void 0}function getGutters(gutters,lineNumbers){for(var result=[],sawLineNumbers=!1,i=0;i<gutters.length;i++){var name=gutters[i],style=null;if("string"!=typeof name&&(style=name.style,name=name.className),"CodeMirror-linenumbers"==name){if(!lineNumbers)continue;sawLineNumbers=!0}result.push({className:name,style:style})}return lineNumbers&&!sawLineNumbers&&result.push({className:"CodeMirror-linenumbers",style:null}),result}function renderGutters(display){var gutters=display.gutters,specs=display.gutterSpecs;removeChildren(gutters),display.lineGutter=null;for(var i=0;i<specs.length;++i){var ref=specs[i],className=ref.className,ref=ref.style,gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+className));ref&&(gElt.style.cssText=ref),"CodeMirror-linenumbers"==className&&((display.lineGutter=gElt).style.width=(display.lineNumWidth||1)+"px")}gutters.style.display=specs.length?"":"none",updateGutterSpace(display)}function updateGutters(cm){renderGutters(cm.display),regChange(cm),alignHorizontally(cm)}function Display(place,doc,input,options){var d=this,lines=(this.input=input,d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler"),d.scrollbarFiller.setAttribute("cm-not-content","true"),d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler"),d.gutterFiller.setAttribute("cm-not-content","true"),d.lineDiv=eltP("div",null,"CodeMirror-code"),d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1"),d.cursorDiv=elt("div",null,"CodeMirror-cursors"),d.measure=elt("div",null,"CodeMirror-measure"),d.lineMeasure=elt("div",null,"CodeMirror-measure"),d.lineSpace=eltP("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none"),eltP("div",[d.lineSpace],"CodeMirror-lines"));d.mover=elt("div",[lines],null,"position: relative"),d.sizer=elt("div",[d.mover],"CodeMirror-sizer"),d.sizerWidth=null,d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;"),d.gutters=elt("div",null,"CodeMirror-gutters"),d.lineGutter=null,d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll"),d.scroller.setAttribute("tabIndex","-1"),d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror"),ie&&ie_version<8&&(d.gutters.style.zIndex=-1,d.scroller.style.paddingRight=0),webkit||gecko&&mobile||(d.scroller.draggable=!0),place&&(place.appendChild?place.appendChild(d.wrapper):place(d.wrapper)),d.viewFrom=d.viewTo=doc.first,d.reportedViewFrom=d.reportedViewTo=doc.first,d.view=[],d.renderedView=null,d.externalMeasured=null,d.viewOffset=0,d.lastWrapHeight=d.lastWrapWidth=0,d.updateLineNumbers=null,d.nativeBarWidth=d.barHeight=d.barWidth=0,d.scrollbarsClipped=!1,d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null,d.alignWidgets=!1,d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.maxLine=null,d.maxLineLength=0,d.maxLineChanged=!1,d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null,d.shift=!1,d.selForContextMenu=null,d.activeTouch=null,d.gutterSpecs=getGutters(options.gutters,options.lineNumbers),renderGutters(d),input.init(d)}DisplayUpdate.prototype.signal=function(emitter,type){hasHandler(emitter,type)&&this.events.push(arguments)},DisplayUpdate.prototype.finish=function(){for(var i=0;i<this.events.length;i++)signal.apply(null,this.events[i])};var wheelSamples=0,wheelPixelsPerUnit=null;function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;return null==dx&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(dx=e.detail),null==dy&&e.detail&&e.axis==e.VERTICAL_AXIS?dy=e.detail:null==dy&&(dy=e.wheelDelta),{x:dx,y:dy}}function wheelEventPixels(e){e=wheelEventDelta(e);return e.x*=wheelPixelsPerUnit,e.y*=wheelPixelsPerUnit,e}function onScrollWheel(cm,e){var top,bot,delta=wheelEventDelta(e),dx=delta.x,delta=delta.y,display=cm.display,scroll=display.scroller,canScrollX=scroll.scrollWidth>scroll.clientWidth,canScrollY=scroll.clientHeight<scroll.scrollHeight;if(dx&&canScrollX||delta&&canScrollY){if(delta&&mac&&webkit)outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode)for(var i=0;i<view.length;i++)if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}!dx||gecko||presto||null==wheelPixelsPerUnit?(delta&&null!=wheelPixelsPerUnit&&(canScrollX=delta*wheelPixelsPerUnit,bot=(top=cm.doc.scrollTop)+display.wrapper.clientHeight,canScrollX<0?top=Math.max(0,top+canScrollX-50):bot=Math.min(cm.doc.height,bot+canScrollX+50),updateDisplaySimple(cm,{top:top,bottom:bot})),wheelSamples<20&&(null==display.wheelStartX?(display.wheelStartX=scroll.scrollLeft,display.wheelStartY=scroll.scrollTop,display.wheelDX=dx,display.wheelDY=delta,setTimeout(function(){var movedX,movedY;null!=display.wheelStartX&&(movedX=scroll.scrollLeft-display.wheelStartX,movedY=(movedY=scroll.scrollTop-display.wheelStartY)&&display.wheelDY&&movedY/display.wheelDY||movedX&&display.wheelDX&&movedX/display.wheelDX,display.wheelStartX=display.wheelStartY=null,movedY)&&(wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+movedY)/(wheelSamples+1),++wheelSamples)},200)):(display.wheelDX+=dx,display.wheelDY+=delta))):(delta&&canScrollY&&updateScrollTop(cm,Math.max(0,scroll.scrollTop+delta*wheelPixelsPerUnit)),setScrollLeft(cm,Math.max(0,scroll.scrollLeft+dx*wheelPixelsPerUnit)),delta&&!canScrollY||e_preventDefault(e),display.wheelStartX=null)}}ie?wheelPixelsPerUnit=-.53:gecko?wheelPixelsPerUnit=15:chrome?wheelPixelsPerUnit=-.7:safari&&(wheelPixelsPerUnit=-1/3);var Selection=function(ranges,primIndex){this.ranges=ranges,this.primIndex=primIndex},Range=(Selection.prototype.primary=function(){return this.ranges[this.primIndex]},Selection.prototype.equals=function(other){if(other!=this){if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length)return!1;for(var i=0;i<this.ranges.length;i++){var here=this.ranges[i],there=other.ranges[i];if(!equalCursorPos(here.anchor,there.anchor)||!equalCursorPos(here.head,there.head))return!1}}return!0},Selection.prototype.deepCopy=function(){for(var out=[],i=0;i<this.ranges.length;i++)out[i]=new Range(copyPos(this.ranges[i].anchor),copyPos(this.ranges[i].head));return new Selection(out,this.primIndex)},Selection.prototype.somethingSelected=function(){for(var i=0;i<this.ranges.length;i++)if(!this.ranges[i].empty())return!0;return!1},Selection.prototype.contains=function(pos,end){end=end||pos;for(var i=0;i<this.ranges.length;i++){var range=this.ranges[i];if(0<=cmp(end,range.from())&&cmp(pos,range.to())<=0)return i}return-1},function(anchor,head){this.anchor=anchor,this.head=head});function normalizeSelection(cm,ranges,primIndex){var mayTouch=cm&&cm.options.selectionsMayTouch,cm=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from())}),primIndex=indexOf(ranges,cm);for(var i=1;i<ranges.length;i++){var to,cur=ranges[i],prev=ranges[i-1],diff=cmp(prev.to(),cur.from());(mayTouch&&!cur.empty()?0<diff:0<=diff)&&(diff=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()),cur=prev.empty()?cur.from()==cur.head:prev.from()==prev.head,i<=primIndex&&--primIndex,ranges.splice(--i,2,new Range(cur?to:diff,cur?diff:to)))}return new Selection(ranges,primIndex)}function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}function changeEnd(change){return change.text?Pos(change.from.line+change.text.length-1,lst(change.text).length+(1==change.text.length?change.from.ch:0)):change.to}function adjustForChange(pos,change){var line,ch;return cmp(pos,change.from)<0?pos:cmp(pos,change.to)<=0?changeEnd(change):(line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch,pos.line==change.to.line&&(ch+=changeEnd(change).ch-change.to.ch),Pos(line,ch))}function computeSelAfterChange(doc,change){for(var out=[],i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))}return normalizeSelection(doc.cm,out,doc.sel.primIndex)}function offsetPos(pos,old,nw){return pos.line==old.line?Pos(nw.line,pos.ch-old.ch+nw.ch):Pos(nw.line+(pos.line-old.line),pos.ch)}function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption),resetModeState(cm)}function resetModeState(cm){cm.doc.iter(function(line){line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null)}),cm.doc.modeFrontier=cm.doc.highlightFrontier=cm.doc.first,startWorker(cm,100),cm.state.modeGen++,cm.curOp&®Change(cm)}function isWholeLineUpdate(doc,change){return 0==change.from.ch&&0==change.to.ch&&""==lst(change.text)&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}function updateDoc(doc,change,markedSpans,estimateHeight){function spansFor(n){return markedSpans?markedSpans[n]:null}function update(line,text,spans){((line,text,markedSpans,estimateHeight)=>{line.text=text,line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null),null!=line.order&&(line.order=null),detachMarkedSpans(line),attachMarkedSpans(line,markedSpans),(text=estimateHeight?estimateHeight(line):1)!=line.height&&updateLineHeight(line,text)})(line,text,spans,estimateHeight),signalLater(line,"change",line,change)}function linesFor(start,end){for(var result=[],i=start;i<end;++i)result.push(new Line(text[i],spansFor(i),estimateHeight));return result}var added,from=change.from,to=change.to,text=change.text,firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line),lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;change.full?(doc.insert(0,linesFor(0,text.length)),doc.remove(text.length,doc.size-text.length)):isWholeLineUpdate(doc,change)?(added=linesFor(0,text.length-1),update(lastLine,lastLine.text,lastSpans),nlines&&doc.remove(from.line,nlines),added.length&&doc.insert(from.line,added)):firstLine==lastLine?1==text.length?update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans):((added=linesFor(1,text.length-1)).push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight)),update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),doc.insert(from.line+1,added)):1==text.length?(update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0)),doc.remove(from.line+1,nlines)):(update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans),added=linesFor(1,text.length-1),1<nlines&&doc.remove(from.line+1,nlines-1),doc.insert(from.line+1,added)),signalLater(doc,"change",doc,change)}function linkedDocs(doc,f,sharedHistOnly){!function propagate(doc,skip,sharedHist){if(doc.linked)for(var i=0;i<doc.linked.length;++i){var shared,rel=doc.linked[i];rel.doc!=skip&&(shared=sharedHist&&rel.sharedHist,!sharedHistOnly||shared)&&(f(rel.doc,shared),propagate(rel.doc,doc,shared))}}(doc,null,!0)}function attachDoc(cm,doc){if(doc.cm)throw new Error("This document is already in use.");cm.doc=doc,estimateLineHeights(doc.cm=cm),loadMode(cm),setDirectionClass(cm),cm.options.lineWrapping||findMaxLine(cm),cm.options.mode=doc.modeOption,regChange(cm)}function setDirectionClass(cm){("rtl"==cm.doc.direction?addClass:rmClass)(cm.display.lineDiv,"CodeMirror-rtl")}function History(startGen){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=startGen||1}function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1),linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1)},!0),histChange}function clearSelectionEvents(array){for(;array.length;){if(!lst(array).ranges)break;array.pop()}}function addChangeToHistory(doc,change,selAfter,opId){var cur,last,hist=doc.history,time=(hist.undone.length=0,+new Date);if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&("+"==change.origin.charAt(0)&&hist.lastModTime>time-(doc.cm?doc.cm.options.historyEventDelay:500)||"*"==change.origin.charAt(0)))&&(cur=((hist,force)=>force?(clearSelectionEvents(hist.done),lst(hist.done)):hist.done.length&&!lst(hist.done).ranges?lst(hist.done):1<hist.done.length&&!hist.done[hist.done.length-2].ranges?(hist.done.pop(),lst(hist.done)):void 0)(hist,hist.lastOp==opId)))last=lst(cur.changes),0==cmp(change.from,change.to)&&0==cmp(change.from,last.to)?last.to=changeEnd(change):cur.changes.push(historyChangeFromChange(doc,change));else{var before=lst(hist.done);for(before&&before.ranges||pushSelectionToHistory(doc.sel,hist.done),cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation},hist.done.push(cur);hist.done.length>hist.undoDepth;)hist.done.shift(),hist.done[0].ranges||hist.done.shift()}hist.done.push(selAfter),hist.generation=++hist.maxGeneration,hist.lastModTime=hist.lastSelTime=time,hist.lastOp=hist.lastSelOp=opId,hist.lastOrigin=hist.lastSelOrigin=change.origin,last||signal(doc,"historyAdded")}function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;opId==hist.lastSelOp||origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||((doc,origin,prev,sel)=>"*"==(origin=origin.charAt(0))||"+"==origin&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500))(doc,origin,lst(hist.done),sel))?hist.done[hist.done.length-1]=sel:pushSelectionToHistory(sel,hist.done),hist.lastSelTime=+new Date,hist.lastSelOrigin=origin,hist.lastSelOp=opId,options&&!1!==options.clearRedo&&clearSelectionEvents(hist.undone)}function pushSelectionToHistory(sel,dest){var top=lst(dest);top&&top.ranges&&top.equals(sel)||dest.push(sel)}function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){line.markedSpans&&((existing=existing||(change["spans_"+doc.id]={}))[n]=line.markedSpans),++n})}function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found)return null;for(var nw=[],i=0;i<change.text.length;++i)nw.push((spans=>{if(!spans)return null;for(var out,i=0;i<spans.length;++i)spans[i].marker.explicitlyCleared?out=out||spans.slice(0,i):out&&out.push(spans[i]);return out?out.length?out:null:spans})(found[i]));return nw}function mergeOldSpans(doc,change){var old=getOldSpans(doc,change),stretched=stretchSpansOverChange(doc,change);if(!old)return stretched;if(stretched)for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur)spans:for(var j=0;j<stretchCur.length;++j){for(var span=stretchCur[j],k=0;k<oldCur.length;++k)if(oldCur[k].marker==span.marker)continue spans;oldCur.push(span)}else stretchCur&&(old[i]=stretchCur)}return old}function copyHistoryArray(events,newGroup,instantiateSel){for(var copy=[],i=0;i<events.length;++i){var event=events[i];if(event.ranges)copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);else{var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var m,change=changes[j];if(newChanges.push({from:change.from,to:change.to,text:change.text}),newGroup)for(var prop in change)(m=prop.match(/^spans_(\d+)$/))&&-1<indexOf(newGroup,Number(m[1]))&&(lst(newChanges)[prop]=change[prop],delete change[prop])}}}return copy}function extendRange(range,head,other,extend){return extend?(extend=range.anchor,other&&((range=cmp(head,extend)<0)!=cmp(other,extend)<0?(extend=head,head=other):range!=cmp(head,other)<0&&(head=other)),new Range(extend,head)):new Range(other||head,head)}function extendSelection(doc,head,other,options,extend){null==extend&&(extend=doc.cm&&(doc.cm.display.shift||doc.extend)),setSelection(doc,new Selection([extendRange(doc.sel.primary(),head,other,extend)],0),options)}function extendSelections(doc,heads,options){for(var out=[],extend=doc.cm&&(doc.cm.display.shift||doc.extend),i=0;i<doc.sel.ranges.length;i++)out[i]=extendRange(doc.sel.ranges[i],heads[i],null,extend);setSelection(doc,normalizeSelection(doc.cm,out,doc.sel.primIndex),options)}function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range,setSelection(doc,normalizeSelection(doc.cm,ranges,doc.sel.primIndex),options)}function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)}function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);last&&last.ranges?setSelectionNoUndo(doc,done[done.length-1]=sel,options):setSelection(doc,sel,options)}function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options),addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)}function setSelectionNoUndo(doc,sel,options){(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))&&(sel=((doc,sel,options)=>(options={ranges:sel.ranges,update:function(ranges){this.ranges=[];for(var i=0;i<ranges.length;i++)this.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))},origin:options&&options.origin},signal(doc,"beforeSelectionChange",doc,options),doc.cm&&signal(doc.cm,"beforeSelectionChange",doc.cm,options),options.ranges!=sel.ranges?normalizeSelection(doc.cm,options.ranges,options.ranges.length-1):sel))(doc,sel,options));var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1);setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,!0)),options&&!1===options.scroll||!doc.cm||ensureCursorVisible(doc.cm)}function setSelectionInner(doc,sel){sel.equals(doc.sel)||(doc.sel=sel,doc.cm&&(doc.cm.curOp.updateInput=1,doc.cm.curOp.selectionChanged=!0,signalCursorActivity(doc.cm)),signalLater(doc,"cursorActivity",doc))}function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,!1))}function skipAtomicInSelection(doc,sel,bias,mayClear){for(var out,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i],old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i],newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear),old=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);!out&&newAnchor==range.anchor&&old==range.head||((out=out||sel.ranges.slice(0,i))[i]=new Range(newAnchor,old))}return out?normalizeSelection(doc.cm,out,sel.primIndex):sel}function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker,preventCursorLeft="selectLeft"in m?!m.selectLeft:m.inclusiveLeft,preventCursorRight="selectRight"in m?!m.selectRight:m.inclusiveRight;if((null==sp.from||(preventCursorLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(null==sp.to||(preventCursorRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear&&(signal(m,"beforeCursorEnter"),m.explicitlyCleared)){if(line.markedSpans){--i;continue}break}if(m.atomic){if(oldPos){var sp=m.find(dir<0?1:-1),diff=void 0;if((sp=(dir<0?preventCursorRight:preventCursorLeft)?movePos(doc,sp,-dir,sp&&sp.line==pos.line?line:null):sp)&&sp.line==pos.line&&(diff=cmp(sp,oldPos))&&(dir<0?diff<0:0<diff))return skipAtomicInner(doc,sp,pos,dir,mayClear)}diff=m.find(dir<0?-1:1);return(diff=(dir<0?preventCursorLeft:preventCursorRight)?movePos(doc,diff,dir,diff.line==pos.line?line:null):diff)?skipAtomicInner(doc,diff,pos,dir,mayClear):null}}}return pos}function skipAtomic(doc,pos,oldPos,bias,mayClear){bias=bias||1,mayClear=skipAtomicInner(doc,pos,oldPos,bias,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,bias,!0)||skipAtomicInner(doc,pos,oldPos,-bias,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,-bias,!0);return mayClear||(doc.cantEdit=!0,Pos(doc.first,0))}function movePos(doc,pos,dir,line){return dir<0&&0==pos.ch?pos.line>doc.first?clipPos(doc,Pos(pos.line-1)):null:0<dir&&pos.ch==(line||getLine(doc,pos.line)).text.length?pos.line<doc.first+doc.size-1?Pos(pos.line+1,0):null:new Pos(pos.line,pos.ch+dir)}function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)}function filterChange(doc,change,update){var obj={canceled:!1,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=!0}};return update&&(obj.update=function(from,to,text,origin){from&&(obj.from=clipPos(doc,from)),to&&(obj.to=clipPos(doc,to)),text&&(obj.text=text),void 0!==origin&&(obj.origin=origin)}),signal(doc,"beforeChange",doc,obj),doc.cm&&signal(doc.cm,"beforeChange",doc.cm,obj),obj.canceled?(doc.cm&&(doc.cm.curOp.updateInput=2),null):{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp)return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly);if(doc.cm.state.suppressEdits)return}if(!(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"))||(change=filterChange(doc,change,!0))){var split=sawReadOnlySpans&&!ignoreReadOnly&&((doc,from,to)=>{var markers=null;if(doc.iter(from.line,to.line+1,function(line){if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;!mark.readOnly||markers&&-1!=indexOf(markers,mark)||(markers=markers||[]).push(mark)}}),!markers)return null;for(var parts=[{from:from,to:to}],i=0;i<markers.length;++i)for(var mk=markers[i],m=mk.find(0),j=0;j<parts.length;++j){var newParts,dfrom,dto,p=parts[j];cmp(p.to,m.from)<0||0<cmp(p.from,m.to)||(newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to),(dfrom<0||!mk.inclusiveLeft&&!dfrom)&&newParts.push({from:p.from,to:m.from}),(0<dto||!mk.inclusiveRight&&!dto)&&newParts.push({from:m.to,to:p.to}),parts.splice.apply(parts,newParts),j+=newParts.length-3)}return parts})(doc,change.from,change.to);if(split)for(var i=split.length-1;0<=i;--i)makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text,origin:change.origin});else makeChangeInner(doc,change)}}function makeChangeInner(doc,change){var selAfter,rebased;1==change.text.length&&""==change.text[0]&&0==cmp(change.from,change.to)||(selAfter=computeSelAfterChange(doc,change),addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN),makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change)),rebased=[],linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))}))}function makeChangeFromHistory(doc,type,allowSelectionOnly){var suppress=doc.cm&&doc.cm.state.suppressEdits;if(!suppress||allowSelectionOnly){for(var event,hist=doc.history,selAfter=doc.sel,source="undo"==type?hist.done:hist.undone,dest="undo"==type?hist.undone:hist.done,i=0;i<source.length&&(event=source[i],allowSelectionOnly?!event.ranges||event.equals(doc.sel):event.ranges);i++);if(i!=source.length){for(hist.lastOrigin=hist.lastSelOrigin=null;;){if(!(event=source.pop()).ranges){if(suppress)return void source.push(event);break}if(pushSelectionToHistory(event,dest),allowSelectionOnly&&!event.equals(doc.sel))return void setSelection(doc,event,{clearRedo:!1});selAfter=event}for(var antiChanges=[],filter=(pushSelectionToHistory(selAfter,dest),dest.push({changes:antiChanges,generation:hist.generation}),hist.generation=event.generation||++hist.maxGeneration,hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")),i$1=event.changes.length-1;0<=i$1;--i$1){var returned=(i=>{var change=event.changes[i];if(change.origin=type,filter&&!filterChange(doc,change,!1))return source.length=0,{};antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source),rebased=(makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change)),!i&&doc.cm&&doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)}),[]);linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})})(i$1);if(returned)return returned.v}}}}function shiftDoc(doc,distance){if(0!=distance&&(doc.first+=distance,doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch))}),doc.sel.primIndex),doc.cm)){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)regLineChange(doc.cm,l,"gutter")}}function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans);var shift;change.to.line<doc.first?shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line)):change.from.line>doc.lastLine()||(change.from.line<doc.first&&(shiftDoc(doc,shift=change.text.length-1-(doc.first-change.from.line)),change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}),shift=doc.lastLine(),(change=change.to.line>shift?{from:change.from,to:Pos(shift,getLine(doc,shift).text.length),text:[change.text[0]],origin:change.origin}:change).removed=getBetween(doc,change.from,change.to),selAfter=selAfter||computeSelAfterChange(doc,change),doc.cm?((cm,change,spans)=>{var doc=cm.doc,display=cm.display,from=change.from,to=change.to,recomputeMaxLength=!1,checkWidthStart=from.line;cm.options.lineWrapping||(checkWidthStart=lineNo(visualLine(getLine(doc,from.line))),doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine)return recomputeMaxLength=!0})),-1<doc.sel.contains(change.from,change.to)&&signalCursorActivity(cm),updateDoc(doc,change,spans,estimateHeight(cm)),cm.options.lineWrapping||(doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);len>display.maxLineLength&&(display.maxLine=line,display.maxLineLength=len,display.maxLineChanged=!0,recomputeMaxLength=!1)}),recomputeMaxLength&&(cm.curOp.updateMaxLine=!0)),((doc,n)=>{if(doc.modeFrontier=Math.min(doc.modeFrontier,n),!(doc.highlightFrontier<n-10)){for(var start=doc.first,line=n-1;start<line;line--){var saved=getLine(doc,line).stateAfter;if(saved&&(!(saved instanceof SavedContext)||line+saved.lookAhead<n)){start=line+1;break}}doc.highlightFrontier=Math.min(doc.highlightFrontier,start)}})(doc,from.line),startWorker(cm,400),spans=change.text.length-(to.line-from.line)-1,change.full?regChange(cm):from.line!=to.line||1!=change.text.length||isWholeLineUpdate(cm.doc,change)?regChange(cm,from.line,to.line+1,spans):regLineChange(cm,from.line,"text"),checkWidthStart=hasHandler(cm,"changes"),((doc=hasHandler(cm,"change"))||checkWidthStart)&&(spans={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin},doc&&signalLater(cm,"change",cm,spans),checkWidthStart)&&(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(spans),cm.display.selForContextMenu=null})(doc.cm,change,spans):updateDoc(doc,change,spans),setSelectionNoUndo(doc,selAfter,sel_dontScroll),doc.cantEdit&&skipAtomic(doc,Pos(doc.firstLine(),0))&&(doc.cantEdit=!1))}function replaceRange(doc,code,from,to,origin){var assign;cmp(to=to||from,from)<0&&(from=(assign=[to,from])[0],to=assign[1]),"string"==typeof code&&(code=doc.splitLines(code)),makeChange(doc,{from:from,to:to,text:code,origin:origin})}function rebaseHistSelSingle(pos,from,to,diff){to<pos.line?pos.line+=diff:from<pos.line&&(pos.line=from,pos.ch=0)}function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=!0;if(sub.ranges){sub.copied||((sub=array[i]=sub.deepCopy()).copied=!0);for(var j=0;j<sub.ranges.length;j++)rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff),rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)}else{for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1];if(to<cur.from.line)cur.from=Pos(cur.from.line+diff,cur.from.ch),cur.to=Pos(cur.to.line+diff,cur.to.ch);else if(from<=cur.to.line){ok=!1;break}}ok||(array.splice(0,i+1),i=0)}}}function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,change=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,change),rebaseHistArray(hist.undone,from,to,change)}function changeLine(doc,handle,changeType,op){var no=handle,line=handle;return"number"==typeof handle?line=getLine(doc,clipLine(doc,handle)):no=lineNo(handle),null==no?null:(op(line,no)&&doc.cm&®LineChange(doc.cm,no,changeType),line)}function LeafChunk(lines){this.lines=lines,this.parent=null;for(var height=0,i=0;i<lines.length;++i)lines[i].parent=this,height+=lines[i].height;this.height=height}function BranchChunk(children){this.children=children;for(var size=0,height=0,i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize(),height+=ch.height,ch.parent=this}this.size=size,this.height=height,this.parent=null}Range.prototype.from=function(){return minPos(this.anchor,this.head)},Range.prototype.to=function(){return maxPos(this.anchor,this.head)},Range.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var i=at,e=at+n;i<e;++i){var line=this.lines[i];this.height-=line.height,(line=>{line.parent=null,detachMarkedSpans(line)})(line),signalLater(line,"delete")}this.lines.splice(at,n)},collapse:function(lines){lines.push.apply(lines,this.lines)},insertInner:function(at,lines,height){this.height+=height,this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i)lines[i].parent=this},iterN:function(at,n,op){for(var e=at+n;at<e;++at)if(op(this.lines[at]))return!0}},BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){this.size-=n;for(var lines,i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height;if(child.removeInner(at,rm),this.height-=oldHeight-child.height,sz==rm&&(this.children.splice(i--,1),child.parent=null),0==(n-=rm))break;at=0}else at-=sz}this.size-n<25&&(1<this.children.length||!(this.children[0]instanceof LeafChunk))&&(this.collapse(lines=[]),this.children=[new LeafChunk(lines)],this.children[0].parent=this)},collapse:function(lines){for(var i=0;i<this.children.length;++i)this.children[i].collapse(lines)},insertInner:function(at,lines,height){this.size+=lines.length,this.height+=height;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<=sz){if(child.insertInner(at,lines,height),child.lines&&50<child.lines.length){for(var remaining=child.lines.length%25+25,pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25));child.height-=leaf.height,this.children.splice(++i,0,leaf),leaf.parent=this}child.lines=child.lines.slice(0,remaining),this.maybeSpill()}break}at-=sz}},maybeSpill:function(){if(!(this.children.length<=10)){var me=this;do{var myIndex,sibling=new BranchChunk(me.children.splice(me.children.length-5,5))}while(me.parent?(me.size-=sibling.size,me.height-=sibling.height,myIndex=indexOf(me.parent.children,me),me.parent.children.splice(myIndex+1,0,sibling)):(((myIndex=new BranchChunk(me.children)).parent=me).children=[myIndex,sibling],me=myIndex),sibling.parent=me.parent,10<me.children.length);me.parent.maybeSpill()}},iterN:function(at,n,op){for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var used=Math.min(n,sz-at);if(child.iterN(at,used,op))return!0;if(0==(n-=used))break;at=0}else at-=sz}}};function LineWidget(doc,node,options){if(options)for(var opt in options)options.hasOwnProperty(opt)&&(this[opt]=options[opt]);this.doc=doc,this.node=node}function adjustScrollWhenAboveVisible(cm,line,diff){heightAtLine(line)<(cm.curOp&&cm.curOp.scrollTop||cm.doc.scrollTop)&&addToScrollTop(cm,diff)}LineWidget.prototype.clear=function(){var cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(null!=no&&ws){for(var i=0;i<ws.length;++i)ws[i]==this&&ws.splice(i--,1);ws.length||(line.widgets=null);var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height)),cm&&(runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height),regLineChange(cm,no,"widget")}),signalLater(cm,"lineWidgetCleared",cm,this,no))}},LineWidget.prototype.changed=function(){var this$1=this,oldH=this.height,cm=this.doc.cm,line=this.line,diff=(this.height=null,widgetHeight(this)-oldH);diff&&(lineIsHidden(this.doc,line)||updateLineHeight(line,line.height+diff),cm)&&runInOp(cm,function(){cm.curOp.forceUpdate=!0,adjustScrollWhenAboveVisible(cm,line,diff),signalLater(cm,"lineWidgetChanged",cm,this$1,lineNo(line))})},eventMixin(LineWidget);function TextMarker(doc,type){this.lines=[],this.type=type,this.doc=doc,this.id=++nextMarkerId}var nextMarkerId=0;function markText(doc,from,to,options,type){if(options&&options.shared)return((doc,from,to,options,type)=>{(options=copyObj(options)).shared=!1;var markers=[markText(doc,from,to,options,type)],primary=markers[0],widget=options.widgetNode;return linkedDocs(doc,function(doc){widget&&(options.widgetNode=widget.cloneNode(!0)),markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)if(doc.linked[i].isParent)return;primary=lst(markers)}),new SharedTextMarker(markers,primary)})(doc,from,to,options,type);if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,markText)(doc,from,to,options,type);var marker=new TextMarker(doc,type),type=cmp(from,to);if(options&©Obj(options,marker,!1),!(0<type||0==type&&!1!==marker.clearWhenEmpty)){if(marker.replacedWith&&(marker.collapsed=!0,marker.widgetNode=eltP("span",[marker.replacedWith],"CodeMirror-widget"),options.handleMouseEvents||marker.widgetNode.setAttribute("cm-ignore-events","true"),options.insertLeft)&&(marker.widgetNode.insertLeft=!0),marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))throw new Error("Inserting collapsed marker partially overlapping an existing one");sawCollapsedSpans=!0}marker.addToHistory&&addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);var updateMaxLine,curLine=from.line,cm=doc.cm;if(doc.iter(curLine,to.line+1,function(line){cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine&&(updateMaxLine=!0),marker.collapsed&&curLine!=from.line&&updateLineHeight(line,0),((line,span)=>{line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span],span.marker.attachLine(line)})(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null)),++curLine}),marker.collapsed&&doc.iter(from.line,to.line+1,function(line){lineIsHidden(doc,line)&&updateLineHeight(line,0)}),marker.clearOnEnter&&on(marker,"beforeCursorEnter",function(){return marker.clear()}),marker.readOnly&&(sawReadOnlySpans=!0,doc.history.done.length||doc.history.undone.length)&&doc.clearHistory(),marker.collapsed&&(marker.id=++nextMarkerId,marker.atomic=!0),cm){if(updateMaxLine&&(cm.curOp.updateMaxLine=!0),marker.collapsed)regChange(cm,from.line,to.line+1);else if(marker.className||marker.startStyle||marker.endStyle||marker.css||marker.attributes||marker.title)for(var i=from.line;i<=to.line;i++)regLineChange(cm,i,"text");marker.atomic&&reCheckSelection(cm.doc),signalLater(cm,"markerAdded",cm,marker)}}return marker}TextMarker.prototype.clear=function(){if(!this.explicitlyCleared){for(var found,cm=this.doc.cm,withOp=cm&&!cm.curOp,min=(withOp&&startOperation(cm),hasHandler(this,"clear")&&(found=this.find())&&signalLater(this,"clear",found.from,found.to),null),max=null,i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);cm&&!this.collapsed?regLineChange(cm,lineNo(line),"text"):cm&&(null!=span.to&&(max=lineNo(line)),null!=span.from)&&(min=lineNo(line)),line.markedSpans=((spans,span)=>{for(var r,i=0;i<spans.length;++i)spans[i]!=span&&(r=r||[]).push(spans[i]);return r})(line.markedSpans,span),null==span.from&&this.collapsed&&!lineIsHidden(this.doc,line)&&cm&&updateLineHeight(line,textHeight(cm.display))}if(cm&&this.collapsed&&!cm.options.lineWrapping)for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this.lines[i$1]),len=lineLength(visual);len>cm.display.maxLineLength&&(cm.display.maxLine=visual,cm.display.maxLineLength=len,cm.display.maxLineChanged=!0)}null!=min&&cm&&this.collapsed&®Change(cm,min,max+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,cm)&&reCheckSelection(cm.doc),cm&&signalLater(cm,"markerCleared",cm,this,min,max),withOp&&endOperation(cm),this.parent&&this.parent.clear()}},TextMarker.prototype.find=function(side,lineObj){var from,to;null==side&&"bookmark"==this.type&&(side=1);for(var i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);if(null!=span.from&&(from=Pos(lineObj?line:lineNo(line),span.from),-1==side))return from;if(null!=span.to&&(to=Pos(lineObj?line:lineNo(line),span.to),1==side))return to}return from&&{from:from,to:to}},TextMarker.prototype.changed=function(){var this$1=this,pos=this.find(-1,!0),widget=this,cm=this.doc.cm;pos&&cm&&runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line),lineN=findViewForLine(cm,lineN);lineN&&(clearLineMeasurementCacheFor(lineN),cm.curOp.selectionChanged=cm.curOp.forceUpdate=!0),cm.curOp.updateMaxLine=!0,!lineIsHidden(widget.doc,line)&&null!=widget.height&&(lineN=widget.height,widget.height=null,lineN=widgetHeight(widget)-lineN)&&updateLineHeight(line,line.height+lineN),signalLater(cm,"markerChanged",cm,this$1)})},TextMarker.prototype.attachLine=function(line){var op;this.lines.length||!this.doc.cm||(op=this.doc.cm.curOp).maybeHiddenMarkers&&-1!=indexOf(op.maybeHiddenMarkers,this)||(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this),this.lines.push(line)},TextMarker.prototype.detachLine=function(line){this.lines.splice(indexOf(this.lines,line),1),!this.lines.length&&this.doc.cm&&((line=this.doc.cm.curOp).maybeHiddenMarkers||(line.maybeHiddenMarkers=[])).push(this)},eventMixin(TextMarker);var SharedTextMarker=function(markers,primary){this.markers=markers,this.primary=primary;for(var i=0;i<markers.length;++i)markers[i].parent=this};function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent})}function detachSharedMarkers(markers){for(var i=0;i<markers.length;i++)(i=>{var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){return linked.push(d)});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];-1==indexOf(linked,subMarker.doc)&&(subMarker.parent=null,marker.markers.splice(j--,1))}})(i)}SharedTextMarker.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var i=0;i<this.markers.length;++i)this.markers[i].clear();signalLater(this,"clear")}},SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)},eventMixin(SharedTextMarker);function Doc(text,mode,firstLine,lineSep,direction){if(!(this instanceof Doc))return new Doc(text,mode,firstLine,lineSep,direction);null==firstLine&&(firstLine=0),BranchChunk.call(this,[new LeafChunk([new Line("",null)])]),this.first=firstLine,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,firstLine=Pos(this.modeFrontier=this.highlightFrontier=firstLine,0),this.sel=simpleSelection(firstLine),this.history=new History(null),this.id=++nextDocId,this.modeOption=mode,this.lineSep=lineSep,this.direction="rtl"==direction?"rtl":"ltr",this.extend=!1,"string"==typeof text&&(text=this.splitLines(text)),updateDoc(this,{from:firstLine,to:firstLine,text:text}),setSelection(this,simpleSelection(firstLine),sel_dontScroll)}var nextDocId=0,lastDrop=((Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){op?this.iterN(from-this.first,to-from,op):this.iterN(this.first,this.first+this.size,from)},insert:function(at,lines){for(var height=0,i=0;i<lines.length;++i)height+=lines[i].height;this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:!0},!0),this.cm&&scrollToCoords(this.cm,0,0),setSelection(this,simpleSelection(top),sel_dontScroll)}),replaceRange:function(code,from,to,origin){replaceRange(this,code,from=clipPos(this,from),to=to?clipPos(this,to):from,origin)},getRange:function(from,to,lineSep){from=getBetween(this,clipPos(this,from),clipPos(this,to));return!1===lineSep?from:from.join(lineSep||this.lineSeparator())},getLine:function(line){line=this.getLineHandle(line);return line&&line.text},getLineHandle:function(line){if(isLine(this,line))return getLine(this,line)},getLineNumber:lineNo,getLineHandleVisualStart:function(line){return visualLine(line="number"==typeof line?getLine(this,line):line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var range=this.sel.primary(),start=null==start||"head"==start?range.head:"anchor"==start?range.anchor:"end"==start||"to"==start||!1===start?range.to():range.from();return start},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,"number"==typeof line?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){extendSelections(this,clipPosArray(this,map(this.sel.ranges,f)),options)}),setSelections:docMethodOp(function(ranges,primary,options){if(ranges.length){for(var out=[],i=0;i<ranges.length;i++)out[i]=new Range(clipPos(this,ranges[i].anchor),clipPos(this,ranges[i].head));null==primary&&(primary=Math.min(ranges.length-1,this.sel.primIndex)),setSelection(this,normalizeSelection(this.cm,out,primary),options)}}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor))),setSelection(this,normalizeSelection(this.cm,ranges,ranges.length-1),options)}),getSelection:function(lineSep){for(var ranges=this.sel.ranges,i=0;i<ranges.length;i++)var sel=getBetween(this,ranges[i].from(),ranges[i].to()),lines=lines?lines.concat(sel):sel;return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},getSelections:function(lineSep){for(var parts=[],ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());!1!==lineSep&&(sel=sel.join(lineSep||this.lineSeparator())),parts[i]=sel}return parts},replaceSelection:function(code,collapse,origin){for(var dup=[],i=0;i<this.sel.ranges.length;i++)dup[i]=code;this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){for(var changes=[],sel=this.sel,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i];changes[i]={from:range.from(),to:range.to(),text:this.splitLines(code[i]),origin:origin}}for(var collapse=collapse&&"end"!=collapse&&((doc,changes,hint)=>{for(var out=[],newPrev=oldPrev=Pos(doc.first,0),i=0;i<changes.length;i++){var change=changes[i],from=offsetPos(change.from,oldPrev,newPrev),to=offsetPos(changeEnd(change),oldPrev,newPrev),oldPrev=change.to,newPrev=to;"around"==hint?(change=cmp((change=doc.sel.ranges[i]).head,change.anchor)<0,out[i]=new Range(change?to:from,change?from:to)):out[i]=new Range(from,from)}return new Selection(out,doc.sel.primIndex)})(this,changes,collapse),i$1=changes.length-1;0<=i$1;i$1--)makeChange(this,changes[i$1]);collapse?setSelectionReplaceHistory(this,collapse):this.cm&&ensureCursorVisible(this.cm)}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",!0)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",!0)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){for(var hist=this.history,done=0,undone=0,i=0;i<hist.done.length;i++)hist.done[i].ranges||++done;for(var i$1=0;i$1<hist.undone.length;i$1++)hist.undone[i$1].ranges||++undone;return{undo:done,redo:undone}},clearHistory:function(){var this$1=this;this.history=new History(this.history.maxGeneration),linkedDocs(this,function(doc){return doc.history=this$1.history},!0)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(forceSplit){return forceSplit&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,!0),hist.undone=copyHistoryArray(histData.undone.slice(0),null,!0)},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});return!(markers[gutterID]=value)&&isEmpty(markers)&&(line.gutterMarkers=null),1})}),clearGutter:docMethodOp(function(gutterID){var this$1=this;this.iter(function(line){line.gutterMarkers&&line.gutterMarkers[gutterID]&&changeLine(this$1,line,"gutter",function(){return line.gutterMarkers[gutterID]=null,isEmpty(line.gutterMarkers)&&(line.gutterMarkers=null),1})})}),lineInfo:function(line){var n;if("number"==typeof line){if(!isLine(this,line))return null;if(n=line,!(line=getLine(this,line)))return null}else if(null==(n=lineNo(line)))return null;return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass";if(line[prop]){if(classTest(cls).test(line[prop]))return;line[prop]+=" "+cls}else line[prop]=cls;return 1})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass",cur=line[prop];if(cur){if(null==cls)line[prop]=null;else{var found=cur.match(classTest(cls));if(!found)return;var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(found.index&&end!=cur.length?" ":"")+cur.slice(end)||null}return 1}})}),addLineWidget:docMethodOp(function(handle,node,options){return((doc,handle,node,options)=>{var widget=new LineWidget(doc,node,options),cm=doc.cm;return cm&&widget.noHScroll&&(cm.display.alignWidgets=!0),changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);return null==widget.insertAt?widgets.push(widget):widgets.splice(Math.min(widgets.length,Math.max(0,widget.insertAt)),0,widget),widget.line=line,cm&&!lineIsHidden(doc,line)&&(widgets=heightAtLine(line)<doc.scrollTop,updateLineHeight(line,line.height+widgetHeight(widget)),widgets&&addToScrollTop(cm,widget.height),cm.curOp.forceUpdate=!0),1}),cm&&signalLater(cm,"lineWidgetAdded",cm,widget,"number"==typeof handle?handle:lineNo(handle)),widget})(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){options={replacedWith:options&&(null==options.nodeType?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:!1,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};return markText(this,pos=clipPos(this,pos),pos,options,"bookmark")},findMarksAt:function(pos){var markers=[],spans=getLine(this,(pos=clipPos(this,pos)).line).markedSpans;if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];(null==span.from||span.from<=pos.ch)&&(null==span.to||span.to>=pos.ch)&&markers.push(span.marker.parent||span.marker)}return markers},findMarks:function(from,to,filter){from=clipPos(this,from),to=clipPos(this,to);var found=[],lineNo=from.line;return this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans)for(var i=0;i<spans.length;i++){var span=spans[i];null!=span.to&&lineNo==from.line&&from.ch>=span.to||null==span.from&&lineNo!=from.line||null!=span.from&&lineNo==to.line&&span.from>=to.ch||filter&&!filter(span.marker)||found.push(span.marker.parent||span.marker)}++lineNo}),found},getAllMarks:function(){var markers=[];return this.iter(function(line){var sps=line.markedSpans;if(sps)for(var i=0;i<sps.length;++i)null!=sps[i].from&&markers.push(sps[i].marker)}),markers},posFromIndex:function(off){var ch,lineNo=this.first,sepSize=this.lineSeparator().length;return this.iter(function(line){line=line.text.length+sepSize;if(off<line)return ch=off,!0;off-=line,++lineNo}),clipPos(this,Pos(lineNo,ch))},indexFromPos:function(coords){var sepSize,index=(coords=clipPos(this,coords)).ch;return coords.line<this.first||coords.ch<0?0:(sepSize=this.lineSeparator().length,this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize}),index)},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);return doc.scrollTop=this.scrollTop,doc.scrollLeft=this.scrollLeft,doc.sel=this.sel,doc.extend=!1,copyHistory&&(doc.history.undoDepth=this.history.undoDepth,doc.setHistory(this.getHistory())),doc},linkedDoc:function(options){for(var from=this.first,to=this.first+this.size,to=(null!=(options=options||{}).from&&options.from>from&&(from=options.from),null!=options.to&&options.to<to&&(to=options.to),new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep,this.direction)),doc=(options.sharedHist&&(to.history=this.history),(this.linked||(this.linked=[])).push({doc:to,sharedHist:options.sharedHist}),to.linked=[{doc:this,isParent:!0,sharedHist:options.sharedHist}],to),markers=findSharedMarkers(this),i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find(),mFrom=doc.clipPos(pos.from),pos=doc.clipPos(pos.to);cmp(mFrom,pos)&&(mFrom=markText(doc,mFrom,pos,marker.primary,marker.primary.type),marker.markers.push(mFrom),mFrom.parent=marker)}return to},unlinkDoc:function(other){if(other instanceof CodeMirror&&(other=other.doc),this.linked)for(var i=0;i<this.linked.length;++i){var link=this.linked[i];if(link.doc==other){this.linked.splice(i,1),other.unlinkDoc(this),detachSharedMarkers(findSharedMarkers(this));break}}var splitIds;other.history==this.history&&(splitIds=[other.id],linkedDocs(other,function(doc){return splitIds.push(doc.id)},!0),other.history=new History(null),other.history.done=copyHistoryArray(this.history.done,splitIds),other.history.undone=copyHistoryArray(this.history.undone,splitIds))},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){return this.lineSep?str.split(this.lineSep):splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:docMethodOp(function(dir){var cm;(dir="rtl"!=dir?"ltr":dir)!=this.direction&&(this.direction=dir,this.iter(function(line){return line.order=null}),this.cm)&&runInOp(cm=this.cm,function(){setDirectionClass(cm),regChange(cm)})})})).eachLine=Doc.prototype.iter,0);function onDrop(e){var cm=this;if(clearDragCursor(cm),!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e),ie&&(lastDrop=+new Date);var pos=posFromMouse(cm,e,!0),files=e.dataTransfer.files;if(pos&&!cm.isReadOnly())if(files&&files.length&&window.FileReader&&window.File)for(var n=files.length,text=Array(n),read=0,markAsReadAndPasteIfAllFilesAreRead=function(){++read==n&&operation(cm,function(){var change={from:pos=clipPos(cm.doc,pos),to:pos,text:cm.doc.splitLines(text.filter(function(t){return null!=t}).join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change),setSelectionReplaceHistory(cm.doc,simpleSelection(clipPos(cm.doc,pos),clipPos(cm.doc,changeEnd(change))))})()},i=0;i<files.length;i++)((file,i)=>{var reader;cm.options.allowDropFileTypes&&-1==indexOf(cm.options.allowDropFileTypes,file.type)?markAsReadAndPasteIfAllFilesAreRead():((reader=new FileReader).onerror=function(){return markAsReadAndPasteIfAllFilesAreRead()},reader.onload=function(){var content=reader.result;/[\x00-\x08\x0e-\x1f]{2}/.test(content)||(text[i]=content),markAsReadAndPasteIfAllFilesAreRead()},reader.readAsText(file))})(files[i],i);else if(cm.state.draggingText&&-1<cm.doc.sel.contains(pos))cm.state.draggingText(e),setTimeout(function(){return cm.display.input.focus()},20);else try{var selected,text$1=e.dataTransfer.getData("Text");if(text$1){if(cm.state.draggingText&&!cm.state.draggingText.copy&&(selected=cm.listSelections()),setSelectionNoUndo(cm.doc,simpleSelection(pos,pos)),selected)for(var i$1=0;i$1<selected.length;++i$1)replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag");cm.replaceSelection(text$1,"around","paste"),cm.display.input.focus()}}catch(e$1){}}}function clearDragCursor(cm){cm.display.dragCursor&&(cm.display.lineSpace.removeChild(cm.display.dragCursor),cm.display.dragCursor=null)}function forEachCodeMirror(f){if(document.getElementsByClassName){for(var byClass=document.getElementsByClassName("CodeMirror"),editors=[],i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;cm&&editors.push(cm)}editors.length&&editors[0].operation(function(){for(var i=0;i<editors.length;i++)f(editors[i])})}}var globalsRegistered=!1;function ensureGlobalHandlers(){var resizeTimer;globalsRegistered||(on(window,"resize",function(){null==resizeTimer&&(resizeTimer=setTimeout(function(){resizeTimer=null,forEachCodeMirror(onResize)},100))}),on(window,"blur",function(){return forEachCodeMirror(onBlur)}),globalsRegistered=!0)}function onResize(cm){var d=cm.display;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.scrollbarsClipped=!1,cm.setSize()}for(var keyNames={3:"Pause",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",224:"Mod",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},i=0;i<10;i++)keyNames[i+48]=keyNames[i+96]=String(i);for(var i$1=65;i$1<=90;i$1++)keyNames[i$1]=String.fromCharCode(i$1);for(var i$2=1;i$2<=12;i$2++)keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2;var keyMap={};function normalizeKeyName(name){var alt,ctrl,shift,cmd,parts=name.split(/-(?!$)/);name=parts[parts.length-1];for(var i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))cmd=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else{if(!/^s(hift)?$/i.test(mod))throw new Error("Unrecognized modifier name: "+mod);shift=!0}}return alt&&(name="Alt-"+name),ctrl&&(name="Ctrl-"+name),cmd&&(name="Cmd-"+name),name=shift?"Shift-"+name:name}function normalizeKeyMap(keymap){var keyname,prop,copy={};for(keyname in keymap)if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(!/^(name|fallthrough|(de|at)tach)$/.test(keyname)){if("..."!=value)for(var keys=map(keyname.split(" "),normalizeKeyName),i=0;i<keys.length;i++){var val=void 0,name=void 0,val=i==keys.length-1?(name=keys.join(" "),value):(name=keys.slice(0,i+1).join(" "),"..."),prev=copy[name];if(prev){if(prev!=val)throw new Error("Inconsistent bindings for "+name)}else copy[name]=val}delete keymap[keyname]}}for(prop in copy)keymap[prop]=copy[prop];return keymap}function lookupKey(key,map,handle,context){var found=(map=getKeyMap(map)).call?map.call(key,context):map[key];if(!1===found)return"nothing";if("..."===found)return"multi";if(null!=found&&handle(found))return"handled";if(map.fallthrough){if("[object Array]"!=Object.prototype.toString.call(map.fallthrough))return lookupKey(key,map.fallthrough,handle,context);for(var i=0;i<map.fallthrough.length;i++){var result=lookupKey(key,map.fallthrough[i],handle,context);if(result)return result}}}function isModifierKey(value){value="string"==typeof value?value:keyNames[value.keyCode];return"Ctrl"==value||"Alt"==value||"Shift"==value||"Mod"==value}function addModifierNames(name,event,noShift){var base=name;return event.altKey&&"Alt"!=base&&(name="Alt-"+name),(flipCtrlCmd?event.metaKey:event.ctrlKey)&&"Ctrl"!=base&&(name="Ctrl-"+name),(flipCtrlCmd?event.ctrlKey:event.metaKey)&&"Mod"!=base&&(name="Cmd-"+name),name=!noShift&&event.shiftKey&&"Shift"!=base?"Shift-"+name:name}function keyName(event,noShift){var name;return!(presto&&34==event.keyCode&&event.char||null==(name=keyNames[event.keyCode])||event.altGraphKey)&&addModifierNames(name=3==event.keyCode&&event.code?event.code:name,event,noShift)}function getKeyMap(val){return"string"==typeof val?keyMap[val]:val}function deleteNearSelection(cm,compute){for(var ranges=cm.doc.sel.ranges,kill=[],i=0;i<ranges.length;i++){for(var toKill=compute(ranges[i]);kill.length&&cmp(toKill.from,lst(kill).to)<=0;){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}kill.push(toKill)}runInOp(cm,function(){for(var i=kill.length-1;0<=i;i--)replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");ensureCursorVisible(cm)})}function moveCharLogically(line,ch,dir){ch=skipExtendingChars(line.text,ch+dir,dir);return ch<0||ch>line.text.length?null:ch}function moveLogically(line,start,dir){line=moveCharLogically(line,start.ch,dir);return null==line?null:new Pos(start.line,line,dir<0?"after":"before")}function endOfLine(visually,cm,lineObj,lineNo,dir){if(visually){"rtl"==cm.doc.direction&&(dir=-dir);var sticky,prep,ch,targetTop,visually=getOrder(lineObj,cm.doc.direction);if(visually)return sticky=dir<0==(1==(visually=dir<0?lst(visually):visually[0]).level)?"after":"before",0<visually.level||"rtl"==cm.doc.direction?(prep=prepareMeasureForLine(cm,lineObj),ch=dir<0?lineObj.text.length-1:0,targetTop=measureCharPrepared(cm,prep,ch).top,ch=findFirst(function(ch){return measureCharPrepared(cm,prep,ch).top==targetTop},dir<0==(1==visually.level)?visually.from:visually.to-1,ch),"before"==sticky&&(ch=moveCharLogically(lineObj,ch,1))):ch=dir<0?visually.to:visually.from,new Pos(lineNo,ch,sticky)}return new Pos(lineNo,dir<0?lineObj.text.length:0,dir<0?"before":"after")}function moveVisually(cm,line,start,dir){var bidi=getOrder(line,cm.doc.direction);if(!bidi)return moveLogically(line,start,dir);start.ch>=line.text.length?(start.ch=line.text.length,start.sticky="before"):start.ch<=0&&(start.ch=0,start.sticky="after");var partPos=getBidiPartAt(bidi,start.ch,start.sticky),part=bidi[partPos];if("ltr"==cm.doc.direction&&part.level%2==0&&(0<dir?part.to>start.ch:part.from<start.ch))return moveLogically(line,start,dir);function mv(pos,dir){return moveCharLogically(line,pos instanceof Pos?pos.ch:pos,dir)}function getWrappedLineExtent(ch){return cm.options.lineWrapping?(prep=prep||prepareMeasureForLine(cm,line),wrappedLineExtentChar(cm,line,prep,ch)):{begin:0,end:line.text.length}}var prep,wrappedLineExtent=getWrappedLineExtent("before"==start.sticky?mv(start,-1):start.ch);if("rtl"==cm.doc.direction||1==part.level){var moveInStorageOrder=1==part.level==dir<0,ch=mv(start,moveInStorageOrder?1:-1);if(null!=ch&&(moveInStorageOrder?ch<=part.to&&ch<=wrappedLineExtent.end:ch>=part.from&&ch>=wrappedLineExtent.begin))return new Pos(start.line,ch,moveInStorageOrder?"before":"after")}function searchInVisualLine(partPos,dir,wrappedLineExtent){for(var getRes=function(ch,moveInStorageOrder){return moveInStorageOrder?new Pos(start.line,mv(ch,1),"before"):new Pos(start.line,ch,"after")};0<=partPos&&partPos<bidi.length;partPos+=dir){var part=bidi[partPos],moveInStorageOrder=0<dir==(1!=part.level),ch=moveInStorageOrder?wrappedLineExtent.begin:mv(wrappedLineExtent.end,-1);if(part.from<=ch&&ch<part.to)return getRes(ch,moveInStorageOrder);if(ch=moveInStorageOrder?part.from:mv(part.to,-1),wrappedLineExtent.begin<=ch&&ch<wrappedLineExtent.end)return getRes(ch,moveInStorageOrder)}}part=searchInVisualLine(partPos+dir,dir,wrappedLineExtent);return part||(null==(ch=0<dir?wrappedLineExtent.end:mv(wrappedLineExtent.begin,-1))||0<dir&&ch==line.text.length||!(part=searchInVisualLine(0<dir?0:bidi.length-1,dir,getWrappedLineExtent(ch)))?null:part)}keyMap.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},keyMap.default=mac?keyMap.macDefault:keyMap.pcDefault;var commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll)},killLine:function(cm){return deleteNearSelection(cm,function(range){var len;return range.empty()?(len=getLine(cm.doc,range.head.line).text.length,range.head.ch==len&&range.head.line<cm.lastLine()?{from:range.head,to:Pos(range.head.line+1,0)}:{from:range.head,to:Pos(range.head.line,len)}):{from:range.from(),to:range.to()}})},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))}})},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:range.from()}})},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5;return{from:cm.coordsChar({left:0,top:top},"div"),to:range.from()}})},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,top=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:top}})},undo:function(cm){return cm.undo()},redo:function(cm){return cm.redo()},undoSelection:function(cm){return cm.undoSelection()},redoSelection:function(cm){return cm.redoSelection()},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0))},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()))},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head)},{origin:"+move",bias:1})},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return((cm,lineN)=>{var line=getLine(cm.doc,lineN),visual=(line=>{for(var merged;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return line})(line);return visual!=line&&(lineN=lineNo(visual)),endOfLine(!0,cm,line,lineN,-1)})(cm,range.head.line)},{origin:"+move",bias:-1})},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){range=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:range},"div")},sel_move)},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){range=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:range},"div")},sel_move)},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.cursorCoords(range.head,"div").top+5,top=cm.coordsChar({left:0,top:top},"div");return top.ch<cm.getLine(top.line).search(/\S/)?lineStartSmart(cm,range.head):top},sel_move)},goLineUp:function(cm){return cm.moveV(-1,"line")},goLineDown:function(cm){return cm.moveV(1,"line")},goPageUp:function(cm){return cm.moveV(-1,"page")},goPageDown:function(cm){return cm.moveV(1,"page")},goCharLeft:function(cm){return cm.moveH(-1,"char")},goCharRight:function(cm){return cm.moveH(1,"char")},goColumnLeft:function(cm){return cm.moveH(-1,"column")},goColumnRight:function(cm){return cm.moveH(1,"column")},goWordLeft:function(cm){return cm.moveH(-1,"word")},goGroupRight:function(cm){return cm.moveH(1,"group")},goGroupLeft:function(cm){return cm.moveH(-1,"group")},goWordRight:function(cm){return cm.moveH(1,"word")},delCharBefore:function(cm){return cm.deleteH(-1,"codepoint")},delCharAfter:function(cm){return cm.deleteH(1,"char")},delWordBefore:function(cm){return cm.deleteH(-1,"word")},delWordAfter:function(cm){return cm.deleteH(1,"word")},delGroupBefore:function(cm){return cm.deleteH(-1,"group")},delGroupAfter:function(cm){return cm.deleteH(1,"group")},indentAuto:function(cm){return cm.indentSelection("smart")},indentMore:function(cm){return cm.indentSelection("add")},indentLess:function(cm){return cm.indentSelection("subtract")},insertTab:function(cm){return cm.replaceSelection("\t")},insertSoftTab:function(cm){for(var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize,i=0;i<ranges.length;i++){var pos=ranges[i].from(),pos=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(spaceStr(tabSize-pos%tabSize))}cm.replaceSelections(spaces)},defaultTab:function(cm){cm.somethingSelected()?cm.indentSelection("add"):cm.execCommand("insertTab")},transposeChars:function(cm){return runInOp(cm,function(){for(var cur,line,prev,ranges=cm.listSelections(),newSel=[],i=0;i<ranges.length;i++)ranges[i].empty()&&(cur=ranges[i].head,(line=getLine(cm.doc,cur.line).text)&&(0<(cur=cur.ch==line.length?new Pos(cur.line,cur.ch-1):cur).ch?(cur=new Pos(cur.line,cur.ch+1),cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose")):cur.line>cm.doc.first&&(prev=getLine(cm.doc,cur.line-1).text)&&(cur=new Pos(cur.line,1),cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose"))),newSel.push(new Range(cur,cur)));cm.setSelections(newSel)})},newlineAndIndent:function(cm){return runInOp(cm,function(){for(var i=(sels=cm.listSelections()).length-1;0<=i;i--)cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input");for(var sels=cm.listSelections(),i$1=0;i$1<sels.length;i$1++)cm.indentLine(sels[i$1].from().line,null,!0);ensureCursorVisible(cm)})},openLine:function(cm){return cm.replaceSelection("\n","start")},toggleOverwrite:function(cm){return cm.toggleOverwrite()}};function lineStart(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLine(line);return endOfLine(!0,cm,visual,lineN=visual!=line?lineNo(visual):lineN,1)}function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line),line=getLine(cm.doc,start.line),cm=getOrder(line,cm.doc.direction);return cm&&0!=cm[0].level?start:(cm=Math.max(start.ch,line.text.search(/\S/)),line=pos.line==start.line&&pos.ch<=cm&&pos.ch,Pos(start.line,line?0:cm,start.sticky))}function doHandleBinding(cm,bound,dropShift){if("string"==typeof bound&&!(bound=commands[bound]))return!1;cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),dropShift&&(cm.display.shift=!1),done=bound(cm)!=Pass}finally{cm.display.shift=prevShift,cm.state.suppressEdits=!1}return done}var stopSeq=new Delayed;function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name))return"handled";if(/\'$/.test(name)?cm.state.keySeq=null:stopSeq.set(50,function(){cm.state.keySeq==seq&&(cm.state.keySeq=null,cm.display.input.reset())}),dispatchKeyInner(cm,seq+" "+name,e,handle))return!0}return dispatchKeyInner(cm,name,e,handle)}function dispatchKeyInner(cm,name,e,handle){handle=((cm,name,handle)=>{for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result)return result}return cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm)||lookupKey(name,cm.options.keyMap,handle,cm)})(cm,name,handle);return"multi"==handle&&(cm.state.keySeq=name),"handled"==handle&&signalLater(cm,"keyHandled",cm,name,e),"handled"!=handle&&"multi"!=handle||(e_preventDefault(e),restartBlink(cm)),!!handle}function handleKeyBinding(cm,e){var name=keyName(e,!0);return!!name&&(e.shiftKey&&!cm.state.keySeq?dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,!0)})||dispatchKey(cm,name,e,function(b){if("string"==typeof b?/^go[A-Z]/.test(b):b.motion)return doHandleBinding(cm,b)}):dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b)}))}var lastStoppedKey=null;function onKeyDown(e){var code,handled,cm=this;e.target&&e.target!=cm.display.input.getField()||(cm.curOp.focus=activeElt(),signalDOMEvent(cm,e))||(ie&&ie_version<11&&27==e.keyCode&&(e.returnValue=!1),cm.display.shift=16==(code=e.keyCode)||e.shiftKey,handled=handleKeyBinding(cm,e),presto&&(lastStoppedKey=handled?code:null,!handled)&&88==code&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)&&cm.replaceSelection("",null,"cut"),gecko&&!mac&&!handled&&46==code&&e.shiftKey&&!e.ctrlKey&&document.execCommand&&document.execCommand("cut"),18!=code)||/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)||(cm=>{var lineDiv=cm.display.lineDiv;function up(e){18!=e.keyCode&&e.altKey||(rmClass(lineDiv,"CodeMirror-crosshair"),off(document,"keyup",up),off(document,"mouseover",up))}addClass(lineDiv,"CodeMirror-crosshair"),on(document,"keyup",up),on(document,"mouseover",up)})(cm)}function onKeyUp(e){16==e.keyCode&&(this.doc.sel.shift=!1),signalDOMEvent(this,e)}function onKeyPress(e){var charCode,keyCode,cm=this;e.target&&e.target!=cm.display.input.getField()||eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey||(keyCode=e.keyCode,charCode=e.charCode,presto&&keyCode==lastStoppedKey?(lastStoppedKey=null,e_preventDefault(e)):presto&&(!e.which||e.which<10)&&handleKeyBinding(cm,e)||"\b"==(keyCode=String.fromCharCode(null==charCode?keyCode:charCode))||((cm,e,ch)=>dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,!0)}))(cm,e,keyCode)||cm.display.input.onKeyPress(e))}var lastClick,lastDoubleClick,PastClick=function(time,pos,button){this.time=time,this.pos=pos,this.button=button};function onMouseDown(e){var pos,button,repeat,cm=this,display=cm.display;signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch()||(display.input.ensurePolled(),display.shift=e.shiftKey,eventInWidget(display,e)?webkit||(display.scroller.draggable=!1,setTimeout(function(){return display.scroller.draggable=!0},100)):clickInGutter(cm,e)||(pos=posFromMouse(cm,e),button=e_button(e),repeat=pos?((pos,button)=>{var now=+new Date;return lastDoubleClick&&lastDoubleClick.compare(now,pos,button)?(lastClick=lastDoubleClick=null,"triple"):lastClick&&lastClick.compare(now,pos,button)?(lastDoubleClick=new PastClick(now,pos,button),lastClick=null,"double"):(lastClick=new PastClick(now,pos,button),lastDoubleClick=null,"single")})(pos,button):"single",window.focus(),1==button&&cm.state.selectingText&&cm.state.selectingText(e),pos&&((cm,button,pos,repeat,event)=>{var name="Click";return"double"==repeat?name="Double"+name:"triple"==repeat&&(name="Triple"+name),dispatchKey(cm,addModifierNames(name=(1==button?"Left":2==button?"Middle":"Right")+name,event),event,function(bound){if(!(bound="string"==typeof bound?commands[bound]:bound))return!1;var done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),done=bound(cm,pos)!=Pass}finally{cm.state.suppressEdits=!1}return done})})(cm,button,pos,repeat,e))||(1==button?pos?((cm,pos,repeat,event)=>{ie?setTimeout(bind(ensureFocus,cm),0):cm.curOp.focus=activeElt();var behavior=((cm,repeat,event)=>{var rect,option=cm.getOption("configureMouse");return null==(option=option?option(cm,repeat,event):{}).unit&&(rect=chromeOS?event.shiftKey&&event.metaKey:event.altKey,option.unit=rect?"rectangle":"single"==repeat?"char":"double"==repeat?"word":"line"),null!=option.extend&&!cm.doc.extend||(option.extend=cm.doc.extend||event.shiftKey),null==option.addNew&&(option.addNew=mac?event.metaKey:event.ctrlKey),null==option.moveOnDrag&&(option.moveOnDrag=!(mac?event.altKey:event.ctrlKey)),option})(cm,repeat,event),sel=cm.doc.sel;(cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&"single"==repeat&&-1<(repeat=sel.contains(pos))&&(cmp((repeat=sel.ranges[repeat]).from(),pos)<0||0<pos.xRel)&&(0<cmp(repeat.to(),pos)||pos.xRel<0)?(cm,event,pos,behavior)=>{var display=cm.display,moved=!1,dragEnd=operation(cm,function(e){webkit&&(display.scroller.draggable=!1),cm.state.draggingText=!1,cm.state.delayingBlurEvent&&(cm.hasFocus()?cm.state.delayingBlurEvent=!1:delayBlurEvent(cm)),off(display.wrapper.ownerDocument,"mouseup",dragEnd),off(display.wrapper.ownerDocument,"mousemove",mouseMove),off(display.scroller,"dragstart",dragStart),off(display.scroller,"drop",dragEnd),moved||(e_preventDefault(e),behavior.addNew||extendSelection(cm.doc,pos,null,null,behavior.extend),webkit&&!safari||ie&&9==ie_version?setTimeout(function(){display.wrapper.ownerDocument.body.focus({preventScroll:!0}),display.input.focus()},20):display.input.focus())}),mouseMove=function(e2){moved=moved||10<=Math.abs(event.clientX-e2.clientX)+Math.abs(event.clientY-e2.clientY)},dragStart=function(){return moved=!0};webkit&&(display.scroller.draggable=!0),(cm.state.draggingText=dragEnd).copy=!behavior.moveOnDrag,on(display.wrapper.ownerDocument,"mouseup",dragEnd),on(display.wrapper.ownerDocument,"mousemove",mouseMove),on(display.scroller,"dragstart",dragStart),on(display.scroller,"drop",dragEnd),cm.state.delayingBlurEvent=!0,setTimeout(function(){return display.input.focus()},20),display.scroller.dragDrop&&display.scroller.dragDrop()}:(cm,event,start,behavior)=>{ie&&delayBlurEvent(cm);var display=cm.display,doc=cm.doc;e_preventDefault(event);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges,lastPos=(behavior.addNew&&!behavior.extend?(ourIndex=doc.sel.contains(start),ourRange=-1<ourIndex?ranges[ourIndex]:new Range(start,start)):(ourRange=doc.sel.primary(),ourIndex=doc.sel.primIndex),"rectangle"==behavior.unit?(behavior.addNew||(ourRange=new Range(start,start)),start=posFromMouse(cm,event,!0,!0),ourIndex=-1):(event=rangeForUnit(cm,start,behavior.unit),ourRange=behavior.extend?extendRange(ourRange,event.anchor,event.head,behavior.extend):event),behavior.addNew?-1==ourIndex?(ourIndex=ranges.length,setSelection(doc,normalizeSelection(cm,ranges.concat([ourRange]),ourIndex),{scroll:!1,origin:"*mouse"})):1<ranges.length&&ranges[ourIndex].empty()&&"char"==behavior.unit&&!behavior.extend?(setSelection(doc,normalizeSelection(cm,ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:!1,origin:"*mouse"}),startSel=doc.sel):replaceOneSelection(doc,ourIndex,ourRange,sel_mouse):(setSelection(doc,new Selection([ourRange],ourIndex=0),sel_mouse),startSel=doc.sel),start);function extendTo(pos){if(0!=cmp(lastPos,pos))if(lastPos=pos,"rectangle"==behavior.unit){for(var ranges=[],tabSize=cm.options.tabSize,startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize),posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize),left=Math.min(startCol,posCol),right=Math.max(startCol,posCol),line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);left==right?ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos))):text.length>leftPos&&ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}ranges.length||ranges.push(new Range(start,start)),setSelection(doc,normalizeSelection(cm,startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:!1}),cm.scrollIntoView(pos)}else{var head,startCol=ourRange,posCol=rangeForUnit(cm,pos,behavior.unit),pos=startCol.anchor,pos=0<cmp(posCol.anchor,pos)?(head=posCol.head,minPos(startCol.from(),posCol.anchor)):(head=posCol.anchor,maxPos(startCol.to(),posCol.head)),startCol=startSel.ranges.slice(0);startCol[ourIndex]=((cm,range)=>{var index,part,boundary,anchor=range.anchor,head=range.head,anchorLine=getLine(cm.doc,anchor.line);return 0==cmp(anchor,head)&&anchor.sticky==head.sticky||!(anchorLine=getOrder(anchorLine))||(index=getBidiPartAt(anchorLine,anchor.ch,anchor.sticky),(part=anchorLine[index]).from!=anchor.ch&&part.to!=anchor.ch)||0==(boundary=index+(part.from==anchor.ch==(1!=part.level)?0:1))||boundary==anchorLine.length||(index=(part=head.line!=anchor.line?0<(head.line-anchor.line)*("ltr"==cm.doc.direction?1:-1):(cm=getBidiPartAt(anchorLine,head.ch,head.sticky),index=cm-index||(head.ch-anchor.ch)*(1==part.level?-1:1),cm==boundary-1||cm==boundary?index<0:0<index))==(1==(cm=anchorLine[boundary+(part?-1:0)]).level),anchorLine=index?cm.from:cm.to,boundary=index?"after":"before",anchor.ch==anchorLine&&anchor.sticky==boundary)?range:new Range(new Pos(anchor.line,anchorLine,boundary),head)})(cm,new Range(clipPos(doc,pos),head)),setSelection(doc,normalizeSelection(cm,startCol,ourIndex),sel_mouse)}}var editorSize=display.wrapper.getBoundingClientRect(),counter=0;function done(e){cm.state.selectingText=!1,counter=1/0,e&&(e_preventDefault(e),display.input.focus()),off(display.wrapper.ownerDocument,"mousemove",move),off(display.wrapper.ownerDocument,"mouseup",up),doc.history.lastSelOrigin=null}var move=operation(cm,function(e){(0!==e.buttons&&e_button(e)?function extend(e){var visible,outside,curCount=++counter,cur=posFromMouse(cm,e,!0,"rectangle"==behavior.unit);cur&&(0!=cmp(cur,lastPos)?(cm.curOp.focus=activeElt(),extendTo(cur),visible=visibleLines(display,doc),(cur.line>=visible.to||cur.line<visible.from)&&setTimeout(operation(cm,function(){counter==curCount&&extend(e)}),150)):(outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0)&&setTimeout(operation(cm,function(){counter==curCount&&(display.scroller.scrollTop+=outside,extend(e))}),50))}:done)(e)}),up=operation(cm,done);cm.state.selectingText=up,on(display.wrapper.ownerDocument,"mousemove",move),on(display.wrapper.ownerDocument,"mouseup",up)})(cm,event,pos,behavior)})(cm,pos,repeat,e):e_target(e)==display.scroller&&e_preventDefault(e):2==button?(pos&&extendSelection(cm.doc,pos),setTimeout(function(){return display.input.focus()},20)):3==button&&(captureRightClick?cm.display.input.onContextMenu(e):delayBlurEvent(cm))))}function rangeForUnit(cm,pos,unit){return"char"==unit?new Range(pos,pos):"word"==unit?cm.findWordAt(pos):"line"==unit?new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0))):(unit=unit(cm,pos),new Range(unit.from,unit.to))}function gutterEvent(cm,e,type,prevent){var mX,mY;if(e.touches)mX=e.touches[0].clientX,mY=e.touches[0].clientY;else try{mX=e.clientX,mY=e.clientY}catch(e$1){return!1}if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right))return!1;prevent&&e_preventDefault(e);var display=cm.display,prevent=display.lineDiv.getBoundingClientRect();if(mY>prevent.bottom||!hasHandler(cm,type))return e_defaultPrevented(e);mY-=prevent.top-display.viewOffset;for(var i=0;i<cm.display.gutterSpecs.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX)return signal(cm,type,cm,lineAtHeight(cm.doc,mY),cm.display.gutterSpecs[i].className,e),e_defaultPrevented(e)}}function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",!0)}function onContextMenu(cm,e){eventInWidget(cm.display,e)||((cm,e)=>hasHandler(cm,"gutterContextMenu")&&gutterEvent(cm,e,"gutterContextMenu",!1))(cm,e)||signalDOMEvent(cm,e,"contextmenu")||captureRightClick||cm.display.input.onContextMenu(e)}function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+cm.options.theme.replace(/(^|\s)\s*/g," cm-s-"),clearCaches(cm)}PastClick.prototype.compare=function(time,pos,button){return this.time+400>time&&0==cmp(pos,this.pos)&&button==this.button};var Init={toString:function(){return"CodeMirror.Init"}},defaults={},optionHandlers={};function dragDropChanged(cm,value,old){!value!=!(old&&old!=Init)&&(old=cm.display.dragFunctions,(value=value?on:off)(cm.display.scroller,"dragstart",old.start),value(cm.display.scroller,"dragenter",old.enter),value(cm.display.scroller,"dragover",old.over),value(cm.display.scroller,"dragleave",old.leave),value(cm.display.scroller,"drop",old.drop))}function wrappingChanged(cm){cm.options.lineWrapping?(addClass(cm.display.wrapper,"CodeMirror-wrap"),cm.display.sizer.style.minWidth="",cm.display.sizerWidth=null):(rmClass(cm.display.wrapper,"CodeMirror-wrap"),findMaxLine(cm)),estimateLineHeights(cm),regChange(cm),clearCaches(cm),setTimeout(function(){return updateScrollbars(cm)},100)}function CodeMirror(place,options){var this$1=this;if(!(this instanceof CodeMirror))return new CodeMirror(place,options);this.options=options=options?copyObj(options):{},copyObj(defaults,options,!1);var opt,doc=options.value,input=("string"==typeof doc?doc=new Doc(doc,options.mode,null,options.lineSeparator,options.direction):options.mode&&(doc.modeOption=options.mode),this.doc=doc,new CodeMirror.inputStyles[options.inputStyle](this)),place=this.display=new Display(place,doc,input,options),cm=(themeChanged(place.wrapper.CodeMirror=this),options.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),initScrollbars(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Delayed,keySeq:null,specialChars:null},options.autofocus&&!mobile&&place.input.focus(),ie&&ie_version<11&&setTimeout(function(){return this$1.display.input.reset(!0)},20),this),d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown)),on(d.scroller,"dblclick",ie&&ie_version<11?operation(cm,function(e){var pos;signalDOMEvent(cm,e)||!(pos=posFromMouse(cm,e))||clickInGutter(cm,e)||eventInWidget(cm.display,e)||(e_preventDefault(e),e=cm.findWordAt(pos),extendSelection(cm.doc,e.anchor,e.head))}):function(e){return signalDOMEvent(cm,e)||e_preventDefault(e)}),on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e)}),on(d.input.getField(),"contextmenu",function(e){d.scroller.contains(e.target)||onContextMenu(cm,e)});var touchFinished,prevTouch={end:0};function finishTouch(){d.activeTouch&&(touchFinished=setTimeout(function(){return d.activeTouch=null},1e3),(prevTouch=d.activeTouch).end=+new Date)}function farAway(touch,other){var dx;return null==other.left||400<(dx=other.left-touch.left)*dx+(dx=other.top-touch.top)*dx}on(d.scroller,"touchstart",function(e){var now;signalDOMEvent(cm,e)||(e=>1==e.touches.length&&(e=e.touches[0]).radiusX<=1&&e.radiusY<=1)(e)||clickInGutter(cm,e)||(d.input.ensurePolled(),clearTimeout(touchFinished),now=+new Date,d.activeTouch={start:now,moved:!1,prev:now-prevTouch.end<=300?prevTouch:null},1==e.touches.length&&(d.activeTouch.left=e.touches[0].pageX,d.activeTouch.top=e.touches[0].pageY))}),on(d.scroller,"touchmove",function(){d.activeTouch&&(d.activeTouch.moved=!0)}),on(d.scroller,"touchend",function(e){var pos,touch=d.activeTouch;touch&&!eventInWidget(d,e)&&null!=touch.left&&!touch.moved&&new Date-touch.start<300&&(pos=cm.coordsChar(d.activeTouch,"page"),touch=!touch.prev||farAway(touch,touch.prev)?new Range(pos,pos):!touch.prev.prev||farAway(touch,touch.prev.prev)?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0))),cm.setSelection(touch.anchor,touch.head),cm.focus(),e_preventDefault(e)),finishTouch()}),on(d.scroller,"touchcancel",finishTouch),on(d.scroller,"scroll",function(){d.scroller.clientHeight&&(updateScrollTop(cm,d.scroller.scrollTop),setScrollLeft(cm,d.scroller.scrollLeft,!0),signal(cm,"scroll",cm))}),on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e)}),on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e)}),on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0}),d.dragFunctions={enter:function(e){signalDOMEvent(cm,e)||e_stop(e)},over:function(e){signalDOMEvent(cm,e)||(((cm,e)=>{(e=posFromMouse(cm,e))&&(drawSelectionCursor(cm,e,e=document.createDocumentFragment()),cm.display.dragCursor||(cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)),removeChildrenAndAdd(cm.display.dragCursor,e))})(cm,e),e_stop(e))},start:function(e){return((cm,e)=>{var img;ie&&(!cm.state.draggingText||+new Date-lastDrop<100)?e_stop(e):signalDOMEvent(cm,e)||eventInWidget(cm.display,e)||(e.dataTransfer.setData("Text",cm.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!safari&&((img=elt("img",null,null,"position: fixed; left: 0; top: 0;")).src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",presto&&(img.width=img.height=1,cm.display.wrapper.appendChild(img),img._top=img.offsetTop),e.dataTransfer.setDragImage(img,0,0),presto)&&img.parentNode.removeChild(img))})(cm,e)},drop:operation(cm,onDrop),leave:function(e){signalDOMEvent(cm,e)||clearDragCursor(cm)}};input=d.input.getField();for(opt in on(input,"keyup",function(e){return onKeyUp.call(cm,e)}),on(input,"keydown",operation(cm,onKeyDown)),on(input,"keypress",operation(cm,onKeyPress)),on(input,"focus",function(e){return onFocus(cm,e)}),on(input,"blur",function(e){return onBlur(cm,e)}),ensureGlobalHandlers(),startOperation(this),this.curOp.forceUpdate=!0,attachDoc(this,doc),options.autofocus&&!mobile||this.hasFocus()?setTimeout(function(){this$1.hasFocus()&&!this$1.state.focused&&onFocus(this$1)},20):onBlur(this),optionHandlers)optionHandlers.hasOwnProperty(opt)&&optionHandlers[opt](this,options[opt],Init);maybeUpdateLineNumberWidth(this),options.finishInit&&options.finishInit(this);for(var i=0;i<initHooks.length;++i)initHooks[i](this);endOperation(this),webkit&&options.lineWrapping&&"optimizelegibility"==getComputedStyle(place.lineDiv).textRendering&&(place.lineDiv.style.textRendering="auto")}CodeMirror.defaults=defaults,CodeMirror.optionHandlers=optionHandlers;var initHooks=[];function indentLine(cm,n,how,aggressive){var state,doc=cm.doc,tabSize=("smart"==(how=null==how?"add":how)&&(doc.mode.indent?state=getContextBefore(cm,n).state:how="prev"),cm.options.tabSize),line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize),curSpaceString=(line.stateAfter&&(line.stateAfter=null),line.text.match(/^\s*/)[0]);if(aggressive||/\S/.test(line.text)){if("smart"==how&&((indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text))==Pass||150<indentation)){if(!aggressive)return;how="prev"}}else indentation=0,how="not";"prev"==how?indentation=n>doc.first?countColumn(getLine(doc,n-1).text,null,tabSize):0:"add"==how?indentation=curSpace+cm.options.indentUnit:"subtract"==how?indentation=curSpace-cm.options.indentUnit:"number"==typeof how&&(indentation=curSpace+how);var indentation=Math.max(0,indentation),indentString="",pos=0;if(cm.options.indentWithTabs)for(var i=Math.floor(indentation/tabSize);i;--i)pos+=tabSize,indentString+="\t";if(pos<indentation&&(indentString+=spaceStr(indentation-pos)),indentString!=curSpaceString)return replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input"),!(line.stateAfter=null);for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1];if(range.head.line==n&&range.head.ch<curSpaceString.length){range=Pos(n,curSpaceString.length);replaceOneSelection(doc,i$1,new Range(range,range));break}}}CodeMirror.defineInitHook=function(f){return initHooks.push(f)};var lastCopied=null;function setLastCopied(newLastCopied){lastCopied=newLastCopied}function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc,recent=(cm.display.shift=!1,sel=sel||doc.sel,+new Date-200),paste="paste"==origin||cm.state.pasteIncoming>recent,textLines=splitLinesAuto(inserted),multiPaste=null;if(paste&&1<sel.ranges.length)if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0)for(var multiPaste=[],i=0;i<lastCopied.text.length;i++)multiPaste.push(doc.splitLines(lastCopied.text[i]))}else textLines.length==sel.ranges.length&&cm.options.pasteLinesPerSelection&&(multiPaste=map(textLines,function(l){return[l]}));for(var updateInput=cm.curOp.updateInput,i$1=sel.ranges.length-1;0<=i$1;i$1--){var range=sel.ranges[i$1],from=range.from(),to=range.to(),range=(range.empty()&&(deleted&&0<deleted?from=Pos(from.line,from.ch-deleted):cm.state.overwrite&&!paste?to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length)):paste&&lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==textLines.join("\n")&&(from=to=Pos(from.line,0))),{from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming>recent?"cut":"+input")});makeChange(cm.doc,range),signalLater(cm,"inputRead",cm,range)}inserted&&!paste&&triggerElectric(cm,inserted),ensureCursorVisible(cm),cm.curOp.updateInput<2&&(cm.curOp.updateInput=updateInput),cm.curOp.typing=!0,cm.state.pasteIncoming=cm.state.cutIncoming=-1}function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text");return pasted&&(e.preventDefault(),cm.isReadOnly()||cm.options.disableInput||runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste")}),1)}function triggerElectric(cm,inserted){if(cm.options.electricChars&&cm.options.smartIndent)for(var sel=cm.doc.sel,i=sel.ranges.length-1;0<=i;i--){var range=sel.ranges[i];if(!(100<range.head.ch||i&&sel.ranges[i-1].head.line==range.head.line)){var mode=cm.getModeAt(range.head),indented=!1;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)if(-1<inserted.indexOf(mode.electricChars.charAt(j))){indented=indentLine(cm,range.head.line,"smart");break}}else mode.electricInput&&mode.electricInput.test(getLine(cm.doc,range.head.line).text.slice(0,range.head.ch))&&(indented=indentLine(cm,range.head.line,"smart"));indented&&signalLater(cm,"electricInput",cm,range.head.line)}}}function copyableRanges(cm){for(var text=[],ranges=[],i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line,line={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(line),text.push(cm.getRange(line.anchor,line.head))}return{text:text,ranges:ranges}}function disableBrowserMagic(field,spellcheck,autocorrect,autocapitalize){field.setAttribute("autocorrect",autocorrect?"":"off"),field.setAttribute("autocapitalize",autocapitalize?"":"off"),field.setAttribute("spellcheck",!!spellcheck)}function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");return webkit?te.style.width="1000px":te.setAttribute("wrap","off"),ios&&(te.style.border="1px solid black"),disableBrowserMagic(te),div}function findPosH(doc,pos,dir,unit,visually){var oldPos=pos,origDir=dir,lineObj=getLine(doc,pos.line),lineDir=visually&&"rtl"==doc.direction?-dir:dir;function moveOnce(boundToLine){var ch;if(null==(ch="codepoint"==unit?(ch=lineObj.text.charCodeAt(pos.ch+(0<unit?0:-1)),isNaN(ch)?null:new Pos(pos.line,Math.max(0,Math.min(lineObj.text.length,pos.ch+dir*(55296<=ch&&ch<56320?2:1))),-dir)):visually?moveVisually(doc.cm,lineObj,pos,dir):moveLogically(lineObj,pos,dir))){if(boundToLine||(boundToLine=pos.line+lineDir)<doc.first||boundToLine>=doc.first+doc.size||(pos=new Pos(boundToLine,pos.ch,pos.sticky),!(lineObj=getLine(doc,boundToLine))))return;pos=endOfLine(visually,doc.cm,lineObj,pos.line,lineDir)}else pos=ch;return 1}if("char"==unit||"codepoint"==unit)moveOnce();else if("column"==unit)moveOnce(!0);else if("word"==unit||"group"==unit)for(var sawType=null,group="group"==unit,helper=doc.cm&&doc.cm.getHelper(pos,"wordChars"),first=!0;!(dir<0)||moveOnce(!first);first=!1){var cur=lineObj.text.charAt(pos.ch)||"\n",cur=isWordChar(cur,helper)?"w":group&&"\n"==cur?"n":!group||/\s/.test(cur)?null:"p";if(group&&!first&&(cur=cur||"s"),sawType&&sawType!=cur){dir<0&&(dir=1,moveOnce(),pos.sticky="after");break}if(cur&&(sawType=cur),0<dir&&!moveOnce(!first))break}origDir=skipAtomic(doc,pos,oldPos,origDir,!0);return equalCursorPos(oldPos,origDir)&&(origDir.hitSide=!0),origDir}function findPosV(cm,pos,dir,unit){var pageSize,y,target,doc=cm.doc,x=pos.left;for("page"==unit?(pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),pageSize=Math.max(pageSize-.5*textHeight(cm.display),3),y=(0<dir?pos.bottom:pos.top)+dir*pageSize):"line"==unit&&(y=0<dir?pos.bottom+3:pos.top-3);(target=coordsChar(cm,x,y)).outside;){if(dir<0?y<=0:y>=doc.height){target.hitSide=!0;break}y+=5*dir}return target}function ContentEditableInput(cm){this.cm=cm,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new Delayed,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null}function posToDOM(cm,pos){var info,side,view=findViewForLine(cm,pos.line);return!view||view.hidden?null:(info=mapFromLineView(view,view=getLine(cm.doc,pos.line),pos.line),side="left",(view=getOrder(view,cm.doc.direction))&&(side=getBidiPartAt(view,pos.ch)%2?"right":"left"),(cm=nodeAndOffsetInLineMap(info.map,pos.ch,side)).offset="right"==cm.collapse?cm.end:cm.start,cm)}function badPos(pos,bad){return bad&&(pos.bad=!0),pos}function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){if(!(lineNode=cm.display.lineDiv.childNodes[offset]))return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),!0);node=null,offset=0}else for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv)return null;if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv)break}for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)return((lineView,node,offset)=>{var wrapper=lineView.text.firstChild,bad=!1;if(!node||!contains(wrapper,node))return badPos(Pos(lineNo(lineView.line),0),!0);if(node==wrapper)if(bad=!0,node=wrapper.childNodes[offset],offset=0,!node)return badPos(Pos(lineNo(line=lineView.rest?lst(lineView.rest):lineView.line),line.text.length),bad);var line=3==node.nodeType?node:null,topNode=node;for(line||1!=node.childNodes.length||3!=node.firstChild.nodeType||(line=node.firstChild,offset=offset&&line.nodeValue.length);topNode.parentNode!=wrapper;)topNode=topNode.parentNode;var measure=lineView.measure,maps=measure.maps;function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++)for(var map=i<0?measure.map:maps[i],j=0;j<map.length;j+=3){var line,ch,curNode=map[j+2];if(curNode==textNode||curNode==topNode)return line=lineNo(i<0?lineView.line:lineView.rest[i]),ch=map[j]+offset,Pos(line,ch=offset<0||curNode!=textNode?map[j+(offset?1:0)]:ch)}}var found=find(line,topNode,offset);if(found)return badPos(found,bad);for(var after=topNode.nextSibling,dist=line?line.nodeValue.length-offset:0;after;after=after.nextSibling){if(found=find(after,after.firstChild,0))return badPos(Pos(found.line,found.ch-dist),bad);dist+=after.textContent.length}for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){if(found=find(before,before.firstChild,-1))return badPos(Pos(found.line,found.ch+dist$1),bad);dist$1+=before.textContent.length}})(lineView,node,offset)}}ContentEditableInput.prototype.init=function(display){var this$1=this,input=this,cm=input.cm,div=input.div=display.lineDiv;function belongsToInput(e){for(var t=e.target;t;t=t.parentNode){if(t==div)return 1;if(/\bCodeMirror-(?:line)?widget\b/.test(t.className))break}}function onCopyCut(e){if(belongsToInput(e)&&!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()}),"cut"==e.type&&cm.replaceSelection("",null,"cut");else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type&&cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll),cm.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var content=lastCopied.text.join("\n");if(e.clipboardData.setData("Text",content),e.clipboardData.getData("Text")==content)return void e.preventDefault()}var kludge=hiddenTextarea(),content=kludge.firstChild,hadFocus=(cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild),content.value=lastCopied.text.join("\n"),document.activeElement);selectInput(content),setTimeout(function(){cm.display.lineSpace.removeChild(kludge),hadFocus.focus(),hadFocus==div&&input.showPrimarySelection()},50)}}disableBrowserMagic(div,cm.options.spellcheck,cm.options.autocorrect,cm.options.autocapitalize),on(div,"paste",function(e){!belongsToInput(e)||signalDOMEvent(cm,e)||handlePaste(e,cm)||ie_version<=11&&setTimeout(operation(cm,function(){return this$1.updateFromDOM()}),20)}),on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:!1}}),on(div,"compositionupdate",function(e){this$1.composing||(this$1.composing={data:e.data,done:!1})}),on(div,"compositionend",function(e){this$1.composing&&(e.data!=this$1.composing.data&&this$1.readFromDOMSoon(),this$1.composing.done=!0)}),on(div,"touchstart",function(){return input.forceCompositionEnd()}),on(div,"input",function(){this$1.composing||this$1.readFromDOMSoon()}),on(div,"copy",onCopyCut),on(div,"cut",onCopyCut)},ContentEditableInput.prototype.screenReaderLabelChanged=function(label){label?this.div.setAttribute("aria-label",label):this.div.removeAttribute("aria-label")},ContentEditableInput.prototype.prepareSelection=function(){var result=prepareSelection(this.cm,!1);return result.focus=document.activeElement==this.div,result},ContentEditableInput.prototype.showSelection=function(info,takeFocus){info&&this.cm.display.view.length&&((info.focus||takeFocus)&&this.showPrimarySelection(),this.showMultipleSelections(info))},ContentEditableInput.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()},ContentEditableInput.prototype.showPrimarySelection=function(){var sel=this.getSelection(),cm=this.cm,prim=cm.doc.sel.primary(),from=prim.from(),prim=prim.to();if(cm.display.viewTo==cm.display.viewFrom||from.line>=cm.display.viewTo||prim.line<cm.display.viewFrom)sel.removeAllRanges();else{var curAnchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),curFocus=domToPos(cm,sel.focusNode,sel.focusOffset);if(!curAnchor||curAnchor.bad||!curFocus||curFocus.bad||0!=cmp(minPos(curAnchor,curFocus),from)||0!=cmp(maxPos(curAnchor,curFocus),prim)){var curAnchor=cm.display.view,curFocus=from.line>=cm.display.viewFrom&&posToDOM(cm,from)||{node:curAnchor[0].measure.map[2],offset:0},from=prim.line<cm.display.viewTo&&posToDOM(cm,prim);if(from||(from={node:(curAnchor=(prim=curAnchor[curAnchor.length-1].measure).maps?prim.maps[prim.maps.length-1]:prim.map)[curAnchor.length-1],offset:curAnchor[curAnchor.length-2]-curAnchor[curAnchor.length-3]}),curFocus&&from){var rng,prim=sel.rangeCount&&sel.getRangeAt(0);try{rng=range(curFocus.node,curFocus.offset,from.offset,from.node)}catch(e){}rng&&(!gecko&&cm.state.focused&&(sel.collapse(curFocus.node,curFocus.offset),rng.collapsed)||(sel.removeAllRanges(),sel.addRange(rng)),prim&&null==sel.anchorNode?sel.addRange(prim):gecko&&this.startGracePeriod()),this.rememberSelection()}else sel.removeAllRanges()}}},ContentEditableInput.prototype.startGracePeriod=function(){var this$1=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){this$1.gracePeriod=!1,this$1.selectionChanged()&&this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=!0})},20)},ContentEditableInput.prototype.showMultipleSelections=function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors),removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)},ContentEditableInput.prototype.rememberSelection=function(){var sel=this.getSelection();this.lastAnchorNode=sel.anchorNode,this.lastAnchorOffset=sel.anchorOffset,this.lastFocusNode=sel.focusNode,this.lastFocusOffset=sel.focusOffset},ContentEditableInput.prototype.selectionInEditor=function(){var sel=this.getSelection();return!!sel.rangeCount&&(sel=sel.getRangeAt(0).commonAncestorContainer,contains(this.div,sel))},ContentEditableInput.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()&&document.activeElement==this.div||this.showSelection(this.prepareSelection(),!0),this.div.focus())},ContentEditableInput.prototype.blur=function(){this.div.blur()},ContentEditableInput.prototype.getField=function(){return this.div},ContentEditableInput.prototype.supportsTouch=function(){return!0},ContentEditableInput.prototype.receivedFocus=function(){var input=this;this.selectionInEditor()?this.pollSelection():runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,function poll(){input.cm.state.focused&&(input.pollSelection(),input.polling.set(input.cm.options.pollInterval,poll))})},ContentEditableInput.prototype.selectionChanged=function(){var sel=this.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset},ContentEditableInput.prototype.pollSelection=function(){var sel,cm,anchor,head;null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()&&(sel=this.getSelection(),cm=this.cm,android&&chrome&&this.cm.display.gutterSpecs.length&&(node=>{for(var scan=node;scan;scan=scan.parentNode)if(/CodeMirror-gutter-wrapper/.test(scan.className))return 1})(sel.anchorNode)?(this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),this.focus()):this.composing||(this.rememberSelection(),anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),head=domToPos(cm,sel.focusNode,sel.focusOffset),anchor&&head&&runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll),(anchor.bad||head.bad)&&(cm.curOp.selectionChanged=!0)})))},ContentEditableInput.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var fromLine,cm=this.cm,display=cm.display,sel=cm.doc.sel.primary(),from=sel.from(),sel=sel.to();if(0==from.ch&&from.line>cm.firstLine()&&(from=Pos(from.line-1,getLine(cm.doc,from.line-1).length)),sel.ch==getLine(cm.doc,sel.line).text.length&&sel.line<cm.lastLine()&&(sel=Pos(sel.line+1,0)),from.line<display.viewFrom||sel.line>display.viewTo-1)return!1;var toLine,fromIndex=from.line==display.viewFrom||0==(fromIndex=findViewIndex(cm,from.line))?(fromLine=lineNo(display.view[0].line),display.view[0].node):(fromLine=lineNo(display.view[fromIndex].line),display.view[fromIndex-1].node.nextSibling),sel=findViewIndex(cm,sel.line),display=sel==display.view.length-1?(toLine=display.viewTo-1,display.lineDiv.lastChild):(toLine=lineNo(display.view[sel+1].line)-1,display.view[sel+1].node.previousSibling);if(!fromIndex)return!1;for(var newText=cm.doc.splitLines(((cm,from,to,fromLine,toLine)=>{var text="",closing=!1,lineSep=cm.doc.lineSeparator(),extraLinebreak=!1;function close(){closing&&(text+=lineSep,extraLinebreak&&(text+=lineSep),closing=extraLinebreak=!1)}function addText(str){str&&(close(),text+=str)}for(;!function walk(node){if(1==node.nodeType){var cmText=node.getAttribute("cm-text");if(cmText)addText(cmText);else if(cmText=node.getAttribute("cm-marker"))(cmText=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),(id=+cmText,function(marker){return marker.id==id}))).length&&(cmText=cmText[0].find(0))&&addText(getBetween(cm.doc,cmText.from,cmText.to).join(lineSep));else if("false"!=node.getAttribute("contenteditable")&&(cmText=/^(pre|div|p|li|table|br)$/i.test(node.nodeName),/^br$/i.test(node.nodeName)||0!=node.textContent.length)){cmText&&close();for(var i=0;i<node.childNodes.length;i++)walk(node.childNodes[i]);/^(pre|p)$/i.test(node.nodeName)&&(extraLinebreak=!0),cmText&&(closing=!0)}}else 3==node.nodeType&&addText(node.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "));var id}(from),from!=to;)from=from.nextSibling,extraLinebreak=!1;return text})(cm,fromIndex,display,fromLine,toLine)),oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));1<newText.length&&1<oldText.length;)if(lst(newText)==lst(oldText))newText.pop(),oldText.pop(),toLine--;else{if(newText[0]!=oldText[0])break;newText.shift(),oldText.shift(),fromLine++}for(var cutFront=0,cutEnd=0,newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront);)++cutFront;for(var newBot=lst(newText),oldBot=lst(oldText),maxCutEnd=Math.min(newBot.length-(1==newText.length?cutFront:0),oldBot.length-(1==oldText.length?cutFront:0));cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)++cutEnd;if(1==newText.length&&1==oldText.length&&fromLine==from.line)for(;cutFront&&cutFront>from.ch&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)cutFront--,cutEnd++;newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,""),newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"");sel=Pos(fromLine,cutFront),fromIndex=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);return 1<newText.length||newText[0]||cmp(sel,fromIndex)?(replaceRange(cm.doc,newText,sel,fromIndex,"+input"),!0):void 0},ContentEditableInput.prototype.ensurePolled=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.reset=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},ContentEditableInput.prototype.readFromDOMSoon=function(){var this$1=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(this$1.readDOMTimeout=null,this$1.composing){if(!this$1.composing.done)return;this$1.composing=null}this$1.updateFromDOM()},80))},ContentEditableInput.prototype.updateFromDOM=function(){var this$1=this;!this.cm.isReadOnly()&&this.pollContent()||runInOp(this.cm,function(){return regChange(this$1.cm)})},ContentEditableInput.prototype.setUneditable=function(node){node.contentEditable="false"},ContentEditableInput.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly())||operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0)},ContentEditableInput.prototype.readOnlyChanged=function(val){this.div.contentEditable=String("nocursor"!=val)},ContentEditableInput.prototype.onContextMenu=function(){},ContentEditableInput.prototype.resetPosition=function(){},ContentEditableInput.prototype.needsContentAttribute=!0;function TextareaInput(cm){this.cm=cm,this.prevInput="",this.pollingFast=!1,this.polling=new Delayed,this.hasSelection=!1,this.composing=null}TextareaInput.prototype.init=function(display){var this$1=this,input=this,cm=this.cm,te=(this.createField(display),this.textarea);function prepareCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()});else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type?cm.setSelections(ranges.ranges,null,sel_dontScroll):(input.prevInput="",te.value=ranges.text.join("\n"),selectInput(te))}"cut"==e.type&&(cm.state.cutIncoming=+new Date)}}display.wrapper.insertBefore(this.wrapper,display.wrapper.firstChild),ios&&(te.style.width="0px"),on(te,"input",function(){ie&&9<=ie_version&&this$1.hasSelection&&(this$1.hasSelection=null),input.poll()}),on(te,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)||(cm.state.pasteIncoming=+new Date,input.fastPoll())}),on(te,"cut",prepareCopyCut),on(te,"copy",prepareCopyCut),on(display.scroller,"paste",function(e){var event;eventInWidget(display,e)||signalDOMEvent(cm,e)||(te.dispatchEvent?((event=new Event("paste")).clipboardData=e.clipboardData,te.dispatchEvent(event)):(cm.state.pasteIncoming=+new Date,input.focus()))}),on(display.lineSpace,"selectstart",function(e){eventInWidget(display,e)||e_preventDefault(e)}),on(te,"compositionstart",function(){var start=cm.getCursor("from");input.composing&&input.composing.range.clear(),input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}}),on(te,"compositionend",function(){input.composing&&(input.poll(),input.composing.range.clear(),input.composing=null)})},TextareaInput.prototype.createField=function(_display){this.wrapper=hiddenTextarea(),this.textarea=this.wrapper.firstChild},TextareaInput.prototype.screenReaderLabelChanged=function(label){label?this.textarea.setAttribute("aria-label",label):this.textarea.removeAttribute("aria-label")},TextareaInput.prototype.prepareSelection=function(){var lineOff,cm=this.cm,display=cm.display,doc=cm.doc,result=prepareSelection(cm);return cm.options.moveInputWithCursor&&(cm=cursorCoords(cm,doc.sel.primary().head,"div"),doc=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect(),result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,cm.top+lineOff.top-doc.top)),result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,cm.left+lineOff.left-doc.left))),result},TextareaInput.prototype.showSelection=function(drawn){var display=this.cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors),removeChildrenAndAdd(display.selectionDiv,drawn.selection),null!=drawn.teTop&&(this.wrapper.style.top=drawn.teTop+"px",this.wrapper.style.left=drawn.teLeft+"px")},TextareaInput.prototype.reset=function(typing){var cm,content;this.contextMenuPending||this.composing||((cm=this.cm).somethingSelected()?(this.prevInput="",content=cm.getSelection(),this.textarea.value=content,cm.state.focused&&selectInput(this.textarea),ie&&9<=ie_version&&(this.hasSelection=content)):typing||(this.prevInput=this.textarea.value="",ie&&9<=ie_version&&(this.hasSelection=null)))},TextareaInput.prototype.getField=function(){return this.textarea},TextareaInput.prototype.supportsTouch=function(){return!1},TextareaInput.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!mobile||activeElt()!=this.textarea))try{this.textarea.focus()}catch(e){}},TextareaInput.prototype.blur=function(){this.textarea.blur()},TextareaInput.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},TextareaInput.prototype.receivedFocus=function(){this.slowPoll()},TextareaInput.prototype.slowPoll=function(){var this$1=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){this$1.poll(),this$1.cm.state.focused&&this$1.slowPoll()})},TextareaInput.prototype.fastPoll=function(){var missed=!1,input=this;input.pollingFast=!0,input.polling.set(20,function p(){input.poll()||missed?(input.pollingFast=!1,input.slowPoll()):(missed=!0,input.polling.set(60,p))})},TextareaInput.prototype.poll=function(){var this$1=this,cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||hasSelection(input)&&!prevInput&&!this.composing||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)return!1;var text=input.value;if(text==prevInput&&!cm.somethingSelected())return!1;if(ie&&9<=ie_version&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text))return cm.display.input.reset(),!1;if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);if(8203==first&&(prevInput=prevInput||""),8666==first)return this.reset(),this.cm.execCommand("undo")}for(var same=0,l=Math.min(prevInput.length,text.length);same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same);)++same;return runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null),1e3<text.length||-1<text.indexOf("\n")?input.value=this$1.prevInput="":this$1.prevInput=text,this$1.composing&&(this$1.composing.range.clear(),this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},TextareaInput.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},TextareaInput.prototype.onKeyPress=function(){ie&&9<=ie_version&&(this.hasSelection=null),this.fastPoll()},TextareaInput.prototype.onContextMenu=function(e){var oldCSS,oldWrapperCSS,oldScrollY,mouseup,input=this,cm=input.cm,display=cm.display,te=input.textarea,pos=(input.contextMenuPending&&input.contextMenuPending(),posFromMouse(cm,e)),scrollPos=display.scroller.scrollTop;function prepareSelectAllHack(){var selected,extval;null!=te.selectionStart&&(extval=""+((selected=cm.somethingSelected())?te.value:""),te.value="⇚",te.value=extval,input.prevInput=selected?"":"",te.selectionStart=1,te.selectionEnd=extval.length,display.selForContextMenu=cm.doc.sel)}function rehide(){var i,poll;input.contextMenuPending==rehide&&(input.contextMenuPending=!1,input.wrapper.style.cssText=oldWrapperCSS,te.style.cssText=oldCSS,ie&&ie_version<9&&display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos),null!=te.selectionStart)&&((!ie||ie_version<9)&&prepareSelectAllHack(),i=0,poll=function(){display.selForContextMenu==cm.doc.sel&&0==te.selectionStart&&0<te.selectionEnd&&""==input.prevInput?operation(cm,selectAll)(cm):i++<10?display.detectingSelectAll=setTimeout(poll,500):(display.selForContextMenu=null,display.input.reset())},display.detectingSelectAll=setTimeout(poll,200))}pos&&!presto&&(cm.options.resetSelectionOnContextMenu&&-1==cm.doc.sel.contains(pos)&&operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll),oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText,pos=input.wrapper.offsetParent.getBoundingClientRect(),input.wrapper.style.cssText="position: static",te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-pos.top-5)+"px; left: "+(e.clientX-pos.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",webkit&&(oldScrollY=window.scrollY),display.input.focus(),webkit&&window.scrollTo(null,oldScrollY),display.input.reset(),cm.somethingSelected()||(te.value=input.prevInput=" "),input.contextMenuPending=rehide,display.selForContextMenu=cm.doc.sel,clearTimeout(display.detectingSelectAll),ie&&9<=ie_version&&prepareSelectAllHack(),captureRightClick?(e_stop(e),mouseup=function(){off(window,"mouseup",mouseup),setTimeout(rehide,20)},on(window,"mouseup",mouseup)):setTimeout(rehide,50))},TextareaInput.prototype.readOnlyChanged=function(val){val||this.reset(),this.textarea.disabled="nocursor"==val,this.textarea.readOnly=!!val},TextareaInput.prototype.setUneditable=function(){},TextareaInput.prototype.needsContentAttribute=!1,(CodeMirror=>{var optionHandlers=CodeMirror.optionHandlers;function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt,handle&&(optionHandlers[name]=notOnInit?function(cm,val,old){old!=Init&&handle(cm,val,old)}:handle)}CodeMirror.defineOption=option,CodeMirror.Init=Init,option("value","",function(cm,val){return cm.setValue(val)},!0),option("mode",null,function(cm,val){cm.doc.modeOption=val,loadMode(cm)},!0),option("indentUnit",2,loadMode,!0),option("indentWithTabs",!1),option("smartIndent",!0),option("tabSize",4,function(cm){resetModeState(cm),clearCaches(cm),regChange(cm)},!0),option("lineSeparator",null,function(cm,val){if(cm.doc.lineSep=val){var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(-1==found)break;pos=found+val.length,newBreaks.push(Pos(lineNo,found))}lineNo++});for(var i=newBreaks.length-1;0<=i;i--)replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}}),option("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g"),old!=Init&&cm.refresh()}),option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh()},!0),option("electricChars",!0),option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),option("spellcheck",!1,function(cm,val){return cm.getInputField().spellcheck=val},!0),option("autocorrect",!1,function(cm,val){return cm.getInputField().autocorrect=val},!0),option("autocapitalize",!1,function(cm,val){return cm.getInputField().autocapitalize=val},!0),option("rtlMoveVisually",!windows),option("wholeLineUpdateBefore",!0),option("theme","default",function(cm){themeChanged(cm),updateGutters(cm)},!0),option("keyMap","default",function(cm,val,old){val=getKeyMap(val),old=old!=Init&&getKeyMap(old);old&&old.detach&&old.detach(cm,val),val.attach&&val.attach(cm,old||null)}),option("extraKeys",null),option("configureMouse",null),option("lineWrapping",!1,wrappingChanged,!0),option("gutters",[],function(cm,val){cm.display.gutterSpecs=getGutters(val,cm.options.lineNumbers),updateGutters(cm)},!0),option("fixedGutter",!0,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0",cm.refresh()},!0),option("coverGutterNextToScrollbar",!1,function(cm){return updateScrollbars(cm)},!0),option("scrollbarStyle","native",function(cm){initScrollbars(cm),updateScrollbars(cm),cm.display.scrollbars.setScrollTop(cm.doc.scrollTop),cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},!0),option("lineNumbers",!1,function(cm,val){cm.display.gutterSpecs=getGutters(cm.options.gutters,val),updateGutters(cm)},!0),option("firstLineNumber",1,updateGutters,!0),option("lineNumberFormatter",function(integer){return integer},updateGutters,!0),option("showCursorWhenSelecting",!1,updateSelection,!0),option("resetSelectionOnContextMenu",!0),option("lineWiseCopyCut",!0),option("pasteLinesPerSelection",!0),option("selectionsMayTouch",!1),option("readOnly",!1,function(cm,val){"nocursor"==val&&(onBlur(cm),cm.display.input.blur()),cm.display.input.readOnlyChanged(val)}),option("screenReaderLabel",null,function(cm,val){cm.display.input.screenReaderLabelChanged(val=""===val?null:val)}),option("disableInput",!1,function(cm,val){val||cm.display.input.reset()},!0),option("dragDrop",!0,dragDropChanged),option("allowDropFileTypes",null),option("cursorBlinkRate",530),option("cursorScrollMargin",0),option("cursorHeight",1,updateSelection,!0),option("singleCursorHeightPerLine",!0,updateSelection,!0),option("workTime",100),option("workDelay",100),option("flattenSpans",!0,resetModeState,!0),option("addModeClass",!1,resetModeState,!0),option("pollInterval",100),option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val}),option("historyEventDelay",1250),option("viewportMargin",10,function(cm){return cm.refresh()},!0),option("maxHighlightLength",1e4,resetModeState,!0),option("moveInputWithCursor",!0,function(cm,val){val||cm.display.input.resetPosition()}),option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||""}),option("autofocus",null),option("direction","ltr",function(cm,val){return cm.doc.setDirection(val)},!0),option("phrases",null)})(CodeMirror),(CodeMirror=>{var optionHandlers=CodeMirror.optionHandlers,helpers=CodeMirror.helpers={};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus(),this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option];options[option]==value&&"mode"!=option||(options[option]=value,optionHandlers.hasOwnProperty(option)&&operation(this,optionHandlers[option])(this,value,old),signal(this,"optionChange",this,option))},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map))},removeKeyMap:function(map){for(var maps=this.state.keyMaps,i=0;i<maps.length;++i)if(maps[i]==map||maps[i].name==map)return maps.splice(i,1),!0},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState)throw new Error("Overlays may not be stateful.");for(var array=this.state.overlays,mode={mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:options&&options.priority||0},score=function(overlay){return overlay.priority},pos=0,priority=score(mode);pos<array.length&&score(array[pos])<=priority;)pos++;array.splice(pos,0,mode),this.state.modeGen++,regChange(this)}),removeOverlay:methodOp(function(spec){for(var overlays=this.state.overlays,i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||"string"==typeof spec&&cur.name==spec)return overlays.splice(i,1),this.state.modeGen++,void regChange(this)}}),indentLine:methodOp(function(n,dir,aggressive){"string"!=typeof dir&&"number"!=typeof dir&&(dir=null==dir?this.options.smartIndent?"smart":"prev":dir?"add":"subtract"),isLine(this.doc,n)&&indentLine(this,n,dir,aggressive)}),indentSelection:methodOp(function(how){for(var ranges=this.doc.sel.ranges,end=-1,i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty())range.head.line>end&&(indentLine(this,range.head.line,how,!0),end=range.head.line,i==this.doc.sel.primIndex)&&ensureCursorVisible(this);else{for(var from=range.from(),range=range.to(),start=Math.max(end,from.line),end=Math.min(this.lastLine(),range.line-(range.ch?0:1))+1,j=start;j<end;++j)indentLine(this,j,how);range=this.doc.sel.ranges;0==from.ch&&ranges.length==range.length&&0<range[i].from().ch&&replaceOneSelection(this.doc,i,new Range(from,range[i].to()),sel_dontScroll)}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,!0)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var type,styles=getLineStyles(this,getLine(this.doc,pos.line)),before=0,after=(styles.length-1)/2,ch=pos.ch;if(0==ch)type=styles[2];else for(;;){var mid=before+after>>1;if((mid?styles[2*mid-1]:0)>=ch)after=mid;else{if(!(styles[2*mid+1]<ch)){type=styles[2*mid+2];break}before=1+mid}}pos=type?type.indexOf("overlay "):-1;return pos<0?type:0==pos?null:type.slice(0,pos-1)},getModeAt:function(pos){var mode=this.doc.mode;return mode.innerMode?CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode:mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var found=[];if(helpers.hasOwnProperty(type)){var help=helpers[type],mode=this.getModeAt(pos);if("string"==typeof mode[type])help[mode[type]]&&found.push(help[mode[type]]);else if(mode[type])for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];val&&found.push(val)}else mode.helperType&&help[mode.helperType]?found.push(help[mode.helperType]):help[mode.name]&&found.push(help[mode.name]);for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1];cur.pred(mode,this)&&-1==indexOf(found,cur.val)&&found.push(cur.val)}}return found},getStateAfter:function(line,precise){var doc=this.doc;return getContextBefore(this,(line=clipLine(doc,null==line?doc.first+doc.size-1:line))+1,precise).state},cursorCoords:function(start,mode){var range=this.doc.sel.primary(),start=null==start?range.head:"object"==typeof start?clipPos(this.doc,start):start?range.from():range.to();return cursorCoords(this,start,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){return coordsChar(this,(coords=fromCoordSystem(this,coords,mode||"page")).left,coords.top)},lineAtHeight:function(height,mode){return height=fromCoordSystem(this,{top:height,left:0},mode||"page").top,lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var end=!1,last="number"==typeof line?(last=this.doc.first+this.doc.size-1,line<this.doc.first?line=this.doc.first:last<line&&(line=last,end=!0),getLine(this.doc,line)):line;return intoCoordSystem(this,last,{top:0,left:0},mode||"page",includeWidgets||end).top+(end?this.doc.height-heightAtLine(last):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var hspace,vspace,display=this.display,top=(pos=cursorCoords(this,clipPos(this.doc,pos))).bottom,left=pos.left;node.style.position="absolute",node.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(node),display.sizer.appendChild(node),"over"==vert?top=pos.top:"above"!=vert&&"near"!=vert||(vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth),("above"==vert||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight?top=pos.top-node.offsetHeight:pos.bottom+node.offsetHeight<=vspace&&(top=pos.bottom),left+node.offsetWidth>hspace&&(left=hspace-node.offsetWidth)),node.style.top=top+"px",node.style.left=node.style.right="","right"==horiz?(left=display.sizer.clientWidth-node.offsetWidth,node.style.right="0px"):("left"==horiz?left=0:"middle"==horiz&&(left=(display.sizer.clientWidth-node.offsetWidth)/2),node.style.left=left+"px"),scroll&&(vert=this,vspace={left:left,top:top,right:left+node.offsetWidth,bottom:top+node.offsetHeight},null!=(vspace=calculateScrollPos(vert,vspace)).scrollTop&&updateScrollTop(vert,vspace.scrollTop),null!=vspace.scrollLeft)&&setScrollLeft(vert,vspace.scrollLeft)},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,triggerOnMouseDown:methodOp(onMouseDown),execCommand:function(cmd){if(commands.hasOwnProperty(cmd))return commands[cmd].call(null,this)},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){for(var dir=1,cur=(amount<0&&(dir=-1,amount=-amount),clipPos(this.doc,from)),i=0;i<amount&&!(cur=findPosH(this.doc,cur,dir,unit,visually)).hitSide;++i);return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range){return this$1.display.shift||this$1.doc.extend||range.empty()?findPosH(this$1.doc,range.head,dir,unit,this$1.options.rtlMoveVisually):dir<0?range.from():range.to()},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;sel.somethingSelected()?doc.replaceSelection("",null,"+delete"):deleteNearSelection(this,function(range){var other=findPosH(doc,range.head,dir,unit,!1);return dir<0?{from:other,to:range.head}:{from:range.head,to:other}})}),findPosV:function(from,amount,unit,goalColumn){for(var dir=1,x=goalColumn,cur=(amount<0&&(dir=-1,amount=-amount),clipPos(this.doc,from)),i=0;i<amount;++i){var coords=cursorCoords(this,cur,"div");if(null==x?x=coords.left:coords.left=x,(cur=findPosV(this,coords,dir,unit)).hitSide)break}return cur},moveV:methodOp(function(dir,unit){var this$1=this,doc=this.doc,goals=[],collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected();if(doc.extendSelectionsBy(function(range){var headPos,pos;return collapse?dir<0?range.from():range.to():(headPos=cursorCoords(this$1,range.head,"div"),null!=range.goalColumn&&(headPos.left=range.goalColumn),goals.push(headPos.left),pos=findPosV(this$1,headPos,dir,unit),"page"==unit&&range==doc.sel.primary()&&addToScrollTop(this$1,charCoords(this$1,pos,"div").top-headPos.top),pos)},sel_move),goals.length)for(var i=0;i<doc.sel.ranges.length;i++)doc.sel.ranges[i].goalColumn=goals[i]}),findWordAt:function(pos){var line=getLine(this.doc,pos.line).text,start=pos.ch,end=pos.ch;if(line){for(var helper=this.getHelper(pos,"wordChars"),startChar=("before"!=pos.sticky&&end!=line.length||!start?++end:--start,line.charAt(start)),check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper)}:/\s/.test(startChar)?function(ch){return/\s/.test(ch)}:function(ch){return!/\s/.test(ch)&&!isWordChar(ch)};0<start&&check(line.charAt(start-1));)--start;for(;end<line.length&&check(line.charAt(end));)++end}return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){null!=value&&value==this.state.overwrite||(((this.state.overwrite=!this.state.overwrite)?addClass:rmClass)(this.display.cursorDiv,"CodeMirror-overwrite"),signal(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:methodOp(function(x,y){scrollToCoords(this,x,y)}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range,margin){null==range?(range={from:this.doc.sel.primary().head,to:null},null==margin&&(margin=this.options.cursorScrollMargin)):"number"==typeof range?range={from:Pos(range,0),to:null}:null==range.from&&(range={from:range,to:null}),range.to||(range.to=range.from),range.margin=margin||0,null!=range.from.line?((cm,range)=>{resolveScrollToPos(cm),cm.curOp.scrollToPos=range})(this,range):scrollToCoordsRange(this,range.from,range.to,range.margin)}),setSize:methodOp(function(width,height){function interpret(val){return"number"==typeof val||/^\d+$/.test(String(val))?val+"px":val}var this$1=this,lineNo=(null!=width&&(this.display.wrapper.style.width=interpret(width)),null!=height&&(this.display.wrapper.style.height=interpret(height)),this.options.lineWrapping&&clearLineMeasurementCache(this),this.display.viewFrom);this.doc.iter(lineNo,this.display.viewTo,function(line){if(line.widgets)for(var i=0;i<line.widgets.length;i++)if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo,"widget");break}++lineNo}),this.curOp.forceUpdate=!0,signal(this,"refresh",this)}),operation:function(f){return runInOp(this,f)},startOperation:function(){return startOperation(this)},endOperation:function(){return endOperation(this)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this),this.curOp.forceUpdate=!0,clearCaches(this),scrollToCoords(this,this.doc.scrollLeft,this.doc.scrollTop),updateGutterSpace(this.display),(null==oldHeight||.5<Math.abs(oldHeight-textHeight(this.display))||this.options.lineWrapping)&&estimateLineHeights(this),signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc;return old.cm=null,this.state.selectingText&&this.state.selectingText(),attachDoc(this,doc),clearCaches(this),this.display.input.reset(),scrollToCoords(this,doc.scrollLeft,doc.scrollTop),this.curOp.forceScroll=!0,signalLater(this,"swapDoc",this,old),old}),phrase:function(phraseText){var phrases=this.options.phrases;return phrases&&Object.prototype.hasOwnProperty.call(phrases,phraseText)?phrases[phraseText]:phraseText},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},eventMixin(CodeMirror),CodeMirror.registerHelper=function(type,name,value){helpers.hasOwnProperty(type)||(helpers[type]=CodeMirror[type]={_global:[]}),helpers[type][name]=value},CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value),helpers[type]._global.push({pred:predicate,val:value})}})(CodeMirror);var prop,dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(prop in Doc.prototype)Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0&&(CodeMirror.prototype[prop]=(method=>function(){return method.apply(this.doc,arguments)})(Doc.prototype[prop]));return eventMixin(Doc),CodeMirror.inputStyles={textarea:TextareaInput,contenteditable:ContentEditableInput},CodeMirror.defineMode=function(name){CodeMirror.defaults.mode||"null"==name||(CodeMirror.defaults.mode=name),function(name,mode){2<arguments.length&&(mode.dependencies=Array.prototype.slice.call(arguments,2)),modes[name]=mode}.apply(this,arguments)},CodeMirror.defineMIME=function(mime,spec){mimeModes[mime]=spec},CodeMirror.defineMode("null",function(){return{token:function(stream){return stream.skipToEnd()}}}),CodeMirror.defineMIME("text/plain","null"),CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func},CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func},CodeMirror.fromTextArea=function(textarea,options){var hasFocus;function save(){textarea.value=cm.getValue()}if((options=options?copyObj(options):{}).value=textarea.value,!options.tabindex&&textarea.tabIndex&&(options.tabindex=textarea.tabIndex),!options.placeholder&&textarea.placeholder&&(options.placeholder=textarea.placeholder),null==options.autofocus&&(hasFocus=activeElt(),options.autofocus=hasFocus==textarea||null!=textarea.getAttribute("autofocus")&&hasFocus==document.body),textarea.form&&(on(textarea.form,"submit",save),!options.leaveSubmitMethodAlone)){var form=textarea.form,realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save(),form.submit=realSubmit,form.submit(),form.submit=wrappedSubmit}}catch(e){}}options.finishInit=function(cm){cm.save=save,cm.getTextArea=function(){return textarea},cm.toTextArea=function(){cm.toTextArea=isNaN,save(),textarea.parentNode.removeChild(cm.getWrapperElement()),textarea.style.display="",textarea.form&&(off(textarea.form,"submit",save),options.leaveSubmitMethodAlone||"function"!=typeof textarea.form.submit||(textarea.form.submit=realSubmit))}},textarea.style.display="none";var cm=CodeMirror(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling)},options);return cm},(CodeMirror=>{CodeMirror.off=off,CodeMirror.on=on,CodeMirror.wheelEventPixels=wheelEventPixels,CodeMirror.Doc=Doc,CodeMirror.splitLines=splitLinesAuto,CodeMirror.countColumn=countColumn,CodeMirror.findColumn=findColumn,CodeMirror.isWordChar=isWordCharBasic,CodeMirror.Pass=Pass,CodeMirror.signal=signal,CodeMirror.Line=Line,CodeMirror.changeEnd=changeEnd,CodeMirror.scrollbarModel=scrollbarModel,CodeMirror.Pos=Pos,CodeMirror.cmpPos=cmp,CodeMirror.modes=modes,CodeMirror.mimeModes=mimeModes,CodeMirror.resolveMode=resolveMode,CodeMirror.getMode=getMode,CodeMirror.modeExtensions=modeExtensions,CodeMirror.extendMode=extendMode,CodeMirror.copyState=copyState,CodeMirror.startState=startState,CodeMirror.innerMode=innerMode,CodeMirror.commands=commands,CodeMirror.keyMap=keyMap,CodeMirror.keyName=keyName,CodeMirror.isModifierKey=isModifierKey,CodeMirror.lookupKey=lookupKey,CodeMirror.normalizeKeyMap=normalizeKeyMap,CodeMirror.StringStream=StringStream,CodeMirror.SharedTextMarker=SharedTextMarker,CodeMirror.TextMarker=TextMarker,CodeMirror.LineWidget=LineWidget,CodeMirror.e_preventDefault=e_preventDefault,CodeMirror.e_stopPropagation=e_stopPropagation,CodeMirror.e_stop=e_stop,CodeMirror.addClass=addClass,CodeMirror.contains=contains,CodeMirror.rmClass=rmClass,CodeMirror.keyNames=keyNames})(CodeMirror),CodeMirror.version="5.58.3",CodeMirror}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function drawRulers(cm){cm.state.rulerDiv.textContent="";var val=cm.getOption("rulers"),cw=cm.defaultCharWidth(),left=cm.charCoords(CodeMirror.Pos(cm.firstLine(),0),"div").left;cm.state.rulerDiv.style.minHeight=cm.display.scroller.offsetHeight+30+"px";for(var i=0;i<val.length;i++){var elt=document.createElement("div");elt.className="CodeMirror-ruler";var col,conf=val[i];"number"==typeof conf?col=conf:(col=conf.column,conf.className&&(elt.className+=" "+conf.className),conf.color&&(elt.style.borderColor=conf.color),conf.lineStyle&&(elt.style.borderLeftStyle=conf.lineStyle),conf.width&&(elt.style.borderLeftWidth=conf.width)),elt.style.left=left+col*cw+"px",cm.state.rulerDiv.appendChild(elt)}}CodeMirror.defineOption("rulers",!1,function(cm,val){cm.state.rulerDiv&&(cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv),cm.state.rulerDiv=null,cm.off("refresh",drawRulers)),val&&val.length&&(cm.state.rulerDiv=cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"),cm.display.lineSpace),cm.state.rulerDiv.className="CodeMirror-rulers",drawRulers(cm),cm.on("refresh",drawRulers))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function onChange(cm,change){CodeMirror.changeEnd(change).line==cm.lastLine()&&updateBottomMargin(cm)}function updateBottomMargin(cm){var padding="";1<cm.lineCount()&&(padding=cm.display.scroller.clientHeight-30-cm.getLineHandle(cm.lastLine()).height+"px"),cm.state.scrollPastEndPadding!=padding&&(cm.state.scrollPastEndPadding=padding,cm.display.lineSpace.parentNode.style.paddingBottom=padding,cm.off("refresh",updateBottomMargin),cm.setSize(),cm.on("refresh",updateBottomMargin))}CodeMirror.defineOption("scrollPastEnd",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.off("change",onChange),cm.off("refresh",updateBottomMargin),cm.display.lineSpace.parentNode.style.paddingBottom="",cm.state.scrollPastEndPadding=null),val&&(cm.on("change",onChange),cm.on("refresh",updateBottomMargin),updateBottomMargin(cm))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function doFold(cm,pos,options,force){options&&options.call?(finder=options,options=null):finder=getOption(cm,options,"rangeFinder"),"number"==typeof pos&&(pos=CodeMirror.Pos(pos,0));var finder,minSize=getOption(cm,options,"minFoldSize");function getRange(allowFolded){var range=finder(cm,pos);if(!range||range.to.line-range.from.line<minSize)return null;for(var marks=cm.findMarksAt(range.from),i=0;i<marks.length;++i)if(marks[i].__isFold&&"fold"!==force){if(!allowFolded)return null;range.cleared=!0,marks[i].clear()}return range}var myWidget,myRange,range=getRange(!0);if(getOption(cm,options,"scanUp"))for(;!range&&pos.line>cm.firstLine();)pos=CodeMirror.Pos(pos.line-1,0),range=getRange(!1);range&&!range.cleared&&"unfold"!==force&&(myWidget=((cm,options,range)=>("string"==typeof(cm="function"==typeof(cm=getOption(cm,options,"widget"))?cm(range.from,range.to):cm)?(options=document.createTextNode(cm),(cm=document.createElement("span")).appendChild(options),cm.className="CodeMirror-foldmarker"):cm=cm&&cm.cloneNode(!0),cm))(cm,options,range),CodeMirror.on(myWidget,"mousedown",function(e){myRange.clear(),CodeMirror.e_preventDefault(e)}),(myRange=cm.markText(range.from,range.to,{replacedWith:myWidget,clearOnEnter:getOption(cm,options,"clearOnEnter"),__isFold:!0})).on("clear",function(from,to){CodeMirror.signal(cm,"unfold",cm,from,to)}),CodeMirror.signal(cm,"fold",cm,range.from,range.to))}CodeMirror.newFoldFunction=function(rangeFinder,widget){return function(cm,pos){doFold(cm,pos,{rangeFinder:rangeFinder,widget:widget})}},CodeMirror.defineExtension("foldCode",function(pos,options,force){doFold(this,pos,options,force)}),CodeMirror.defineExtension("isFolded",function(pos){for(var marks=this.findMarksAt(pos),i=0;i<marks.length;++i)if(marks[i].__isFold)return!0}),CodeMirror.commands.toggleFold=function(cm){cm.foldCode(cm.getCursor())},CodeMirror.commands.fold=function(cm){cm.foldCode(cm.getCursor(),null,"fold")},CodeMirror.commands.unfold=function(cm){cm.foldCode(cm.getCursor(),null,"unfold")},CodeMirror.commands.foldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"fold")})},CodeMirror.commands.unfoldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"unfold")})},CodeMirror.registerHelper("fold","combine",function(){var funcs=Array.prototype.slice.call(arguments,0);return function(cm,start){for(var i=0;i<funcs.length;++i){var found=funcs[i](cm,start);if(found)return found}}}),CodeMirror.registerHelper("fold","auto",function(cm,start){for(var helpers=cm.getHelpers(start,"fold"),i=0;i<helpers.length;i++){var cur=helpers[i](cm,start);if(cur)return cur}});var defaultOptions={rangeFinder:CodeMirror.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};function getOption(cm,options,name){return(options&&void 0!==options[name]||(options=cm.options.foldOptions)&&void 0!==options[name]?options:defaultOptions)[name]}CodeMirror.defineOption("foldOptions",null),CodeMirror.defineExtension("foldOption",function(options,name){return getOption(this,options,name)})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./foldcode")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./foldcode"],mod):mod(CodeMirror)})(function(CodeMirror){CodeMirror.defineOption("foldGutter",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.clearGutter(cm.state.foldGutter.options.gutter),cm.state.foldGutter=null,cm.off("gutterClick",onGutterClick),cm.off("changes",onChange),cm.off("viewportChange",onViewportChange),cm.off("fold",onFold),cm.off("unfold",onFold),cm.off("swapDoc",onChange)),val&&(cm.state.foldGutter=new State((opts=>(null==(opts=!0===opts?{}:opts).gutter&&(opts.gutter="CodeMirror-foldgutter"),null==opts.indicatorOpen&&(opts.indicatorOpen="CodeMirror-foldgutter-open"),null==opts.indicatorFolded&&(opts.indicatorFolded="CodeMirror-foldgutter-folded"),opts))(val)),updateInViewport(cm),cm.on("gutterClick",onGutterClick),cm.on("changes",onChange),cm.on("viewportChange",onViewportChange),cm.on("fold",onFold),cm.on("unfold",onFold),cm.on("swapDoc",onChange))});var Pos=CodeMirror.Pos;function State(options){this.options=options,this.from=this.to=0}function isFolded(cm,line){for(var marks=cm.findMarks(Pos(line,0),Pos(line+1,0)),i=0;i<marks.length;++i)if(marks[i].__isFold){var fromPos=marks[i].find(-1);if(fromPos&&fromPos.line===line)return marks[i]}}function marker(spec){var elt;return"string"==typeof spec?((elt=document.createElement("div")).className=spec+" CodeMirror-guttermarker-subtle",elt):spec.cloneNode(!0)}function updateFoldInfo(cm,from,to){var opts=cm.state.foldGutter.options,cur=from-1,minSize=cm.foldOption(opts,"minFoldSize"),func=cm.foldOption(opts,"rangeFinder"),clsFolded="string"==typeof opts.indicatorFolded&&classTest(opts.indicatorFolded),clsOpen="string"==typeof opts.indicatorOpen&&classTest(opts.indicatorOpen);cm.eachLine(from,to,function(line){++cur;var mark=null,old=(old=line.gutterMarkers)&&old[opts.gutter];if(isFolded(cm,cur)){if(clsFolded&&old&&clsFolded.test(old.className))return;mark=marker(opts.indicatorFolded)}else{var pos=Pos(cur,0),pos=func&&func(cm,pos);if(pos&&pos.to.line-pos.from.line>=minSize){if(clsOpen&&old&&clsOpen.test(old.className))return;mark=marker(opts.indicatorOpen)}}(mark||old)&&cm.setGutterMarker(line,opts.gutter,mark)})}function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}function updateInViewport(cm){var vp=cm.getViewport(),state=cm.state.foldGutter;state&&(cm.operation(function(){updateFoldInfo(cm,vp.from,vp.to)}),state.from=vp.from,state.to=vp.to)}function onGutterClick(cm,line,gutter){var state=cm.state.foldGutter;state&&gutter==(gutter=state.options).gutter&&((state=isFolded(cm,line))?state.clear():cm.foldCode(Pos(line,0),gutter))}function onChange(cm){var opts,state=cm.state.foldGutter;state&&(opts=state.options,state.from=state.to=0,clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){updateInViewport(cm)},opts.foldOnChangeTimeSpan||600))}function onViewportChange(cm){var opts,state=cm.state.foldGutter;state&&(opts=state.options,clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){var vp=cm.getViewport();state.from==state.to||20<vp.from-state.to||20<state.from-vp.to?updateInViewport(cm):cm.operation(function(){vp.from<state.from&&(updateFoldInfo(cm,vp.from,state.from),state.from=vp.from),vp.to>state.to&&(updateFoldInfo(cm,state.to,vp.to),state.to=vp.to)})},opts.updateViewportTimeSpan||400))}function onFold(cm,from){var state=cm.state.foldGutter;state&&(from=from.line)>=state.from&&from<state.to&&updateFoldInfo(cm,from,from+1)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var noOptions={},nonWS=/[^\s\u00a0]/,Pos=CodeMirror.Pos,cmp=CodeMirror.cmpPos;function firstNonWS(str){str=str.search(nonWS);return-1==str?0:str}function getMode(cm,pos){var mode=cm.getMode();return!1!==mode.useInnerComments&&mode.innerMode?cm.getModeAt(pos):mode}CodeMirror.commands.toggleComment=function(cm){cm.toggleComment()},CodeMirror.defineExtension("toggleComment",function(options){options=options||noOptions;for(var minLine=1/0,ranges=this.listSelections(),mode=null,i=ranges.length-1;0<=i;i--){var from=ranges[i].from(),to=ranges[i].to();from.line>=minLine||(to.line>=minLine&&(to=Pos(minLine,0)),minLine=from.line,null==mode?mode=this.uncomment(from,to,options)?"un":(this.lineComment(from,to,options),"line"):"un"==mode?this.uncomment(from,to,options):this.lineComment(from,to,options))}}),CodeMirror.defineExtension("lineComment",function(from,to,options){options=options||noOptions;var commentString,end,pad,blankLines,self=this,mode=getMode(self,from),firstLine=self.getLine(from.line);null!=firstLine&&(firstLine=firstLine,!/\bstring\b/.test(self.getTokenTypeAt(Pos(from.line,0)))||/^[\'\"\`]/.test(firstLine))&&((commentString=options.lineComment||mode.lineComment)?(end=Math.min(0!=to.ch||to.line==from.line?to.line+1:to.line,self.lastLine()+1),pad=null==options.padding?" ":options.padding,blankLines=options.commentBlankLines||from.line==to.line,self.operation(function(){if(options.indent){for(var baseString=null,i=from.line;i<end;++i){var whitespace=(line=self.getLine(i)).slice(0,firstNonWS(line));(null==baseString||baseString.length>whitespace.length)&&(baseString=whitespace)}for(i=from.line;i<end;++i){var line=self.getLine(i),cut=baseString.length;(blankLines||nonWS.test(line))&&(line.slice(0,cut)!=baseString&&(cut=firstNonWS(line)),self.replaceRange(baseString+commentString+pad,Pos(i,0),Pos(i,cut)))}}else for(i=from.line;i<end;++i)(blankLines||nonWS.test(self.getLine(i)))&&self.replaceRange(commentString+pad,Pos(i,0))})):(options.blockCommentStart||mode.blockCommentStart)&&(options.fullLines=!0,self.blockComment(from,to,options)))}),CodeMirror.defineExtension("blockComment",function(from,to,options){options=options||noOptions;var end,pad,self=this,mode=getMode(self,from),startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;startString&&endString?/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line,0)))||((end=Math.min(to.line,self.lastLine()))!=from.line&&0==to.ch&&nonWS.test(self.getLine(end))&&--end,pad=null==options.padding?" ":options.padding,end<from.line)||self.operation(function(){if(0!=options.fullLines){var lastLineHasText=nonWS.test(self.getLine(end)),lead=(self.replaceRange(pad+endString,Pos(end)),self.replaceRange(startString+pad,Pos(from.line,0)),options.blockCommentLead||mode.blockCommentLead);if(null!=lead)for(var i=from.line+1;i<=end;++i)i==end&&!lastLineHasText||self.replaceRange(lead+pad,Pos(i,0))}else{var atCursor=0==cmp(self.getCursor("to"),to),empty=!self.somethingSelected();self.replaceRange(endString,to),atCursor&&self.setSelection(empty?to:self.getCursor("from"),to),self.replaceRange(startString,from)}}):(options.lineComment||mode.lineComment)&&0!=options.fullLines&&self.lineComment(from,to,options)}),CodeMirror.defineExtension("uncomment",function(from,to,options){options=options||noOptions;var didSomething,self=this,mode=getMode(self,from),end=Math.min(0!=to.ch||to.line==from.line?to.line:to.line-1,self.lastLine()),start=Math.min(from.line,end),lineString=options.lineComment||mode.lineComment,lines=[],pad=null==options.padding?" ":options.padding;lineComment:if(lineString){for(var i=start;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lineString);if(-1==(found=-1<found&&!/comment/.test(self.getTokenTypeAt(Pos(i,found+1)))?-1:found)&&nonWS.test(line))break lineComment;if(-1<found&&nonWS.test(line.slice(0,found)))break lineComment;lines.push(line)}if(self.operation(function(){for(var i=start;i<=end;++i){var line=lines[i-start],pos=line.indexOf(lineString),endPos=pos+lineString.length;pos<0||(line.slice(endPos,endPos+pad.length)==pad&&(endPos+=pad.length),didSomething=!0,self.replaceRange("",Pos(i,pos),Pos(i,endPos)))}}),didSomething)return!0}var lead,startLine,open,endLine,close,startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;return!(!startString||!endString||(lead=options.blockCommentLead||mode.blockCommentLead,startLine=self.getLine(start),-1==(open=startLine.indexOf(startString)))||(endLine=end==start?startLine:self.getLine(end),close=endLine.indexOf(endString,end==start?open+startString.length:0),options=Pos(start,open+1),mode=Pos(end,close+1),-1==close)||!/comment/.test(self.getTokenTypeAt(options))||!/comment/.test(self.getTokenTypeAt(mode))||-1<self.getRange(options,mode,"\n").indexOf(endString)||(mode=-1==(options=startLine.lastIndexOf(startString,from.ch))?-1:startLine.slice(0,from.ch).indexOf(endString,options+startString.length),-1!=options&&-1!=mode&&mode+endString.length!=from.ch)||(mode=endLine.indexOf(endString,to.ch),from=endLine.slice(to.ch).lastIndexOf(startString,mode-to.ch),options=-1==mode||-1==from?-1:to.ch+from,-1!=mode&&-1!=options&&options!=to.ch)||(self.operation(function(){self.replaceRange("",Pos(end,close-(pad&&endLine.slice(close-pad.length,close)==pad?pad.length:0)),Pos(end,close+endString.length));var openEnd=open+startString.length;if(pad&&startLine.slice(openEnd,openEnd+pad.length)==pad&&(openEnd+=pad.length),self.replaceRange("",Pos(start,open),Pos(start,openEnd)),lead)for(var i=start+1;i<=end;++i){var foundEnd,line=self.getLine(i),found=line.indexOf(lead);-1==found||nonWS.test(line.slice(0,found))||(foundEnd=found+lead.length,pad&&line.slice(foundEnd,foundEnd+pad.length)==pad&&(foundEnd+=pad.length),self.replaceRange("",Pos(i,found),Pos(i,foundEnd)))}}),0))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function dialogDiv(cm,template,bottom){var cm=cm.getWrapperElement(),dialog=cm.appendChild(document.createElement("div"));return dialog.className=bottom?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof template?dialog.innerHTML=template:dialog.appendChild(template),CodeMirror.addClass(cm,"dialog-opened"),dialog}function closeNotification(cm,newVal){cm.state.currentNotificationClose&&cm.state.currentNotificationClose(),cm.state.currentNotificationClose=newVal}CodeMirror.defineExtension("openDialog",function(template,callback,options){options=options||{},closeNotification(this,null);var dialog=dialogDiv(this,template,options.bottom),closed=!1,me=this;function close(newVal){"string"==typeof newVal?inp.value=newVal:closed||(closed=!0,CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog),me.focus(),options.onClose&&options.onClose(dialog))}var inp=dialog.getElementsByTagName("input")[0];return inp?(inp.focus(),options.value&&(inp.value=options.value,!1!==options.selectValueOnOpen)&&inp.select(),options.onInput&&CodeMirror.on(inp,"input",function(e){options.onInput(e,inp.value,close)}),options.onKeyUp&&CodeMirror.on(inp,"keyup",function(e){options.onKeyUp(e,inp.value,close)}),CodeMirror.on(inp,"keydown",function(e){options&&options.onKeyDown&&options.onKeyDown(e,inp.value,close)||((27==e.keyCode||!1!==options.closeOnEnter&&13==e.keyCode)&&(inp.blur(),CodeMirror.e_stop(e),close()),13==e.keyCode&&callback(inp.value,e))}),!1!==options.closeOnBlur&&CodeMirror.on(dialog,"focusout",function(evt){null!==evt.relatedTarget&&close()})):(template=dialog.getElementsByTagName("button")[0])&&(CodeMirror.on(template,"click",function(){close(),me.focus()}),!1!==options.closeOnBlur&&CodeMirror.on(template,"blur",close),template.focus()),close}),CodeMirror.defineExtension("openConfirm",function(template,callbacks,options){closeNotification(this,null);var dialog=dialogDiv(this,template,options&&options.bottom),buttons=dialog.getElementsByTagName("button"),closed=!1,me=this,blurring=1;function close(){closed||(closed=!0,CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog),me.focus())}buttons[0].focus();for(var i=0;i<buttons.length;++i){var b=buttons[i];(callback=>{CodeMirror.on(b,"click",function(e){CodeMirror.e_preventDefault(e),close(),callback&&callback(me)})})(callbacks[i]),CodeMirror.on(b,"blur",function(){--blurring,setTimeout(function(){blurring<=0&&close()},200)}),CodeMirror.on(b,"focus",function(){++blurring})}}),CodeMirror.defineExtension("openNotification",function(template,options){closeNotification(this,close);var doneTimer,dialog=dialogDiv(this,template,options&&options.bottom),closed=!1,template=options&&void 0!==options.duration?options.duration:5e3;function close(){closed||(closed=!0,clearTimeout(doneTimer),CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog))}return CodeMirror.on(dialog,"click",function(e){CodeMirror.e_preventDefault(e),close()}),template&&(doneTimer=setTimeout(close,template)),close})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./searchcursor"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../dialog/dialog"],mod):mod(CodeMirror)})(function(CodeMirror){function SearchState(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function getSearchState(cm){return cm.state.search||(cm.state.search=new SearchState)}function queryCaseInsensitive(query){return"string"==typeof query&&query==query.toLowerCase()}function getSearchCursor(cm,query,pos){return cm.getSearchCursor(query,pos,{caseFold:queryCaseInsensitive(query),multiline:!0})}function dialog(cm,text,shortText,deflt,f){cm.openDialog?cm.openDialog(text,f,{value:deflt,selectValueOnOpen:!0}):f(prompt(shortText,deflt))}function parseString(string){return string.replace(/\\([nrt\\])/g,function(match,ch){return"n"==ch?"\n":"r"==ch?"\r":"t"==ch?"\t":"\\"==ch?"\\":match})}function parseQuery(query){var isRE=query.match(/^\/(.*)\/([a-z]*)$/);if(isRE)try{query=new RegExp(isRE[1],-1==isRE[2].indexOf("i")?"":"i")}catch(e){}else query=parseString(query);return query=("string"==typeof query?""==query:query.test(""))?/x^/:query}function startSearch(cm,state,query){state.queryText=query,state.query=parseQuery(query),cm.removeOverlay(state.overlay,queryCaseInsensitive(state.query)),state.overlay=((query,caseInsensitive)=>("string"==typeof query?query=new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),caseInsensitive?"gi":"g"):query.global||(query=new RegExp(query.source,query.ignoreCase?"gi":"g")),{token:function(stream){query.lastIndex=stream.pos;var match=query.exec(stream.string);if(match&&match.index==stream.pos)return stream.pos+=match[0].length||1,"searching";match?stream.pos=match.index:stream.skipToEnd()}}))(state.query,queryCaseInsensitive(state.query)),cm.addOverlay(state.overlay),cm.showMatchesOnScrollbar&&(state.annotate&&(state.annotate.clear(),state.annotate=null),state.annotate=cm.showMatchesOnScrollbar(state.query,queryCaseInsensitive(state.query)))}function doSearch(cm,rev,persistent,immediate){var state=getSearchState(cm);if(state.query)return findNext(cm,rev);var hiding,searchNext,q=cm.getSelection()||state.lastQuery;q instanceof RegExp&&"x^"==q.source&&(q=null),persistent&&cm.openDialog?(hiding=null,searchNext=function(query,event){CodeMirror.e_stop(event),query&&(query!=state.queryText&&(startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor()),hiding&&(hiding.style.opacity=1),findNext(cm,event.shiftKey,function(_,to){var dialog;to.line<3&&document.querySelector&&(dialog=cm.display.wrapper.querySelector(".CodeMirror-dialog"))&&dialog.getBoundingClientRect().bottom-4>cm.cursorCoords(to,"window").top&&((hiding=dialog).style.opacity=.4)}))},((cm,text,deflt,onEnter,onKeyDown)=>{cm.openDialog(text,onEnter,{value:deflt,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){clearSearch(cm)},onKeyDown:onKeyDown})})(cm,getQueryDialog(cm),q,searchNext,function(event,query){var keyName=CodeMirror.keyName(event),extra=cm.getOption("extraKeys"),extra=extra&&extra[keyName]||CodeMirror.keyMap[cm.getOption("keyMap")][keyName];"findNext"==extra||"findPrev"==extra||"findPersistentNext"==extra||"findPersistentPrev"==extra?(CodeMirror.e_stop(event),startSearch(cm,getSearchState(cm),query),cm.execCommand(extra)):"find"!=extra&&"findPersistent"!=extra||(CodeMirror.e_stop(event),searchNext(query,event))}),immediate&&q&&(startSearch(cm,state,q),findNext(cm,rev))):dialog(cm,getQueryDialog(cm),"Search for:",q,function(query){query&&!state.query&&cm.operation(function(){startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor(),findNext(cm,rev)})})}function findNext(cm,rev,callback){cm.operation(function(){var state=getSearchState(cm),cursor=getSearchCursor(cm,state.query,rev?state.posFrom:state.posTo);(cursor.find(rev)||(cursor=getSearchCursor(cm,state.query,rev?CodeMirror.Pos(cm.lastLine()):CodeMirror.Pos(cm.firstLine(),0))).find(rev))&&(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()},20),state.posFrom=cursor.from(),state.posTo=cursor.to(),callback)&&callback(cursor.from(),cursor.to())})}function clearSearch(cm){cm.operation(function(){var state=getSearchState(cm);state.lastQuery=state.query,state.query&&(state.query=state.queryText=null,cm.removeOverlay(state.overlay),state.annotate)&&(state.annotate.clear(),state.annotate=null)})}function getQueryDialog(cm){return'<span class="CodeMirror-search-label">'+cm.phrase("Search:")+'</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use /re/ syntax for regexp search)")+"</span>"}function replaceAll(cm,query,text){cm.operation(function(){for(var match,cursor=getSearchCursor(cm,query);cursor.findNext();)"string"!=typeof query?(match=cm.getRange(cursor.from(),cursor.to()).match(query),cursor.replace(text.replace(/\$(\d)/g,function(_,i){return match[i]}))):cursor.replace(text)})}function replace(cm,all){var query,dialogText;cm.getOption("readOnly")||(query=cm.getSelection()||getSearchState(cm).lastQuery,dialogText='<span class="CodeMirror-search-label">'+(all?cm.phrase("Replace all:"):cm.phrase("Replace:"))+"</span>",dialog(cm,dialogText+' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use /re/ syntax for regexp search)")+"</span>",dialogText,query,function(query){query&&(query=parseQuery(query),dialog(cm,'<span class="CodeMirror-search-label">'+cm.phrase("With:")+'</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>',cm.phrase("Replace with:"),"",function(text){var cursor,advance,doReplace;text=parseString(text),all?replaceAll(cm,query,text):(clearSearch(cm),cursor=getSearchCursor(cm,query,cm.getCursor("from")),doReplace=function(match){cursor.replace("string"==typeof query?text:text.replace(/\$(\d)/g,function(_,i){return match[i]})),advance()},(advance=function(){var match,start=cursor.from();!(match=cursor.findNext())&&(cursor=getSearchCursor(cm,query),!(match=cursor.findNext())||start&&cursor.from().line==start.line&&cursor.from().ch==start.ch)||(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()}),((cm,text,shortText,fs)=>{cm.openConfirm?cm.openConfirm(text,fs):confirm(shortText)&&fs[0]()})(cm,(cm=>'<span class="CodeMirror-search-label">'+cm.phrase("Replace?")+"</span> <button>"+cm.phrase("Yes")+"</button> <button>"+cm.phrase("No")+"</button> <button>"+cm.phrase("All")+"</button> <button>"+cm.phrase("Stop")+"</button> ")(cm),cm.phrase("Replace?"),[function(){doReplace(match)},advance,function(){replaceAll(cm,query,text)}]))})())}))}))}CodeMirror.commands.find=function(cm){clearSearch(cm),doSearch(cm)},CodeMirror.commands.findPersistent=function(cm){clearSearch(cm),doSearch(cm,!1,!0)},CodeMirror.commands.findPersistentNext=function(cm){doSearch(cm,!1,!0,!0)},CodeMirror.commands.findPersistentPrev=function(cm){doSearch(cm,!0,!0,!0)},CodeMirror.commands.findNext=doSearch,CodeMirror.commands.findPrev=function(cm){doSearch(cm,!0)},CodeMirror.commands.clearSearch=clearSearch,CodeMirror.commands.replace=replace,CodeMirror.commands.replaceAll=function(cm){replace(cm,!0)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var doFold,noFold,Pos=CodeMirror.Pos;function ensureFlags(regexp,flags){for(var current=(regexp=>{var flags=regexp.flags;return null!=flags?flags:(regexp.ignoreCase?"i":"")+(regexp.global?"g":"")+(regexp.multiline?"m":"")})(regexp),target=current,i=0;i<flags.length;i++)-1==target.indexOf(flags.charAt(i))&&(target+=flags.charAt(i));return current==target?regexp:new RegExp(regexp.source,target)}function maybeMultiline(regexp){return/\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)}function searchRegexpForward(doc,regexp,start){regexp=ensureFlags(regexp,"g");for(var line=start.line,ch=start.ch,last=doc.lastLine();line<=last;line++,ch=0){regexp.lastIndex=ch;var string=doc.getLine(line),string=regexp.exec(string);if(string)return{from:Pos(line,string.index),to:Pos(line,string.index+string[0].length),match:string}}}function searchRegexpForwardMultiline(doc,regexp,start){if(!maybeMultiline(regexp))return searchRegexpForward(doc,regexp,start);regexp=ensureFlags(regexp,"gm");for(var chunk=1,line=start.line,last=doc.lastLine();line<=last;){for(var i=0;i<chunk&&!(last<line);i++)var curLine=doc.getLine(line++),string=null==string?curLine:string+"\n"+curLine;chunk*=2,regexp.lastIndex=start.ch;var inside,startLine,before,match=regexp.exec(string);if(match)return before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=start.line+before.length-1,before=before[before.length-1].length,{from:Pos(startLine,before),to:Pos(startLine+inside.length-1,1==inside.length?before+inside[0].length:inside[inside.length-1].length),match:match}}}function lastMatchIn(string,regexp,endMargin){for(var match,from=0;from<=string.length;){regexp.lastIndex=from;var newMatch=regexp.exec(string);if(!newMatch)break;var end=newMatch.index+newMatch[0].length;if(end>string.length-endMargin)break;(!match||end>match.index+match[0].length)&&(match=newMatch),from=newMatch.index+1}return match}function searchRegexpBackward(doc,regexp,start){regexp=ensureFlags(regexp,"g");for(var line=start.line,ch=start.ch,first=doc.firstLine();first<=line;line--,ch=-1){var string=doc.getLine(line),string=lastMatchIn(string,regexp,ch<0?0:string.length-ch);if(string)return{from:Pos(line,string.index),to:Pos(line,string.index+string[0].length),match:string}}}function searchRegexpBackwardMultiline(doc,regexp,start){if(!maybeMultiline(regexp))return searchRegexpBackward(doc,regexp,start);regexp=ensureFlags(regexp,"gm");for(var chunkSize=1,endMargin=doc.getLine(start.line).length-start.ch,line=start.line,first=doc.firstLine();first<=line;){for(var i=0;i<chunkSize&&first<=line;i++)var curLine=doc.getLine(line--),string=null==string?curLine:curLine+"\n"+string;chunkSize*=2;var inside,startLine,before,match=lastMatchIn(string,regexp,endMargin);if(match)return before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=line+before.length,before=before[before.length-1].length,{from:Pos(startLine,before),to:Pos(startLine+inside.length-1,1==inside.length?before+inside[0].length:inside[inside.length-1].length),match:match}}}function adjustPos(orig,folded,pos,foldFunc){if(orig.length==folded.length)return pos;for(var min=0,max=pos+Math.max(0,orig.length-folded.length);;){if(min==max)return min;var mid=min+max>>1,len=foldFunc(orig.slice(0,mid)).length;if(len==pos)return mid;pos<len?max=mid:min=1+mid}}function searchStringForward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,last=doc.lastLine()+1-lines.length;line<=last;line++,ch=0){var orig=doc.getLine(line).slice(ch),string=fold(orig);if(1==lines.length){var found=string.indexOf(lines[0]);if(-1!=found)return start=adjustPos(orig,string,found,fold)+ch,{from:Pos(line,adjustPos(orig,string,found,fold)+ch),to:Pos(line,adjustPos(orig,string,found+lines[0].length,fold)+ch)}}else{found=string.length-lines[0].length;if(string.slice(found)==lines[0]){for(var i=1;i<lines.length-1;i++)if(fold(doc.getLine(line+i))!=lines[i])continue search;var end=doc.getLine(line+lines.length-1),endString=fold(end),lastLine=lines[lines.length-1];if(endString.slice(0,lastLine.length)==lastLine)return{from:Pos(line,adjustPos(orig,string,found,fold)+ch),to:Pos(line+lines.length-1,adjustPos(end,endString,lastLine.length,fold))}}}}}function searchStringBackward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,first=doc.firstLine()-1+lines.length;first<=line;line--,ch=-1){var orig=doc.getLine(line),string=fold(orig=-1<ch?orig.slice(0,ch):orig);if(1==lines.length){var found=string.lastIndexOf(lines[0]);if(-1!=found)return{from:Pos(line,adjustPos(orig,string,found,fold)),to:Pos(line,adjustPos(orig,string,found+lines[0].length,fold))}}else{found=lines[lines.length-1];if(string.slice(0,found.length)==found){for(var i=1,start=line-lines.length+1;i<lines.length-1;i++)if(fold(doc.getLine(start+i))!=lines[i])continue search;var top=doc.getLine(line+1-lines.length),topString=fold(top);if(topString.slice(topString.length-lines[0].length)==lines[0])return{from:Pos(line+1-lines.length,adjustPos(top,topString,top.length-lines[0].length,fold)),to:Pos(line,adjustPos(orig,string,found.length,fold))}}}}}function SearchCursor(doc,query,pos,options){var caseFold;this.atOccurrence=!1,this.doc=doc,pos=pos?doc.clipPos(pos):Pos(0,0),this.pos={from:pos,to:pos},"object"==typeof options?caseFold=options.caseFold:(caseFold=options,options=null),"string"==typeof query?(null==caseFold&&(caseFold=!1),this.matches=function(reverse,pos){return(reverse?searchStringBackward:searchStringForward)(doc,query,pos,caseFold)}):(query=ensureFlags(query,"gm"),options&&!1===options.multiline?this.matches=function(reverse,pos){return(reverse?searchRegexpBackward:searchRegexpForward)(doc,query,pos)}:this.matches=function(reverse,pos){return(reverse?searchRegexpBackwardMultiline:searchRegexpForwardMultiline)(doc,query,pos)})}noFold=String.prototype.normalize?(doFold=function(str){return str.normalize("NFD").toLowerCase()},function(str){return str.normalize("NFD")}):(doFold=function(str){return str.toLowerCase()},function(str){return str}),SearchCursor.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(reverse){for(var end,result=this.matches(reverse,this.doc.clipPos(reverse?this.pos.from:this.pos.to));result&&0==CodeMirror.cmpPos(result.from,result.to);)reverse?result.from.ch?result.from=Pos(result.from.line,result.from.ch-1):result=result.from.line==this.doc.firstLine()?null:this.matches(reverse,this.doc.clipPos(Pos(result.from.line-1))):result.to.ch<this.doc.getLine(result.to.line).length?result.to=Pos(result.to.line,result.to.ch+1):result=result.to.line==this.doc.lastLine()?null:this.matches(reverse,Pos(result.to.line+1,0));return result?(this.pos=result,this.atOccurrence=!0,this.pos.match||!0):(end=Pos(reverse?this.doc.firstLine():this.doc.lastLine()+1,0),this.pos={from:end,to:end},this.atOccurrence=!1)},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(newText,origin){this.atOccurrence&&(newText=CodeMirror.splitLines(newText),this.doc.replaceRange(newText,this.pos.from,this.pos.to,origin),this.pos.to=Pos(this.pos.from.line+newText.length-1,newText[newText.length-1].length+(1==newText.length?this.pos.from.ch:0)))}},CodeMirror.defineExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this.doc,query,pos,caseFold)}),CodeMirror.defineDocExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this,query,pos,caseFold)}),CodeMirror.defineExtension("selectMatches",function(query,caseFold){for(var ranges=[],cur=this.getSearchCursor(query,this.getCursor("from"),caseFold);cur.findNext()&&!(0<CodeMirror.cmpPos(cur.to(),this.getCursor("to")));)ranges.push({anchor:cur.from(),head:cur.to()});ranges.length&&this.setSelections(ranges,0)})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function Annotation(cm,options){function scheduleRedraw(delay){clearTimeout(self.doRedraw),self.doRedraw=setTimeout(function(){self.redraw()},delay)}this.cm=cm,this.options=options,this.buttonHeight=options.scrollButtonHeight||cm.getOption("scrollButtonHeight"),this.annotations=[],this.doRedraw=this.doUpdate=null,this.div=cm.getWrapperElement().appendChild(document.createElement("div")),this.div.style.cssText="position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none",this.computeScale();var self=this;cm.on("refresh",this.resizeHandler=function(){clearTimeout(self.doUpdate),self.doUpdate=setTimeout(function(){self.computeScale()&&scheduleRedraw(20)},100)}),cm.on("markerAdded",this.resizeHandler),cm.on("markerCleared",this.resizeHandler),!1!==options.listenForChanges&&cm.on("changes",this.changeHandler=function(){scheduleRedraw(250)})}CodeMirror.defineExtension("annotateScrollbar",function(options){return new Annotation(this,options="string"==typeof options?{className:options}:options)}),CodeMirror.defineOption("scrollButtonHeight",0),Annotation.prototype.computeScale=function(){var cm=this.cm,cm=(cm.getWrapperElement().clientHeight-cm.display.barHeight-2*this.buttonHeight)/cm.getScrollerElement().scrollHeight;if(cm!=this.hScale)return this.hScale=cm,!0},Annotation.prototype.update=function(annotations){this.annotations=annotations,this.redraw()},Annotation.prototype.redraw=function(compute){!1!==compute&&this.computeScale();var cm=this.cm,hScale=this.hScale,frag=document.createDocumentFragment(),anns=this.annotations,wrapping=cm.getOption("lineWrapping"),singleLineH=wrapping&&1.5*cm.defaultTextHeight(),curLine=null,curLineObj=null;function getY(pos,top){var visual;return curLine!=pos.line&&(curLine=pos.line,curLineObj=cm.getLineHandle(pos.line),(visual=cm.getLineHandleVisualStart(curLineObj))!=curLineObj)&&(curLine=cm.getLineNumber(visual),curLineObj=visual),curLineObj.widgets&&curLineObj.widgets.length||wrapping&&curLineObj.height>singleLineH?cm.charCoords(pos,"local")[top?"top":"bottom"]:cm.heightAtLine(curLineObj,"local")+(top?0:curLineObj.height)}var lastLine=cm.lastLine();if(cm.display.barWidth)for(var nextTop,i=0;i<anns.length;i++){var ann=anns[i];if(!(ann.to.line>lastLine)){for(var height,elt,top=nextTop||getY(ann.from,!0)*hScale,bottom=getY(ann.to,!1)*hScale;i<anns.length-1&&!(anns[i+1].to.line>lastLine)&&!(bottom+.9<(nextTop=getY(anns[i+1].from,!0)*hScale));)bottom=getY((ann=anns[++i]).to,!1)*hScale;bottom!=top&&(height=Math.max(bottom-top,3),(elt=frag.appendChild(document.createElement("div"))).style.cssText="position: absolute; right: 0px; width: "+Math.max(cm.display.barWidth-1,2)+"px; top: "+(top+this.buttonHeight)+"px; height: "+height+"px",elt.className=this.options.className,ann.id)&&elt.setAttribute("annotation-id",ann.id)}}this.div.textContent="",this.div.appendChild(frag)},Annotation.prototype.clear=function(){this.cm.off("refresh",this.resizeHandler),this.cm.off("markerAdded",this.resizeHandler),this.cm.off("markerCleared",this.resizeHandler),this.changeHandler&&this.cm.off("changes",this.changeHandler),this.div.parentNode.removeChild(this.div)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./searchcursor"),require("../scroll/annotatescrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../scroll/annotatescrollbar"],mod):mod(CodeMirror)})(function(CodeMirror){function SearchAnnotation(cm,query,caseFold,options){this.cm=cm;var prop,annotateOptions={listenForChanges:!1};for(prop in this.options=options)annotateOptions[prop]=options[prop];annotateOptions.className||(annotateOptions.className="CodeMirror-search-match"),this.annotation=cm.annotateScrollbar(annotateOptions),this.query=query,this.caseFold=caseFold,this.gap={from:cm.firstLine(),to:cm.lastLine()+1},this.matches=[],this.update=null,this.findMatches(),this.annotation.update(this.matches);var self=this;cm.on("change",this.changeHandler=function(_cm,change){self.onChange(change)})}CodeMirror.defineExtension("showMatchesOnScrollbar",function(query,caseFold,options){return new SearchAnnotation(this,query,caseFold,options=(options="string"==typeof options?{className:options}:options)||{})});function offsetLine(line,changeStart,sizeChange){return line<=changeStart?line:Math.max(changeStart,line+sizeChange)}SearchAnnotation.prototype.findMatches=function(){if(this.gap){for(var i=0;i<this.matches.length;i++){if((match=this.matches[i]).from.line>=this.gap.to)break;match.to.line>=this.gap.from&&this.matches.splice(i--,1)}for(var match,cursor=this.cm.getSearchCursor(this.query,CodeMirror.Pos(this.gap.from,0),{caseFold:this.caseFold,multiline:this.options.multiline}),maxMatches=this.options&&this.options.maxMatches||1e3;cursor.findNext();){if((match={from:cursor.from(),to:cursor.to()}).from.line>=this.gap.to)break;if(this.matches.splice(i++,0,match),this.matches.length>maxMatches)break}this.gap=null}},SearchAnnotation.prototype.onChange=function(change){var startLine=change.from.line,endLine=CodeMirror.changeEnd(change).line,sizeChange=endLine-change.to.line;if(this.gap?(this.gap.from=Math.min(offsetLine(this.gap.from,startLine,sizeChange),change.from.line),this.gap.to=Math.max(offsetLine(this.gap.to,startLine,sizeChange),change.from.line)):this.gap={from:change.from.line,to:endLine+1},sizeChange)for(var i=0;i<this.matches.length;i++){var match=this.matches[i],newFrom=offsetLine(match.from.line,startLine,sizeChange),newFrom=(newFrom!=match.from.line&&(match.from=CodeMirror.Pos(newFrom,match.from.ch)),offsetLine(match.to.line,startLine,sizeChange));newFrom!=match.to.line&&(match.to=CodeMirror.Pos(newFrom,match.to.ch))}clearTimeout(this.update);var self=this;this.update=setTimeout(function(){self.updateAfterChange()},250)},SearchAnnotation.prototype.updateAfterChange=function(){this.findMatches(),this.annotation.update(this.matches)},SearchAnnotation.prototype.clear=function(){this.cm.off("change",this.changeHandler),this.annotation.clear()}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../dialog/dialog"],mod):mod(CodeMirror)})(function(CodeMirror){function interpretLine(cm,string){var num=Number(string);return/^[-+]/.test(string)?cm.getCursor().line+num:num-1}CodeMirror.commands.jumpToLine=function(cm){var cur=cm.getCursor();((cm,text,shortText,deflt,f)=>{cm.openDialog?cm.openDialog(text,f,{value:deflt,selectValueOnOpen:!0}):f(prompt(shortText,deflt))})(cm,(cm=>cm.phrase("Jump to line:")+' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use line:column or scroll% syntax)")+"</span>")(cm),cm.phrase("Jump to line:"),cur.line+1+":"+cur.ch,function(posStr){var match,line;posStr&&((match=/^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr))?cm.setCursor(interpretLine(cm,match[1]),Number(match[2])):(match=/^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr))?(line=Math.round(cm.lineCount()*Number(match[1])/100),/^[-+]/.test(match[1])&&(line=cur.line+line+1),cm.setCursor(line-1,cur.ch)):(match=/^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr))&&cm.setCursor(interpretLine(cm,match[1]),cur.ch))})},CodeMirror.keyMap.default["Alt-G"]="jumpToLine"}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function onCursorActivity(cm){cm.state.markedSelection&&cm.operation(function(){(cm=>{if(!cm.somethingSelected())return clear(cm);if(1<cm.listSelections().length)return reset(cm);var from=cm.getCursor("start"),to=cm.getCursor("end"),array=cm.state.markedSelection;if(!array.length)return coverRange(cm,from,to);var coverStart=array[0].find(),coverEnd=array[array.length-1].find();if(!coverStart||!coverEnd||to.line-from.line<=CHUNK_SIZE||0<=cmp(from,coverEnd.to)||cmp(to,coverStart.from)<=0)return reset(cm);for(;0<cmp(from,coverStart.from);)array.shift().clear(),coverStart=array[0].find();for(cmp(from,coverStart.from)<0&&(coverStart.to.line-from.line<CHUNK_SIZE?(array.shift().clear(),coverRange(cm,from,coverStart.to,0)):coverRange(cm,from,coverStart.from,0));cmp(to,coverEnd.to)<0;)array.pop().clear(),coverEnd=array[array.length-1].find();0<cmp(to,coverEnd.to)&&(to.line-coverEnd.from.line<CHUNK_SIZE?(array.pop().clear(),coverRange(cm,coverEnd.from,to)):coverRange(cm,coverEnd.to,to))})(cm)})}function onChange(cm){cm.state.markedSelection&&cm.state.markedSelection.length&&cm.operation(function(){clear(cm)})}CodeMirror.defineOption("styleSelectedText",!1,function(cm,val,old){old=old&&old!=CodeMirror.Init;val&&!old?(cm.state.markedSelection=[],cm.state.markedSelectionStyle="string"==typeof val?val:"CodeMirror-selectedtext",reset(cm),cm.on("cursorActivity",onCursorActivity),cm.on("change",onChange)):!val&&old&&(cm.off("cursorActivity",onCursorActivity),cm.off("change",onChange),clear(cm),cm.state.markedSelection=cm.state.markedSelectionStyle=null)});var CHUNK_SIZE=8,Pos=CodeMirror.Pos,cmp=CodeMirror.cmpPos;function coverRange(cm,from,to,addAt){if(0!=cmp(from,to))for(var array=cm.state.markedSelection,cls=cm.state.markedSelectionStyle,line=from.line;;){var start=line==from.line?from:Pos(line,0),endLine=line+CHUNK_SIZE,atEnd=endLine>=to.line,end=atEnd?to:Pos(endLine,0),start=cm.markText(start,end,{className:cls});if(null==addAt?array.push(start):array.splice(addAt++,0,start),atEnd)break;line=endLine}}function clear(cm){for(var array=cm.state.markedSelection,i=0;i<array.length;++i)array[i].clear();array.length=0}function reset(cm){clear(cm);for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++)coverRange(cm,ranges[i].from(),ranges[i].to())}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){CodeMirror.runMode=function(string,modespec,callback,options){for(var ie_lt9,node,col,mode=CodeMirror.getMode(CodeMirror.defaults,modespec),tabSize=options&&options.tabSize||CodeMirror.defaults.tabSize,lines=(callback.appendChild&&(ie_lt9=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<9),col=0,(node=callback).innerHTML="",callback=function(text,style){if("\n"==text)node.appendChild(document.createTextNode(ie_lt9?"\r":text)),col=0;else{for(var sp,content="",pos=0;;){var idx=text.indexOf("\t",pos);if(-1==idx){content+=text.slice(pos),col+=text.length-pos;break}col+=idx-pos,content+=text.slice(pos,idx);var size=tabSize-col%tabSize;col+=size;for(var i=0;i<size;++i)content+=" ";pos=idx+1}(style?((sp=node.appendChild(document.createElement("span"))).className="cm-"+style.replace(/ +/g," cm-"),sp):node).appendChild(document.createTextNode(content))}}),CodeMirror.splitLines(string)),state=options&&options.state||CodeMirror.startState(mode),i=0,e=lines.length;i<e;++i){i&&callback("\n");var stream=new CodeMirror.StringStream(lines[i],null,{lookAhead:function(n){return lines[i+n]},baseToken:function(){}});for(!stream.string&&mode.blankLine&&mode.blankLine(state);!stream.eol();){var style=mode.token(stream,state);callback(stream.current(),style,i,stream.start,state),stream.start=stream.pos}}}}),CodeMirror.defineMode("pyret",function(config,parserConfig){function wordRegexp(words){return new RegExp("^(("+words.join(")|(")+"))(?![a-zA-Z0-9-_])")}function toToken(type){return function(tstr){return{type:type,string:tstr}}}let pyret_ident_regex=new RegExp("^[a-zA-Z_][a-zA-Z0-9_-]*");var pyret_closing_keywords=["end"],pyret_closing_tokens=pyret_closing_keywords.map(toToken("keyword")).concat([].map(toToken("builtin"))),pyret_opening_keywords_colon=["reactor","try","ref-graph","block","table","load-table"],pyret_opening_keywords_nocolon=["include from","provide from","fun","when","for","if","let","type-let","ask","spy","cases","data","shared","check","except","letrec","lam","method","examples","do","select","extend","transform","extract","sieve","order","provide","provide-types"],pyret_opening_tokens=pyret_opening_keywords_colon.concat(pyret_opening_keywords_nocolon).map(toToken("keyword"));let pyret_openers_closed_by_end={FUN:!0,WHEN:!0,DO:!0,FOR:!0,IF:!0,BLOCK:!0,LET:!0,TABLE:!0,LOADTABLE:!0,SELECT:!0,EXTEND:!0,SIEVE:!0,TRANSFORM:!0,EXTRACT:!0,ORDER:!0,REACTOR:!0,SPY:!0,INCLUDEFROM:!0,PROVIDECOLON:!0},pyret_keywords=wordRegexp(["else if"].concat(pyret_opening_keywords_nocolon,pyret_closing_keywords,["spy","var","rec","import","include","type","newtype","hiding","from","lazy","shadow","ref","of","module","and","or","as","else","cases","is==","is=~","is<=>","is","satisfies","raises","violates","by","ascending","descending","sanitize","using","because","module","hiding"])),pyret_booleans=wordRegexp(["true","false"]),pyret_keywords_hyphen=wordRegexp(["type-let","does-not-raise","raises-violates","raises-satisfies","raises-other-than","is-roughly","is-not-roughly","is-not==","is-not=~","is-not<=>","is-not"]),pyret_keywords_colon=wordRegexp(pyret_opening_keywords_colon.concat(["doc","otherwise","then","with","sharing","where","do","row","source"])),pyret_single_punctuation=new RegExp("^(["+[":",".","<",">",",","^","!",";","|","=","+","*","/","\\\\","(",")","{","}","\\[","\\]"].join("")+"])"),pyret_double_punctuation=new RegExp("^(("+["<=>","::","=~","==",">=","<=","=>","->",":=","<>"].join(")|(")+"))"),initial_operators={"-":!0,"+":!0,"*":!0,"/":!0,"<":!0,"<=":!0,">":!0,">=":!0,"==":!0,"<>":!0,".":!0,"^":!0,"<=>":!0,"=~":!0,is:!0,"is==":!0,"is=~":!0,"is<=>":!0,because:!0,"is-roughly":!0,"is-not":!0,"is-not-roughly":!0,"is-not==":!0,"is-not=~":!0,"is-not<=>":!0,satisfies:!0,violates:!0,raises:!0,"raises-other-than":!0,"does-not-raise":!0,"raises-satisfies":!0,"raises-violates":!0},pyret_delimiter_type={NONE:0,OPENING:1,CLOSING:2,SUBKEYWORD:3,OPEN_CONTD:4,CLOSE_CONTD:5,SUB_CONTD:6,FOLD_OPEN_CONTD:7};function ret(state,tokType,content,style){return state.lastToken=tokType,state.lastContent=content,style}let number=new RegExp("^[-+]?[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?"),badNumber=new RegExp("^~?[+-]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?"),roughnum=new RegExp("^~[-+]?(?:[0-9]+/[0-9]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)"),restOfRoughnum=new RegExp("^[-+]?(?:[0-9]+/[0-9]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)"),rational=new RegExp("^[-+]?[0-9]+/[0-9]+");function tokenBase(stream,state){var squot_str,unterminated_string,dquot_str;return stream.eatSpace()?"IGNORED-SPACE":"#"===stream.peek()?stream.match("#|",!0)?(state.tokenizer=tokenizeBlockComment,state.commentNestingDepth=1,ret(state,"COMMENT-START",state.lastContent,"comment")):(stream.skipToEnd(),ret(state,"COMMENT",state.lastContent,"comment")):stream.match(roughnum,!1)?(stream.match("~"),state.tokenizer=tokenizeRoughnum,ret(state,"ROUGHNUM-START",stream.current(),"roughnum-start")):stream.match(rational)||stream.match(number)?ret(state,"number",stream.current(),"number"):stream.match(badNumber)?ret(state,"number",stream.current(),"bad-number"):(dquot_str=new RegExp('^"(?:\\\\[01234567]{1,3}|\\\\x[0-9a-fA-F]{1,2}|\\\\u[0-9a-fA-f]{1,4}|\\\\[\\\\nrt"\']|[^\\\\"\n\r])*"'),squot_str=new RegExp("^'(?:\\\\[01234567]{1,3}|\\\\x[0-9a-fA-F]{1,2}|\\\\u[0-9a-fA-f]{1,4}|\\\\[\\\\nrt\"']|[^\\\\'\n\r])*'"),unterminated_string=new RegExp("^[\"'].*"),state.maybeShorthandLambda=!1,(dquot_str=(dquot_str=stream.match(dquot_str,!0))||stream.match(squot_str,!0))?ret(state,"string",dquot_str[0],"string"):stream.match(/^```/,!0)?(state.tokenizer=tokenStringTriple,state.inString=stream.column(),state.lastToken="```",state.tokenizer(stream,state)):(dquot_str=stream.match(unterminated_string,!0))?ret(state,"string",dquot_str[0],"unterminated-string"):(dquot_str=stream.match(/^\.\.\./,!0))?ret(state,dquot_str[0],dquot_str[0],"builtin"):(dquot_str=stream.match(/^({(?=\())/,!0))?(state.maybeShorthandLambda=!0,ret(state,"{","{","builtin")):(dquot_str=(dquot_str=stream.match(pyret_double_punctuation,!0))||stream.match(pyret_single_punctuation,!0))?(!state.dataNoPipeColon||":"!=dquot_str[0]&&"|"!=dquot_str[0]||(state.dataNoPipeColon=!1),ret(state,dquot_str[0],dquot_str[0],"builtin")):(dquot_str=stream.match(pyret_keywords_hyphen,!0))?ret(state,dquot_str[0],dquot_str[0],"keyword"):(dquot_str=stream.match(pyret_keywords,!0))?("data"==dquot_str[0]&&(state.dataNoPipeColon=!0),ret(state,dquot_str[0],dquot_str[0],"keyword")):(dquot_str=stream.match(pyret_booleans,!0))?ret(state,dquot_str[0],dquot_str[0],"boolean"):(dquot_str=stream.match(pyret_keywords_colon,!0))?":"===stream.peek()?ret(state,dquot_str[0],dquot_str[0],"keyword"):ret(state,"name",dquot_str[0],"variable"):(dquot_str=stream.match(pyret_ident_regex))?"|"===state.lastToken||"::"===state.lastToken||"data"===state.lastToken||state.dataNoPipeColon?(state.dataNoPipeColon=!1,ret(state,"name",dquot_str[0],"type")):stream.match(/\s*\(/,!1)?ret(state,"name",dquot_str[0],"function-name"):ret(state,"name",dquot_str[0],"variable"):stream.eat("-")?ret(state,"-","-","builtin"):(stream.next(),null))}function tokenizeRoughnum(stream,state){return stream.match(restOfRoughnum),state.tokenizer=tokenBase,ret(state,"number",stream.current(),"roughnum")}function tokenizeBlockComment(stream,state){return stream.match("#|",!0)?(state.commentNestingDepth++,ret(state,"COMMENT-START",state.lastContent,"comment")):stream.match("|#",!0)?(state.commentNestingDepth--,0===state.commentNestingDepth&&(state.tokenizer=tokenBase),ret(state,"COMMENT-END",state.lastContent,"comment")):(stream.next(),stream.eatWhile(/[^#|]/),ret(state,"COMMENT",state.lastContent,"comment"))}function tokenStringTriple(stream,state){for(;!stream.eol();)if(stream.match(/[^`\\]*/,!0),stream.eat("\\")){if(stream.next(),stream.eol())return ret(state,"string",stream.current(),"string")}else{if(stream.match("```",!0))return state.tokenizer=tokenBase,state.inString=!1,ret(state,"string",stream.current(),"string");stream.next()}return ret(state,"string",stream.current(),"string")}function Indent(funs,cases,data,shared,trys,except,graph,parens,objects,vars,fields,initial,comments){this.fn=funs||0,this.c=cases||0,this.d=data||0,this.s=shared||0,this.t=trys||0,this.e=except||0,this.g=graph||0,this.p=parens||0,this.o=objects||0,this.v=vars||0,this.f=fields||0,this.i=initial||0,this.comments=comments||0}function LineState(tokens,nestingsAtLineStart,nestingsAtLineEnd,deferedOpened,curOpened,deferedClosed,curClosed,delimType){this.tokens=tokens,this.nestingsAtLineStart=nestingsAtLineStart,this.nestingsAtLineEnd=nestingsAtLineEnd,this.deferedOpened=deferedOpened,this.curOpened=curOpened,this.deferedClosed=deferedClosed,this.curClosed=curClosed,this.delimType=delimType}function peek(arr){return arr[arr.length-1]}function hasTop(arr,wanted){if(wanted instanceof Array){for(var i=0;i<wanted.length;i++)if(arr[arr.length-1-i]!==wanted[i])return;return 1}return arr[arr.length-1]===wanted}function parse(firstTokenInLine,state,stream,style){var inOpening=(ls=state.lineState).delimType===pyret_delimiter_type.OPENING||ls.delimType===pyret_delimiter_type.OPEN_CONTD,inSubkw=ls.delimType===pyret_delimiter_type.SUBKEYWORD||ls.delimType===pyret_delimiter_type.SUB_CONTD;if(ls.delimType=pyret_delimiter_type.NONE,firstTokenInLine&&(ls.nestingsAtLineStart=ls.nestingsAtLineEnd.copy()),"name"===state.lastToken&&"function-name"===style&&hasTop(ls.tokens,["WANTOPENPAREN","WANTCLOSEPAREN","WANTCOLONORBLOCK","FUN"])&&inOpening&&(ls.delimType=pyret_delimiter_type.FOLD_OPEN_CONTD),ls.lastToken=state.lastToken,0<ls.nestingsAtLineStart.comments||0<ls.curOpened.comments||0<ls.deferedOpened.comments)"COMMENT-END"===state.lastToken?0<ls.curOpened.comments?ls.curOpened.comments--:0<ls.deferedOpened.comments?ls.deferedOpened.comments--:firstTokenInLine?ls.curClosed.comments++:ls.deferedClosed.comments++:"COMMENT-START"===state.lastToken&&ls.deferedOpened.comments++;else if("COMMENT-START"===state.lastToken)ls.deferedOpened.comments++;else if("COMMENT"!==state.lastToken)if(hasTop(ls.tokens,"NEEDSOMETHING"))ls.tokens.pop(),hasTop(ls.tokens,"VAR")&&0<ls.deferedOpened.v&&(ls.deferedOpened.v--,ls.tokens.pop()),parse(firstTokenInLine,state,stream,style);else if(firstTokenInLine&&(initial_operators[state.lastToken]&&("."==state.lastToken||stream.match(/^\s+/))||"is"===state.lastToken&&stream.match(/^%/)||"is-not"===state.lastToken&&stream.match(/^%/)))ls.curOpened.i++,ls.deferedClosed.i++;else if(":"===state.lastToken)inOpening?ls.delimType=pyret_delimiter_type.OPEN_CONTD:inSubkw&&(ls.delimType=pyret_delimiter_type.SUB_CONTD),hasTop(ls.tokens,"WANTCOLON")||hasTop(ls.tokens,"WANTCOLONOREQUAL")||hasTop(ls.tokens,"WANTCOLONORBLOCK")||hasTop(ls.tokens,"WANTCOLONORSTAR")?ls.tokens.pop():(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"REACTOR")||hasTop(ls.tokens,"SHARED")||hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&((hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("OBJECT")),ls.deferedOpened.f++,ls.tokens.push("FIELD","NEEDSOMETHING"));else if(";"===state.lastToken)(hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("TUPLE"));else if("::"===state.lastToken)(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"SHARED"))&&(ls.deferedOpened.f++,ls.tokens.push("FIELD","NEEDSOMETHING"));else if(","===state.lastToken)hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.deferedClosed.f++);else if("="===state.lastToken)if(hasTop(ls.tokens,"WANTCOLONOREQUAL"))ls.tokens.pop();else{for(;hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.curClosed.v++;ls.deferedOpened.v++,ls.tokens.push("VAR","NEEDSOMETHING")}else if("var"===state.lastToken||"rec"===state.lastToken)ls.deferedOpened.v++,ls.tokens.push("VAR","NEEDSOMETHING","WANTCOLONOREQUAL");else if("fun"===state.lastToken||"method"===state.lastToken||"lam"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FUN","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("method"===state.lastToken)(hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("OBJECT")),ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FUN","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("let"===state.lastToken||"letrec"===state.lastToken||"type-let"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("LET","WANTCOLONORBLOCK");else if("when"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("WHEN","WANTCOLONORBLOCK");else if("do"===state.lastToken)hasTop(ls.tokens,"DO")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WHEN","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("for"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FOR","WANTCOLONORBLOCK");else if("cases"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.c++,ls.tokens.push("CASES","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("data"!==state.lastToken||(hasTop(ls.tokens,"INCLUDEFROMBODY")||hasTop(ls.tokens,"PROVIDE")||hasTop(ls.tokens,"PROVIDEFROMBODY")))if("ask"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.c++,ls.tokens.push("IFCOND","WANTCOLONORBLOCK");else if("spy"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SPY","WANTCOLON");else if("if"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("IF","WANTCOLONORBLOCK","NEEDSOMETHING");else if("else if"===state.lastToken)hasTop(ls.tokens,"IF")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON","NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("else"===state.lastToken)hasTop(ls.tokens,"IF")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("row"===state.lastToken)hasTop(ls.tokens,"TABLEROW")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"TABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("TABLEROW","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("source"===state.lastToken)hasTop(ls.tokens,"LOADTABLESPEC")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("NEEDSOMETHING","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"LOADTABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("LOADTABLESPEC","NEEDSOMETHING","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("sanitize"===state.lastToken)hasTop(ls.tokens,"LOADTABLESPEC")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"LOADTABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("LOADTABLESPEC","NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("|"===state.lastToken)hasTop(ls.tokens,["OBJECT","DATA"])||hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++),hasTop(ls.tokens,"OBJECT")&&ls.tokens.pop()):hasTop(ls.tokens,"DATA")&&ls.tokens.push("NEEDSOMETHING");else if("with"===state.lastToken)hasTop(ls.tokens,["WANTOPENPAREN","WANTCLOSEPAREN","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.push("OBJECT","WANTCOLON")):hasTop(ls.tokens,["DATA"])&&ls.tokens.push("OBJECT","WANTCOLON");else if("provide"===state.lastToken)ls.tokens.push("PROVIDE","WANTCOLONORSTAR"),ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.s++;else if("sharing"===state.lastToken)ls.curClosed.d++,ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.SUBKEYWORD,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.pop(),ls.curClosed.o++,ls.tokens.push("SHARED","WANTCOLON")):hasTop(ls.tokens,["OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.push("SHARED","WANTCOLON")):hasTop(ls.tokens,"DATA")&&(ls.tokens.pop(),ls.tokens.push("SHARED","WANTCOLON"));else if("where"===state.lastToken||"examples"===state.lastToken&&0<ls.tokens.length)ls.delimType="where"===state.lastToken?pyret_delimiter_type.SUBKEYWORD:pyret_delimiter_type.OPENING,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.curClosed.o++,ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,["OBJECT","DATA"])?(ls.tokens.pop(),ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,"DATA")?(ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,"FUN")?(ls.curClosed.f++,ls.deferedOpened.s++):hasTop(ls.tokens,"SHARED")&&(ls.curClosed.s++,ls.deferedOpened.s++),ls.tokens.pop(),ls.tokens.push("CHECK","WANTCOLON");else if("check"===state.lastToken||"examples"===state.lastToken&&0===ls.tokens.length)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.s++,ls.tokens.push("CHECK","WANTCOLON");else if("try"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.t++,ls.tokens.push("TRY","WANTCOLON");else if("except"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,0<ls.curOpened.t?ls.curOpened.t--:0<ls.deferedOpened.t?ls.deferedOpened.t--:ls.curClosed.t++,hasTop(ls.tokens,"TRY")&&(ls.tokens.pop(),ls.tokens.push("WANTCOLON","WANTCLOSEPAREN","WANTOPENPAREN"));else if("then"===state.lastToken||"otherwise"===state.lastToken)ls.delimType=pyret_delimiter_type.SUBKEYWORD;else if("block"===state.lastToken)hasTop(ls.tokens,"WANTCOLONORBLOCK")?ls.delimType=pyret_delimiter_type.SUBKEYWORD:(ls.deferedOpened.fn++,ls.tokens.push("BLOCK","WANTCOLON"),ls.delimType=pyret_delimiter_type.OPENING);else if("reactor"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("REACTOR","WANTCOLON");else if("table"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("TABLE","WANTCOLON");else if("load-table"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("LOADTABLE","WANTCOLON");else if("select"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SELECT","WANTCOLON");else if("extend"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("EXTEND","WANTCOLON");else if("transform"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("TRANSFORM","WANTCOLON");else if("extract"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("EXTRACT","WANTCOLON");else if("sieve"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SIEVE","WANTCOLON");else if("order"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("ORDER","WANTCOLON");else if("ref-graph"===state.lastToken)ls.deferedOpened.g++,ls.tokens.push("GRAPH","WANTCOLON");else if("["===state.lastToken)ls.deferedOpened.o++,ls.tokens.push("ARRAY"),ls.delimType=pyret_delimiter_type.OPENING;else if("]"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,firstTokenInLine?ls.curClosed.o++:ls.deferedClosed.o++,hasTop(ls.tokens,"ARRAY")&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("{"===state.lastToken&&hasTop(ls.tokens,["WANTRECORDORSTAR"]))ls.delimType=pyret_delimiter_type.OPEN_CONTD;else if("{"===state.lastToken)ls.deferedOpened.o++,state.maybeShorthandLambda?ls.tokens.push("BRACEDEXPR"):ls.tokens.push("BRACEDEXPR_NOLAMBDA"),ls.delimType=pyret_delimiter_type.OPENING;else if("}"===state.lastToken&&hasTop(ls.tokens,["WANTRECORDORSTAR"]))firstTokenInLine?ls.curClosed.s++:ls.deferedClosed.s++,ls.tokens.pop(),ls.tokens.pop(),ls.delimType=pyret_delimiter_type.CLOSING;else if("}"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,firstTokenInLine?ls.curClosed.o++:ls.deferedClosed.o++,hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++),(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA")||hasTop(ls.tokens,"TUPLE")||hasTop(ls.tokens,"SHORTHANDLAMBDA"))&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("("===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.p++,hasTop(ls.tokens,"WANTOPENPAREN")?ls.tokens.pop():hasTop(ls.tokens,"BRACEDEXPR")?(ls.tokens.pop(),ls.tokens.push("SHORTHANDLAMBDA","WANTCOLONORBLOCK")):hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"SHARED")?(ls.tokens.push("FUN","WANTCOLONORBLOCK"),ls.deferedOpened.fn++):ls.tokens.push("WANTCLOSEPAREN");else if(")"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,0<ls.curOpened.p?ls.curOpened.p--:0<ls.deferedOpened.p?ls.deferedOpened.p--:ls.deferedClosed.p++,hasTop(ls.tokens,"WANTCLOSEPAREN")&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("end"===state.lastToken){ls.delimType=pyret_delimiter_type.CLOSING,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.curClosed.f++,ls.tokens.pop(),ls.tokens.pop()):hasTop(ls.tokens,["OBJECT","DATA"])?ls.tokens.pop():(hasTop(ls.tokens,["TABLEROW","TABLE"])||hasTop(ls.tokens,["LOADTABLESPEC","LOADTABLE"]))&&(ls.tokens.pop(),ls.curClosed.o++);for(var top=peek(ls.tokens),stillUnclosed=!0;stillUnclosed&&ls.tokens.length;)"OBJECT"===top||"ARRAY"===top?0<ls.curOpened.o?ls.curOpened.o--:0<ls.deferedOpened.o?ls.deferedOpened.o--:ls.curClosed.o++:"WANTCLOSEPAREN"===top?0<ls.curOpened.p?ls.curOpened.p--:0<ls.deferedOpened.p?ls.deferedOpened.p--:ls.curClosed.p++:"FIELD"===top?0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++:"VAR"===top?0<ls.curOpened.v?ls.curOpened.v--:0<ls.deferedOpened.v?ls.deferedOpened.v--:ls.curClosed.v++:"PROVIDE"===top||"INCLUDEFROM"==top?0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++:"INCLUDEFROMBODY"==top||"PROVIDEFROMBODY"==top?(0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++,ls.tokens.pop()):!0===pyret_openers_closed_by_end[top]?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,stillUnclosed=!1):"CASES"===top||"IFCOND"===top?(0<ls.curOpened.c?ls.curOpened.c--:0<ls.deferedOpened.c?ls.deferedOpened.c--:ls.curClosed.c++,stillUnclosed=!1):"DATA"===top?(0<ls.curOpened.d?ls.curOpened.d--:0<ls.deferedOpened.d?ls.deferedOpened.d--:ls.curClosed.d++,stillUnclosed=!1):"SHARED"===top||"CHECK"===top?(0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++,stillUnclosed=!1):"TRY"===top?(0<ls.curOpened.t?ls.curOpened.t--:0<ls.deferedOpened.t?ls.deferedOpened.t--:ls.curClosed.t++,stillUnclosed=!1):"EXCEPT"===top?(0<ls.curOpened.e?ls.curOpened.e--:0<ls.deferedOpened.e?ls.deferedOpened.e--:ls.curClosed.e++,stillUnclosed=!1):"GRAPH"===top&&(0<ls.curOpened.g?ls.curOpened.g--:0<ls.deferedOpened.g?ls.deferedOpened.g--:ls.curClosed.g++,stillUnclosed=!1),ls.tokens.pop(),top=peek(ls.tokens)}else"*"===state.lastToken&&(hasTop(ls.tokens,["WANTCOLONORSTAR","PROVIDE"])||hasTop(ls.tokens,["WANTRECORDORSTAR","PROVIDETYPES"]))?(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop(),ls.tokens.pop()):"include from"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("INCLUDEFROM")):"provide from"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("PROVIDEFROM")):"provide-types"==state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("PROVIDETYPES","WANTRECORDORSTAR")):"include"==state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("INCLUDE")):"import"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("IMPORT","WANTFROMORAS")):"from"!==state.lastToken&&"as"!==state.lastToken||!hasTop(ls.tokens,["WANTFROMORAS"])?"name"===state.lastToken&&hasTop(ls.tokens,["INCLUDE"])?(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop()):"name"===state.lastToken&&(hasTop(ls.tokens,["INCLUDEFROM"])||hasTop(ls.tokens,["PROVIDEFROM"]))?(ls.delimType=pyret_delimiter_type.OPEN_CONTD,style=ls.tokens[ls.tokens.length-1]+"BODY",ls.tokens.push(style,"WANTCOLON")):"name"===state.lastToken&&hasTop(ls.tokens,["IMPORT"])&&(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop()):ls.tokens.pop();else ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.d++,ls.tokens.push("DATA","WANTCOLON","NEEDSOMETHING");if(stream.match(/\s*$/,!1)){for(ls.nestingsAtLineStart.addSelf(ls.curOpened).subSelf(ls.curClosed);hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.curClosed.v++;ls.nestingsAtLineEnd.addSelf(ls.curOpened).addSelf(ls.deferedOpened).subSelf(ls.curClosed).subSelf(ls.deferedClosed),ls.tokens=ls.tokens.concat([]),ls.curOpened.zeroOut(),ls.deferedOpened.zeroOut(),ls.curClosed.zeroOut(),ls.deferedClosed.zeroOut()}}Indent.prototype.toString=function(){return"Fun "+this.fn+", Cases "+this.c+", Data "+this.d+", Shared "+this.s+", Try "+this.t+", Except "+this.e+", Graph "+this.g+", Parens "+this.p+", Object "+this.o+", Vars "+this.v+", Fields "+this.f+", Initial "+this.i+", Comment depth "+this.comments},Indent.prototype.copy=function(){return new Indent(this.fn,this.c,this.d,this.s,this.t,this.e,this.g,this.p,this.o,this.v,this.f,this.i,this.comments)},Indent.prototype.zeroOut=function(){this.fn=this.c=this.d=this.s=this.t=this.e=this.g=this.p=this.o=this.v=this.f=this.i=this.comments=0},Indent.prototype.addSelf=function(that){return this.fn+=that.fn,this.c+=that.c,this.d+=that.d,this.s+=that.s,this.t+=that.t,this.e+=that.e,this.g+=that.g,this.p+=that.p,this.o+=that.o,this.v+=that.v,this.f+=that.f,this.i+=that.i,this.comments+=that.comments,this},Indent.prototype.add=function(that){return this.copy().addSelf(that)},Indent.prototype.subSelf=function(that){return this.fn-=that.fn,this.c-=that.c,this.d-=that.d,this.s-=that.s,this.t-=that.t,that.e-=that.e,this.g-=that.g,this.p-=that.p,this.o-=that.o,this.v-=that.v,this.f-=that.f,this.i-=that.i,this.comments-=that.comments,this},Indent.prototype.sub=function(that){return this.copy().subSelf(that)},LineState.prototype.copy=function(){return new LineState(this.tokens.concat([]),this.nestingsAtLineStart.copy(),this.nestingsAtLineEnd.copy(),this.deferedOpened.copy(),this.curOpened.copy(),this.deferedClosed.copy(),this.curClosed.copy(),this.delimType)},LineState.prototype.print=function(){console.log("LineState is:"),console.log(" NestingsAtLineStart = "+this.nestingsAtLineStart),console.log(" NestingsAtLineEnd = "+this.nestingsAtLineEnd),console.log(" DeferedOpened = "+this.deferedOpened),console.log(" DeferedClosed = "+this.deferedClosed),console.log(" CurOpened = "+this.curOpened),console.log(" CurClosed = "+this.curClosed),console.log(" Tokens = "+this.tokens),console.log(" LastToken = "+this.lastToken)};let INDENTATION=new Indent(1,2,2,1,1,1,1,1,1,1,1,1,1.5);function copyState(oldState){return{tokenizer:oldState.tokenizer,lineState:oldState.lineState.copy(),lastToken:oldState.lastToken,lastContent:oldState.lastContent,commentNestingDepth:oldState.commentNestingDepth,inString:oldState.inString,dataNoPipeColon:oldState.dataNoPipeColon,sol:oldState.sol,maybeShorthandLambda:oldState.maybeShorthandLambda}}return{startState:function(basecolumn){return{tokenizer:tokenBase,inString:!1,commentNestingDepth:0,lineState:new LineState([],new Indent,new Indent,new Indent,new Indent,new Indent,new Indent,pyret_delimiter_type.NONE),sol:!0}},blankLine:function(state){state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy()},lineComment:"#",blockCommentStart:"#|",blockCommentEnd:"|#",blockCommentLead:" ",copyState:copyState,token:function(stream,state){!state.sol&&stream.sol()&&(state.sol=!0,state.indentation=stream.indentation());var style=state.tokenizer(stream,state);return"IGNORED-SPACE"===style?null:(parse(state.sol,state,stream,style),state.sol=!1,style)},indent:function(state,textAfter,fullLine){var indentUnit=config.indentUnit,taSS=new CodeMirror.StringStream(textAfter,config.tabSize),sol=!0,inString=state.inString;if(0<(state=copyState(state)).commentNestingDepth&&(state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy()),/^\s*$/.test(textAfter))state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy();else for(;!taSS.eol();){var style=state.tokenizer(taSS,state);"IGNORED-SPACE"!==style&&(parse(sol,state,taSS,style),sol=!1)}var key,indentSpec=state.lineState.nestingsAtLineStart,indent=0;for(key in INDENTATION)INDENTATION.hasOwnProperty(key)&&(indent+=(indentSpec[key]||0)*INDENTATION[key]);return 0<indentSpec.comments||!1!==inString?0<(textAfter=fullLine.match(/\s*/)[0].length)?textAfter:!1!==inString?inString:indent*indentUnit:/^\s*\|([^#]|$)/.test(fullLine)?(indent-1)*indentUnit:indent*indentUnit},electricInput:new RegExp("(?:[de.\\]}|:]||#|[-enst\\*\\+/=<>^~]\\s|is%|is-not%)$"),fold:"pyret",delimiters:{opening:pyret_opening_tokens,closing:pyret_closing_tokens,subkeywords:{if:["block","else if","else"],when:["block"],fun:["block","where"],method:["block","where"],lam:["block"],for:["block","do"],let:["block"],letrec:["block"],"type-let":["block"],cases:["block"],ask:["block","then","otherwise"],data:["sharing","where"],table:["row"],"load-table":["sanitize","source"],import:["from","as"],provide:["from"],include:["from"]},lastSubkeywords:{if:"else"},special:[{start:"(",ends:[")"]},{start:"[",ends:["]"]},{start:"{",ends:["}"]},{start:"provide",ends:["*","name","type"]},{start:"include",ends:["name","type"]},{start:"import",ends:["name","type"]},{start:"provide-types",ends:["*","}"]}],types:pyret_delimiter_type},unprefixedContexts:["SHARED","OBJECT"],blockCommentStart:"#|",blockCommentEnd:"|#",blockCommentContinue:"",lineComment:"#"}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var Pos=CodeMirror.Pos;function cmpClosest(a,b,c){var ret=a.line-c.line;return ret||(a.ch<=c.ch&&c.ch<=b.ch?0:Math.abs(a.ch-c.ch)<Math.abs(b.ch-c.ch)?a.ch-c.ch:b.ch-c.ch)}function keyMatches(open,close,isFunctionName){"string"!=typeof open?open=isFunctionName||"function-name"===open.type?"fun":open.string:isFunctionName&&(open="fun");isFunctionName="string"==typeof close?close:close.string;if(-1!=DELIMS.indexOf(open)&&-1!=ENDDELIM.indexOf(isFunctionName))return!0;for(var closeType="string"==typeof close?close:close.state.lastToken,i=0;i<SPECIALDELIM.length;i++)if(open===SPECIALDELIM[i].start)return SPECIALDELIM[i].ends.includes(closeType);return!1}function fieldOneOf(fname){var oneOf=Array.prototype.slice.call(arguments,1);return function(obj){for(var fval=obj[fname],i=0;i<oneOf.length;i++)if(fval===oneOf[i])return!0;return!1}}function negate(func){return function(){return!func.apply(this,arguments)}}function getField(fname){return function(o){return o[fname]}}function hasDuplicates(array){for(var valuesSoFar=Object.create(null),i=0;i<array.length;++i){var value=array[i];if(value in valuesSoFar)return 1;valuesSoFar[value]=!0}}var pyretMode=CodeMirror.getMode({},"pyret");if("null"===pyretMode.name)throw Error("Pyret Mode not Defined");if(!(pyretMode.delimiters&&pyretMode.delimiters.opening&&pyretMode.delimiters.closing&&pyretMode.delimiters.subkeywords&&pyretMode.delimiters.lastSubkeywords&&pyretMode.delimiters.special&&pyretMode.delimiters.types))throw Error("No correct delimiters defined in Pyret Mode");if(pyretMode.delimiters.opening.some(negate(fieldOneOf("type","keyword","builtin")))||pyretMode.delimiters.closing.some(negate(fieldOneOf("type","keyword","builtin"))))throw Error("Pyret Mode contains delimiters of unknown type");var DELIMS=pyretMode.delimiters.opening.map(getField("string")),ENDDELIM=pyretMode.delimiters.closing.map(getField("string")),UPFXCONTEXTS=pyretMode.unprefixedContexts;if(!DELIMS||!ENDDELIM||!UPFXCONTEXTS)throw Error("Pyret Mode missing required exports.");if(hasDuplicates(DELIMS)||hasDuplicates(ENDDELIM))throw Error("Pyret Mode contains duplicate delimiter string values");var SPECIALDELIM=pyretMode.delimiters.special,SUBKEYWORDS=pyretMode.delimiters.subkeywords,DELIMTYPES=pyretMode.delimiters.types,LASTSUBKEYWORDS=(new RegExp("("+DELIMS.join("|")+"|"+ENDDELIM.join("|")+"|\\(|\\)|\\[|\\]|{|})","g"),pyretMode.delimiters.lastSubkeywords),INV_SUBKEYWORDS={},INV_LASTSUBKEYWORDS=(Object.keys(SUBKEYWORDS).forEach(function(key){SUBKEYWORDS[key].forEach(function(skw){INV_SUBKEYWORDS[skw]=INV_SUBKEYWORDS[skw]||[],INV_SUBKEYWORDS[skw].push(key)})}),{}),INV_DELIMTYPES=(Object.keys(LASTSUBKEYWORDS).forEach(function(key){var kw=LASTSUBKEYWORDS[key];INV_LASTSUBKEYWORDS[kw]=INV_LASTSUBKEYWORDS[kw]||[],INV_LASTSUBKEYWORDS[kw].push(key)}),{});function TokenTape(cm,line,ch,range){if(this.line=line,this.startCh=ch,this.cm=cm,this.min=range?range.from:cm.firstLine(),this.max=range?range.to-1:cm.lastLine(),this.lineToks=cm.getLineTokens(line),this.dbg=CodeMirror.debugInternal,ch<=1){for(this.current=0;this.current<this.lineToks.length&&!this.lineToks[this.current].type;)++this.current;this.current>=this.lineToks.length&&(this.current=null)}else{for(var i=0;i<this.lineToks.length;i++)if(this.lineToks[i].start<ch&&this.lineToks[i].end>=ch){this.current=i;break}void 0===this.current&&(console.warn("TokenTape: Given invalid start ch of "+ch+". Defaulting to last."),this.current=this.lineToks.length-1)}(this.cachedLine=null)===this.current?this.curRegion=null:0<this.lineToks.length?this.curRegion={start:Pos(this.line,this.lineToks[this.current].start),end:Pos(this.line,this.lineToks[this.current].end)}:this.curRegion={start:Pos(this.line,0),end:Pos(this.line,0)}}function posToString(p){return p?"{line: "+p.line+", ch: "+p.ch+"}":"null"}function tokenToString(t){return"{start: "+t.start+", end: "+t.end+", string: '"+t.string+"', type: "+t.type+", delimType: "+INV_DELIMTYPES[t.state.lineState.delimType]+"}"}function TokenTapeClone(tt){tt instanceof TokenTapeClone&&(tt=tt.__wrapped),this.__wrapped=tt,this.line=tt.line,this.cm=tt.cm,this.min=tt.min,this.max=tt.max,this.lineToks=tt.lineToks.slice(0),this.current=tt.current,this.cachedLine=tt.cachedLine,this.curRegion={start:tt.curRegion.start,end:tt.curRegion.end}}function IterResult(token,fail,subs,badSubs){this.token=token,this.fail=fail,this.subs=subs||[],this.badSubs=badSubs||[]}function initializeTape(cm,pos,foldOpen,range){var ttape=new TokenTape(cm,pos.line,pos.ch,range),start=ttape.findInit(foldOpen);if(ttape.dbg&&ttape.dbg.writeLn("Start token: "+(start&&tokenToString(start))),!start||(cm=Pos(start.line,start.start),range=pos,0<(cm.line-range.line||cm.ch-range.ch)))return{ttape:ttape,didNotMatch:!0};var startType=start.state.lineState.delimType;switch(startType){case DELIMTYPES.NONE:return ttape.dbg&&ttape.dbg.writeLn("Invalid delimiter type."),{ttape:ttape,didNotMatch:!0};case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.CLOSE_CONTD:case DELIMTYPES.SUB_CONTD:if(!foldOpen){if(!ttape.snapBack())return{ttape:ttape,didNotMatch:!0};startType=(start=ttape.cur()).state.lineState.delimType;break}case DELIMTYPES.FOLD_OPEN_CONTD:if(!ttape.snapBack())return{ttape:ttape,didNotMatch:!0};startType=(start=ttape.cur()).state.lineState.delimType}return{ttape:ttape,start:start,startType:startType,here:{from:Pos(start.line,start.start),to:Pos(start.line,start.end),token:start},didNotMatch:!1}}Object.keys(DELIMTYPES).forEach(function(key){INV_DELIMTYPES[DELIMTYPES[key]]=key}),TokenTape.prototype.toString=function(){for(var r,ret="TokenTape:\n\tline: "+this.line+"\n\tmin: "+this.min+"\n\tmax: "+this.max+"\n\tlineToks: [",i=0;i<this.lineToks.length;++i)0<i&&(ret+=",\n\t "),ret+="["+i+"] "+tokenToString(this.lineToks[i]);return ret+="]\n\tcurrent: "+this.current+"\n\tcurRegion: "+((r=this.curRegion)?"{start: "+posToString(r.start)+", end: "+posToString(r.end)+"}":"null")},TokenTapeClone.prototype=Object.create(TokenTape.prototype),TokenTape.prototype.clone=function(){return new TokenTapeClone(this)},TokenTape.prototype.setIndex=function(idx){this.current=idx,this.curRegion={start:Pos(this.line,this.lineToks[idx].start),end:Pos(this.line,this.lineToks[idx].end)}},TokenTape.prototype.nextLine=function(){var newCached;return this.line>=this.max?(this.current=null,this.curRegion=null,!1):(newCached={dir:-1,toks:this.lineToks},this.cachedLine&&1===this.cachedLine.dir?(this.lineToks=this.cachedLine.toks,++this.line):this.lineToks=this.cm.getLineTokens(++this.line),this.cachedLine=newCached,0===this.lineToks.length?this.nextLine():(this.setIndex(0),!0))},TokenTape.prototype.prevLine=function(){var newCached;return this.line<=this.min?(this.current=null,this.curRegion=null,!1):(newCached={dir:1,toks:this.lineToks},this.cachedLine&&-1===this.cachedLine.dir?(this.lineToks=this.cachedLine.toks,--this.line):this.lineToks=this.cm.getLineTokens(--this.line),this.cachedLine=newCached,0===this.lineToks.length?this.prevLine():(this.setIndex(this.lineToks.length-1),!0))},TokenTape.prototype.getContinued=function(){var contdType,idx=this.current,tok=this.lineToks[idx];if(this.current!==this.lineToks.length-1){switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:contdType=DELIMTYPES.OPEN_CONTD;break;case DELIMTYPES.CLOSING:contdType=DELIMTYPES.CLOSE_CONTD;break;case DELIMTYPES.SUBKEYWORD:contdType=DELIMTYPES.SUB_CONTD;break;default:return console.warn("getContinued called with bad current token"),void console.warn(tok)}for(;++idx<this.lineToks.length;)if(this.lineToks[idx].type){if(this.lineToks[idx].state.lineState.delimType!==contdType)break;tok=this.lineToks[idx]}this.curRegion.end=Pos(this.line,tok.end)}},TokenTape.prototype.getFoldingContinued=function(){var idx=this.current,tok=this.lineToks[idx];if(this.current!==this.lineToks.length-1){var contdType,foldContdType=null;switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:contdType=DELIMTYPES.OPEN_CONTD,foldContdType=DELIMTYPES.FOLD_OPEN_CONTD;break;case DELIMTYPES.CLOSING:contdType=DELIMTYPES.CLOSE_CONTD;break;case DELIMTYPES.SUBKEYWORD:contdType=DELIMTYPES.SUB_CONTD;break;default:return console.warn("getFoldingContinued called with bad current token"),void console.warn(tok)}for(;++idx<this.lineToks.length;)if(this.lineToks[idx].type){if(this.lineToks[idx].state.lineState.delimType!==contdType&&this.lineToks[idx].state.lineState.delimType!==foldContdType)break;tok=this.lineToks[idx]}this.curRegion.end=Pos(this.line,tok.end)}},TokenTape.prototype.snapBack=function(){var idx=this.current,tok=this.lineToks[idx];if(0===this.current)return!1;var initType,contdType=tok.state.lineState.delimType;switch(contdType){case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.FOLD_OPEN_CONTD:initType=DELIMTYPES.OPENING;break;case DELIMTYPES.CLOSE_CONTD:initType=DELIMTYPES.CLOSING;break;case DELIMTYPES.SUB_CONTD:initType=DELIMTYPES.SUBKEYWORD;break;default:console.warn("snapBack called with bad current token"),console.warn(tok)}for(;0<=--idx;)if(this.lineToks[idx].type){var curType=this.lineToks[idx].state.lineState.delimType;if(curType===initType)return this.setIndex(idx),!0;if(curType!==contdType)return!1}},TokenTape.prototype.move=function(dir,opts){if(null===this.current&&this.line<=this.min&&-1===dir)return!1;if(null===this.current&&this.line>=this.max&&1===dir)return!1;if(1!==dir&&-1!==dir)return console.warn("Expected direction of 1 or -1. Given: "+dir),!1;opts=opts||{};var moveLine=(1===dir?this.nextLine:this.prevLine).bind(this),isEOL=1===dir?function(i){return i>=this.lineToks.length-1}.bind(this):function(i){return i<=0},idx=this.current;for(this.lineToks[this.current];;){if(isEOL(idx)){if(!moveLine())return!1;idx=this.current}else idx+=dir;if((tok=>{if(tok.type){if(opts.includeContd)switch(tok.state.lineState.delimType){case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.CLOSE_CONTD:case DELIMTYPES.SUB_CONTD:return 1;case DELIMTYPES.FOLD_OPEN_CONTD:if(opts.includeFoldContd)return 1}switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:case DELIMTYPES.CLOSING:case DELIMTYPES.SUBKEYWORD:return 1;default:return}}})(this.lineToks[idx]))return this.setIndex(idx),!0}},TokenTape.prototype.next=function(opts){return this.move(1,opts),this.cur()},TokenTape.prototype.prev=function(){return this.move(-1),this.cur()},TokenTape.prototype.cur=function(){var ret;return null===this.current||0===this.lineToks.length?null:((ret=this.lineToks[this.current]).line=this.line,ret)},TokenTape.prototype.findInit=function(folding){var cur=this.cur(),dbg=this.dbg;if(dbg&&this.dbg.writeLn("cur: "+(cur&&tokenToString(cur))),!cur)return null;function matchesFwd(tok){var diff,sameLine,allowed;return!(!tok||!tok.type)&&(diff=cmpClosest(Pos(tok.line,tok.start),Pos(tok.line,tok.end),startPos),sameLine=tok.line===startPos.line,allowed=tok.start<=truePos.ch,dbg&&dbg.writeLn("matchFwd: "+(tok&&tokenToString(tok))+"; diff = "+diff+"; sameLine = "+sameLine+"; allowed = "+allowed),sameLine)&&0===diff&&allowed}function matchesBwd(tok){var diff,sameLine;return!(!tok||!tok.type)&&(diff=cmpClosest(Pos(tok.line,tok.start),Pos(tok.line,tok.end),truePos),sameLine=tok.line===startPos.line,dbg&&dbg.writeLn("matchBwd: "+(tok&&tokenToString(tok))+"; diff = "+diff+"; sameLine = "+sameLine),sameLine)&&0===diff}var startPos=Pos(this.line,this.startCh+1),truePos=Pos(this.line,this.startCh),curIdx=(dbg&&(dbg.writeLn("startPos: "+posToString(startPos)),dbg.writeLn("truePos: "+posToString(truePos))),this.current);if(dbg&&this.dbg.writeLn("Checking if left at current position is closing"),matchesBwd(cur)&&cur.state.lineState.delimType===DELIMTYPES.CLOSING)return cur;if(dbg&&this.dbg.writeLn("Checking forward at current position"),(()=>{for(;this.line<startPos.line;)this.nextLine();this.setIndex(curIdx)})(),matchesFwd(cur))return cur;dbg&&this.dbg.writeLn("Checking right adjacent token");folding=this.next({includeContd:!0,includeFoldContd:folding});return matchesFwd(folding)?folding:((()=>{for(;this.line>startPos.line;)this.prevLine();this.setIndex(curIdx)})(),dbg&&this.dbg.writeLn("Checking for any on left"),matchesBwd(cur)?cur:null)},TokenTape.prototype.findMatchingToken=function(kw,dir){if(1!==Math.abs(dir))throw new Error("Invalid Direction Given to findMatchingToken: "+dir.toString());var curType=this.lineToks[this.current].state.lineState.delimType;if(curType!==DELIMTYPES.OPENING&&curType!==DELIMTYPES.CLOSING)throw new Error("Invalid starting token: "+this.lineToks[this.current]);function stackEmpty(){return 0===stack.length}var isFunctionName="function-name"===kw.type,kwOrig=kw,forward=(kw=kw.string,1===dir),stack=[],subs={},lastFound=[],badSubs={},getNext=(forward?this.next:this.prev).bind(this),deeperType=forward?DELIMTYPES.OPENING:DELIMTYPES.CLOSING,shallowerType=forward?DELIMTYPES.CLOSING:DELIMTYPES.OPENING,toksMatch=forward?function(tok){return keyMatches(kw,tok,isFunctionName)}:function(tok){return keyMatches(tok,kwOrig)},failIfNoMatch=!forward;for(var dealWithAfterLast=function(tok,parent){this.getContinued();var toAdd={from:this.curRegion.start,to:this.curRegion.end};forward?(badSubs[parent]=badSubs[parent]||[],badSubs[parent].push(toAdd)):-1===(INV_LASTSUBKEYWORDS[tok.string]||[]).indexOf(parent)?(subs[parent]=subs[parent]||[],subs[parent].push(toAdd)):(subs[parent]&&(badSubs[parent]=badSubs[parent]||[],subs[parent].forEach(function(child){badSubs[parent].push(child)})),subs[parent]=[toAdd])}.bind(this);;){var next=getNext();if(!next)return new IterResult(null,failIfNoMatch,kw?subs[kw]:[]);if(stackEmpty()&&next.state.lineState.delimType===DELIMTYPES.SUBKEYWORD)if(forward){var matchingSubs=SUBKEYWORDS[kw],lastSubs=LASTSUBKEYWORDS[kw];if(matchingSubs&&-1!==matchingSubs.indexOf(next.string)){-1!==lastFound.indexOf(kw)?dealWithAfterLast(next,kw):(lastSubs&&lastSubs===next.string&&lastFound.push(kw),subs[kw]=subs[kw]||[],this.getContinued(),subs[kw].push({from:this.curRegion.start,to:this.curRegion.end}));continue}}else{matchingSubs=INV_SUBKEYWORDS[next.string];if(matchingSubs){matchingSubs.forEach(function(key){var nextReg;lastFound.indexOf(key)?dealWithAfterLast(next,key):(this.getContinued(),nextReg={from:this.curRegion.start,to:this.curRegion.end},LASTSUBKEYWORDS[key]===next.string&&lastFound.push(key),subs[key]=subs[key]||[],subs[key].push(nextReg))});continue}}if(next.state.lineState.delimType===shallowerType){if(stackEmpty())return new IterResult({token:next,from:this.curRegion.start,to:this.curRegion.end},lastSubs=!(!kw||toksMatch(next)),lastSubs?[]:forward?subs[kw]:subs[next.string],forward?badSubs[kw]:badSubs[next.string]);stack.pop()}else(t=>t.state.lineState.delimType===deeperType)(next)&&stack.push(next)}},TokenTape.prototype.findMatchingOpen=function(kw){return this.findMatchingToken(kw,-1)},TokenTape.prototype.findMatchingClose=function(kw){return this.findMatchingToken(kw,1)},TokenTape.prototype.findMatchingParent=function(kw){kw=kw.string;var stack=[],skip=0,parents=INV_SUBKEYWORDS[kw];if(!parents)throw new Error("Non-Subkeyword given to findMatchingParent");for(;;){var prev=this.prev();if(!prev)return new IterResult(null,!0);if(0<skip)skip--;else{var prevIsLast=-1!==Object.keys(INV_LASTSUBKEYWORDS).indexOf(prev.string);if(0===stack.length&&prevIsLast)return new IterResult(null,!0);prevIsLast=prev.state.lineState.delimType;if(prevIsLast===DELIMTYPES.CLOSING)stack.push(prev);else{if(parents.indexOf(-1!==prev.string)&&0===stack.length)return new IterResult(prev,!1,[]);prevIsLast===DELIMTYPES.OPENING&&stack.pop()}}}},CodeMirror.registerHelper("fold","pyret",function(cm,start){var dbg=CodeMirror.debugInternal;dbg&&(dbg.clear(),dbg.writeLn("Folding Debug Info:"));var close,kw,ttape=initializeTape(cm,Pos(start.line,0),!0).ttape,openKw=ttape.cur();for(;openKw&&openKw.line===start.line;){if((kw=openKw)&&kw.state.lineState.delimType===DELIMTYPES.OPENING&&("("!==openKw.string||"builtin"!==openKw.type))return ttape.getFoldingContinued(),kw=ttape.curRegion.end,(close=ttape.findMatchingClose(openKw))&&close.token&&{from:kw,to:close.token.from};openKw=ttape.next()}}),CodeMirror.findMatchingKeyword=function(cm,pos,range){var dbg=CodeMirror.debugInternal,pos=(dbg&&(dbg.clear(),dbg.writeLn("Keyword Matching Debug Info:")),initializeTape(cm,pos,!0,range));if(pos.didNotMatch)return dbg&&dbg.writeLn("<no match>"),null;dbg&&(dbg.writeLn("Initial tape:"),dbg.writeLn(pos.ttape.toString()));var other,dbg=pos.ttape,start=pos.start,startType=pos.startType,pos=pos.here;return startType===DELIMTYPES.CLOSING?{open:(other=dbg.findMatchingOpen(start)).token,close:pos,at:"close",matches:!other.fail,extra:other.subs,extraBad:other.badSubs}:-1!=Object.keys(INV_SUBKEYWORDS).indexOf(start.string)&&startType!==DELIMTYPES.OPENING?(startType=dbg.findMatchingParent(start)).fail?{open:startType.token,close:pos,at:"close",matches:!1,extra:[],extraBad:startType.badSubs}:CodeMirror.findMatchingKeyword(cm,Pos(startType.token.line,startType.token.start+1),range):{open:pos,close:(other=dbg.findMatchingClose(start)).token,at:"open",matches:!other.fail,extra:other.subs,extraBad:other.badSubs}}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../fold/pyret-fold")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../fold/pyret-fold"],mod):mod(CodeMirror)})(function(CodeMirror){function clear(cm){if(cm.state.keywordMarks)for(var i=0;i<cm.state.keywordMarks.length;i++)cm.state.keywordMarks[i].clear();cm.state.keywordMarks=[]}function doMatchKeywords(cm){cm.state.failedKeywordMatch=!1,cm.operation(function(){var cur,range,other,wordStyle,regionStyle;clear(cm),cm.somethingSelected()||(cur=cm.getCursor(),(range=cm.getViewport()).from=Math.min(range.from,cur.line),range.to=Math.max(cur.line+1,range.to),(cur=CodeMirror.findMatchingKeyword(cm,cur,range))&&(range="open"==cur.at?cur.open:cur.close,other="close"==cur.at?cur.open:cur.close,regionStyle=(wordStyle=cur.matches?other?"CodeMirror-matchingbracket":"CodeMirror-pyret-no-match-start":other?"CodeMirror-nonmatchingbracket":"CodeMirror-pyret-no-match-end")+"-region",cm.state.failedKeywordMatch=!cur.matches,cm.state.keywordMarks.push(cm.markText(range.from,range.to,{className:wordStyle+" "+("open"==cur.at?"open":"close")})),cur.extra.forEach(function(tok){cm.state.keywordMarks.push(cm.markText(tok.from,tok.to,{className:wordStyle}))}),cur.extraBad.forEach(function(tok){cm.state.keywordMarks.push(cm.markText(tok.from,tok.to,{className:"CodeMirror-nonmatchingbracket"}))}),other)&&(cm.state.keywordMarks.push(cm.markText(other.from,other.to,{className:wordStyle+" "+("close"==cur.at?"open":"close")})),cm.state.keywordMarks.push(cm.markText(cur.open.from,cur.close.to,{className:regionStyle}))))})}function maybeUpdateMatch(cm){cm.state.failedKeywordMatch&&doMatchKeywords(cm)}function nonBlankToken(tok){return null!==tok.type&&!/^\s*$/.test(tok.string)}function nextNonblankTokenAfter(cm,pos,allowAtCurrent){var line=pos.line,toks=cm.getLineTokens(line);if(allowAtCurrent)for(var i=0;i<toks.length;i++)if(toks[i].start==pos.ch&&nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(i=0;i<toks.length;i++)if(toks[i].start<=pos.ch&&toks[i].end>pos.ch)for(nonBlankToken(toks[i])&&i++;i<toks.length;i++)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(line+=1;line<=cm.lastLine();line++)for(toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i]}function prevNonblankTokenBefore(cm,pos){for(var line=pos.line,toks=cm.getLineTokens(line),i=toks.length-1;0<=i;i--)if(toks[i].start<pos.ch&&toks[i].end>=pos.ch)for(nonBlankToken(toks[i])&&i--;0<=i;i--)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(line-=1;line>=cm.firstLine();line--)for(i=(toks=cm.getLineTokens(line)).length-1;0<=i;i--)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i]}CodeMirror.defineOption("matchKeywords",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.off("cursorActivity",doMatchKeywords),cm.off("viewportChange",maybeUpdateMatch),clear(cm)),val&&(cm.state.matchBothKeywords="object"==typeof val&&val.bothKeywords,cm.on("cursorActivity",doMatchKeywords),cm.on("viewportChange",maybeUpdateMatch),doMatchKeywords(cm))}),CodeMirror.commands.toMatchingKeyword=function(cm){var found=CodeMirror.findMatchingKeyword(cm,cm.getCursor());found&&(found="close"==found.at?found.open:found.close)&&cm.extendSelection(found.to,found.from)},CodeMirror.commands.goBackwardSexp=function(cm){var cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),prev=(cursor.ch,prevNonblankTokenBefore(cm,cursor));!prev||cursor.ch!==cur.start&&nonBlankToken(cur)&&"COMMENT-END"!==prev.state.lastToken||(cursor={line:(cur=prev).line,ch:prev.start}),cur&&"comment"===cur.type&&"COMMENT-END"===cur.state.lastToken?((cm,pos,nestingDepth)=>{for(var line=pos.line,toks=cm.getLineTokens(line),i=toks.length-1;0<=i;i--)if(toks[i].start<pos.ch&&"COMMENT-START"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth)return pos={line:line,ch:toks[i].start},cm.extendSelection(pos,pos);for(line-=1;line>=cm.firstLine();line--)for(i=(toks=cm.getLineTokens(line)).length-1;0<=i;i--)if("COMMENT-START"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth)return pos={line:line,ch:toks[i].start},cm.extendSelection(pos,pos);pos={line:cm.firstLine(),ch:0},cm.extendSelection(pos,pos)})(cm,cursor,cur.state.commentNestingDepth+1):(prev=(prev=CodeMirror.findMatchingKeyword(cm,cursor))&&prev.open.from.line==cursor.line&&prev.open.from.ch==cursor.ch?null:prev)?cm.extendSelection(prev.open.from,prev.open.from):CodeMirror.commands.goBackwardToken(cm)},CodeMirror.commands.goForwardSexp=function(cm){var cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),next=nextNonblankTokenAfter(cm,cursor,!0);next&&(cursor.ch===cur.end||next.start===cursor.ch&&next.line===cur.line||!nonBlankToken(cur)||"COMMENT-START"===next.state.lastToken)&&(cursor={line:(cur=next).line,ch:next.start}),cur&&"comment"===cur.type&&"COMMENT-START"===cur.state.lastToken?((cm,pos,nestingDepth)=>{for(var line=pos.line,toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if(toks[i].start>pos.ch&&"COMMENT-END"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth-1)return pos={line:line,ch:toks[i].end},cm.extendSelection(pos,pos);for(line+=1;line<=cm.lastLine();line++)for(toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if("COMMENT-END"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth-1)return pos={line:line,ch:toks[i].end},cm.extendSelection(pos,pos);pos={line:cm.lastLine(),ch:null},cm.extendSelection(pos,pos)})(cm,cursor,cur.state.commentNestingDepth):((cur=CodeMirror.findMatchingKeyword(cm,cursor))&&cur.close.to.line==cursor.line&&cur.close.to.ch==cursor.ch&&next&&(next.ch=next.end,cur=CodeMirror.findMatchingKeyword(cm,next)),cur?cm.extendSelection(cur.close.to,cur.close.to):CodeMirror.commands.goForwardToken(cm))},CodeMirror.commands.goBackwardToken=function(cm){var pos,cursor=cm.getCursor(),cur=cm.getTokenAt(cursor);if(cur)if("comment"===cur.type)CodeMirror.commands.goWordLeft(cm);else{if(cur.type&&cur.start<cursor.ch)pos={line:cursor.line,ch:cur.start};else{cur=prevNonblankTokenBefore(cm,cursor);if(!cur)return;pos={line:cur.line,ch:cur.start}}cm.extendSelection(pos,pos)}},CodeMirror.commands.goForwardToken=function(cm){var pos,cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),next=nextNonblankTokenAfter(cm,cursor,!0);if(next&&(cursor.ch===cur.end||next.start===cursor.ch&&next.line===cur.line)&&(cursor={line:(cur=next).line,ch:next.start}),cur)if(nonBlankToken(cur)){if("comment"===cur.type){for(var index=cursor.ch-cur.start;index<cur.string.length;index++)if(" "!==cur.string[index]&&"\t"!==cur.string[index]&&(" "===cur.string[index+1]||"\t"==cur.string[index+1])){index++;break}return pos={line:cursor.line,ch:cur.start+index},void cm.extendSelection(pos,pos)}}else cur=nextNonblankTokenAfter(cm,cursor,!0);if(cur){if(cur.type&&cur.end>cursor.ch)pos={line:cursor.line,ch:cur.end};else{if(!(next=nextNonblankTokenAfter(cm,cursor)))return;pos={line:next.line,ch:next.end}}cm.extendSelection(pos,pos)}}}),((q,u,c)=>{function v(a,b,g){a.addEventListener?a.addEventListener(b,g,!1):a.attachEvent("on"+b,g)}function z(a){var b;return"keypress"==a.type?(b=String.fromCharCode(a.which),a.shiftKey?b:b.toLowerCase()):n[a.which]||r[a.which]||String.fromCharCode(a.which).toLowerCase()}function w(a){return"shift"==a||"ctrl"==a||"alt"==a||"meta"==a}function A(a,b){for(var d=[],e="+"===(e=a)?["+"]:(e=e.replace(/\+{2}/g,"+plus")).split("+"),g=0;g<e.length;++g){var m=e[g];B[m]&&(m=B[m]),b&&"keypress"!=b&&C[m]&&(m=C[m],d.push("shift")),w(m)&&d.push(m)}if(e=m,!(g=b)){if(!p)for(var c in p={},n)95<c&&c<112||n.hasOwnProperty(c)&&(p[n[c]]=c);g=p[e]?"keydown":"keypress"}return{key:m,modifiers:d,action:g="keypress"==g&&d.length?"keydown":g}}function d(a){function b(a){a=a||{};var l,b=!1;for(l in p)a[l]?b=!0:p[l]=0;b||(x=!1)}function g(a,b,t,f,g,d){var l,E=[],h=t.type;if(!k._callbacks[a])return[];for("keyup"==h&&w(a)&&(b=[a]),l=0;l<k._callbacks[a].length;++l){var e,c=k._callbacks[a][l];!f&&c.seq&&p[c.seq]!=c.level||h!=c.action||((e="keypress"==h&&!t.metaKey&&!t.ctrlKey)||(e=c.modifiers,e=b.sort().join(",")===e.sort().join(",")),e&&(e=f&&c.seq==f&&c.level==d,(!f&&c.combo==g||e)&&k._callbacks[a].splice(l,1),E.push(c)))}return E}function c(a,b,c,f){k.stopCallback(b,b.target||b.srcElement,c,f)||!1!==a(b,c)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!=typeof a.which&&(a.which=a.keyCode);var b=z(a);b&&("keyup"==a.type&&y===b?y=!1:k.handleKey(b,(a=>{var b=[];return a.shiftKey&&b.push("shift"),a.altKey&&b.push("alt"),a.ctrlKey&&b.push("ctrl"),a.metaKey&&b.push("meta"),b})(a),a))}function m(a,g,t,f){function l(g){c(t,g,a),"keyup"!==f&&(y=z(g)),setTimeout(b,10)}for(var d=p[a]=0;d<g.length;++d){var e=d+1===g.length?l:(c=>function(){x=c,++p[a],clearTimeout(q),q=setTimeout(b,1e3)})(f||A(g[d+1]).action);n(g[d],e,f,a,d)}}function n(a,b,c,f,d){k._directMap[a+":"+c]=b;var e=(a=a.replace(/\s+/g," ")).split(" ");1<e.length?m(a,e,b,c):(c=A(a,c),k._callbacks[c.key]=k._callbacks[c.key]||[],g(c.key,c.modifiers,{type:c.action},f,a,d),k._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:d,combo:a}))}var k=this;if(a=a||u,!(k instanceof d))return new d(a);k.target=a,k._callbacks={};var q,p={},y=!(k._directMap={}),r=!1,x=!1;k._handleKey=function(a,d,e){for(var f=g(a,d,e),k=0,l=!(d={}),h=0;h<f.length;++h)f[h].seq&&(k=Math.max(k,f[h].level));for(h=0;h<f.length;++h)f[h].seq?f[h].level==k&&(l=!0,d[f[h].seq]=1,c(f[h].callback,e,f[h].combo,f[h].seq)):l||c(f[h].callback,e,f[h].combo);f="keypress"==e.type&&r,e.type!=x||w(a)||f||b(d),r=l&&"keydown"==e.type},k._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)n(a[d],b,c)},v(a,"keypress",e),v(a,"keydown",e),v(a,"keyup",e)}if(q){var p,n={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},r={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},C={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},B={option:"alt",command:"meta",return:"enter",escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"};for(c=1;c<20;++c)n[111+c]="f"+c;for(c=0;c<=9;++c)n[c+96]=c.toString();d.prototype.bind=function(a,b,c){return a=a instanceof Array?a:[a],this._bindMultiple.call(this,a,b,c),this},d.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)},d.prototype.trigger=function(a,b){return this._directMap[a+":"+b]&&this._directMap[a+":"+b]({},a),this},d.prototype.reset=function(){return this._callbacks={},this._directMap={},this},d.prototype.stopCallback=function(a,b){var c;return!(-1<(" "+b.className+" ").indexOf(" mousetrap ")||function D(a,b){return null!==a&&a!==u&&(a===b||D(a.parentNode,b))}(b,this.target))&&("INPUT"==(b="composedPath"in a&&"function"==typeof a.composedPath&&(c=a.composedPath()[0])!==a.target?c:b).tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable)},d.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)},d.addKeycodes=function(a){for(var b in a)a.hasOwnProperty(b)&&(n[b]=a[b]);p=null},(d.init=function(){var b,a=d(u);for(b in a)"_"!==b.charAt(0)&&(d[b]=(b=>function(){return a[b].apply(a,arguments)})(b))})(),q.Mousetrap=d,"undefined"!=typeof module&&module.exports&&(module.exports=d),"function"==typeof define&&define.amd&&define(function(){return d})}})("undefined"!=typeof window?window:null,"undefined"!=typeof window?document:null),(a=>{var c={},d=a.prototype.stopCallback;a.prototype.stopCallback=function(e,b,a,f){return!!this.paused||!c[a]&&!c[f]&&d.call(this,e,b,a)},a.prototype.bindGlobal=function(a,b,d){if(this.bind(a,b,d),a instanceof Array)for(b=0;b<a.length;b++)c[a[b]]=!0;else c[a]=!0},a.init()})(Mousetrap),window.logger={},function(){this.log=function(){console.log.apply(console,arguments)}}),DummyBackend=function(){this.log=function(_,__){}},AJAXBackend=function(url){this.log=function(name,obj){var request=new XMLHttpRequest;request.open("POST",url,!0),request.send(JSON.stringify(obj))}},logger=(backend=>{var sessionStorage,localStorage;try{sessionStorage=window.localStorage,localStorage=window.sessionStorage}catch(e){sessionStorage={getItem:function(){},setItem:function(){}},localStorage={getItem:function(){},setItem:function(){}}}function guid(){for(var array=new Uint32Array(6),str=(window.crypto.getRandomValues(array),""),i=0;i<array.length;i++)str=str.concat(array[i].toString(36));return str}_identifiers={};var _identifiers,identifiers={get localID(){return _identifiers.lid||storedID(localStorage,"lid")},get sessionID(){return _identifiers.sid||storedID(sessionStorage,"sid")},get windowID(){return _identifiers.tid=_identifiers.tid||guid(),_identifiers.tid}};function storedID(storage,type){var id=storage.getItem(type);return null!==id&&""!==id||(id=_identifiers[type]||guid(),_identifiers[type]=id,storage.setItem(type,id)),id}function log(name,obj){(obj=obj instanceof Object?obj:{}).meta=[Date.now(),name,identifiers.windowID,identifiers.sessionID,identifiers.localID,GIT_REV,GIT_BRANCH],backend.log(name,obj)}var isDetailed="true"==localSettings.getItem("log-detailed");return{guid:guid,log:log,get isDetailed(){var nowIsDetailed="true"==localSettings.getItem("log-detailed");return isDetailed!=nowIsDetailed&&(log("LOG_DETAIL_CHANGED",{detailed:nowIsDetailed}),isDetailed=nowIsDetailed),nowIsDetailed}}})(LOG_URL?new AJAXBackend(LOG_URL):new DummyBackend),gwrap=(window.CodeMirror&&CodeMirror.defineOption("logging",!1,function(cm,new_value){1==new_value&&(cm.CPO_editorID||(cm.CPO_editorID=logger.guid()),logger.log("cm_init",{CPO_editorID:cm.CPO_editorID}),cm.on("change",function(cm,change){logger.isDetailed&&(change.CPO_editorID=cm.CPO_editorID,logger.log("cm_change",change))}),cm.on("focus",function(cm){logger.isDetailed&&logger.log("cm_focus",{CPO_editorID:cm.CPO_editorID})}),cm.on("blur",function(cm){logger.isDetailed&&logger.log("cm_blur",{CPO_editorID:cm.CPO_editorID})}))}),logger.log("load"),window.addEventListener("unload",function(event){logger.log("unload")}),document.addEventListener("visibilitychange",function(){logger.log("pagevis",{visibility:document.visibilityState})}),window.makeShareAPI=function(pyretVersion){var showingNeedingHidden=[];function makeShareUrl(id){id="/editor#share="+id;return""!==pyretVersion&&(id+="&v="+pyretVersion),window.location.origin+id}function getImportLetter(letter){letter=letter.toUpperCase();return!!/[A-Z]/.exec(letter)?letter:"M"}return $(".menuButton a").click(function(){showingNeedingHidden.forEach(function(hideIt){hideIt()})}),{makeShareLink:function(originalFile){var link=$('<button aria-label="Publish, F9" aria-describedby="mhelp-menus mhelp-activate mhelp-escape" class="focusable blueButton" role="menuitem" tabindex="-1">').text("Publish"),shareDiv=$("<div>").addClass("share");return link.click(function(){!function showShares(container,originalFile){function showNewSharePrompt(){var newShare=new modalPrompt({title:"Publish this file",style:"confirm",submitText:"Publish",narrow:!0,options:[{message:"This program has not been shared before. Publishing it by clicking below will make a new copy of the file that you can share with anyone you like. They will be able to see your code and run your program."}]});newShare.show().then(function(confirmed){!0===confirmed&&window.CPO.save().then(function(p){window.stickMessage("Copying...");p=p.makeShareCopy();p.fail(function(err){window.flashError("Couldn't copy the file for sharing.")}),p.then(function(f){return window.flashMessage("File published successfully"),showShares(container,originalFile)})})}).fail(function(err){console.error("Error showing the share dialog",err)})}function showExistingSharePrompt(instances){var f=instances[0],shareUrl=makeShareUrl(f.getUniqueId()),importLetter=getImportLetter(f.getName()[0]),f='import shared-gdrive("'+f.getName()+'", "'+f.getUniqueId()+'") as '+importLetter,importLetter=new modalPrompt({title:"Share or update the published copy",style:"copyText",submitText:"Update",options:[{message:"You can copy the link below to share the most recently published version with others.",text:shareUrl},{message:"You can copy the code below to use the published version as a library.",text:f},{message:"You can also click Update below to copy the current version to the published version, or click Cancel to exit this window."}]});importLetter.show(function(republish){republish&&window.CPO.save().then(function(p){window.stickMessage("Republishing file..."),p.getContents().then(function(contents){contents=instances[0].save(contents,!1);contents.fail(function(err){window.flashError("Couldn't publish the file.")}),contents.then(function(f){window.flashMessage("Published program updated.")})}).fail(function(){window.flashError("Couldn't get the file contents for publishing")})})})}var shares=originalFile.getShares();shares.then(function(sharedInstances){0===sharedInstances.length?showNewSharePrompt():showExistingSharePrompt(sharedInstances)})}(shareDiv,originalFile)}),link},makeShareUrl:makeShareUrl}},window.gwrap={load:function(params){var ret;if(params&¶ms.reauth&&void 0!==params.reauth.immediate)return ret=Q.defer(),loadAPIWrapper(params.reauth.immediate).then(function(gw){var copy=$.extend({},params);delete copy.reauth,gw.load(copy).then(function(loaded){loaded.auth=gw.auth,loaded.hasAuth=function(){return null!==gw.auth},ret.resolve(loaded)})}).fail(function(err){ret.reject(err)}),ret.promise;throw new Error("Google API Wrapper not yet initialized")},request:function(){throw new Error("Google API Wrapper not yet initialized")}});function reauth(immediate,useFullScopes){var d=Q.defer();return immediate?((immediate=$.ajax("/getAccessToken",{method:"get",datatype:"json"})).then(function(t){gapi.auth.setToken({access_token:t.access_token}),logger.log("login",{user_id:t.user_id}),d.resolve({user_id:t.user_id,access_token:t.access_token})}),immediate.fail(function(t){d.resolve(null)})):(immediate="/login?redirect="+encodeURIComponent("/close.html"),useFullScopes&&(immediate+="&scopes=full"),window.addEventListener("message",function(e){(e.domain||e.origin)===document.location.origin?d.resolve(reauth(!0,useFullScopes)):d.resolve(null)}),window.open(immediate)),d.promise}window.reauth=reauth;var _GWRAP_APIS={};function loadAPIWrapper(immediate){function assertDefined(v){if(void 0===window[v])throw new Error("Cannot initialize wrapper! Missing required definition: "+v)}function GoogleAPIError(message){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=message||""}assertDefined("gapi"),assertDefined("apiKey"),assertDefined("Q"),(GoogleAPIError.prototype=Object.create(Error.prototype)).name="GoogleAPIError";var GAPIError=GoogleAPIError.prototype.constructor=GoogleAPIError;function AuthenticationError(message){this.message=message||""}function APIResponseError(response){this.message=(response=response||{}).message||"",this.code=response.code||null,this.response=response}function authCheck(f){function isAuthFailure(result){return result&&(result.error&&result.error.code&&401===result.error.code||result.code&&401===result.code)}return f().then(function(result){return isAuthFailure(result)?function(){return 0<arguments.length&&console.warn("The `immediate` argument to `refresh()` is deprecated."),reauth(!0)}().then(function(authResult){return!authResult||authResult.error?{error:{code:401,message:"Couldn't re-authorize"}}:f()}):result}).then(function(result){if(isAuthFailure(result))throw new AuthenticationError("Authentication failure");return result})}function failCheck(p){return p.then(function(result){if(result&&"number"==typeof result.code&&400<=result.code)throw console.error("40X Error getting Google API response: ",result),new APIResponseError(result);if(result&&result.error)throw console.error("Error getting Google API response: ",result),new APIResponseError(result);return result})}function gQ(makeRequest,skipAuth){var oldAccess=gapi.auth.getToken(),ret=(skipAuth&&gapi.auth.setToken({access_token:null}),failCheck(authCheck(function(){var d=Q.defer();return makeRequest().execute(function(result){d.resolve(result)}),d.promise})));return skipAuth&&setTimeout(function(){gapi.auth.setToken(oldAccess)}),ret}(AuthenticationError.prototype=Object.create(GoogleAPIError.prototype)).name="AuthenticationError",AuthenticationError.prototype.constructor=AuthenticationError,(APIResponseError.prototype=Object.create(GoogleAPIError.prototype)).name="APIResponseError",APIResponseError.prototype.constructor=APIResponseError;var cachedAPIS=[];function loadAPI(params){if(!params)throw new GoogleAPIError("Missing API loading parameters");if(params.reauth){if(void 0===params.reauth.immediate)throw new GoogleAPIError("Missing required field to load(): params.reauth.immediate");var reloaded=Q.defer();return loadAPIWrapper(params.reauth.immediate).then(function(gw){var copy=$.extend({},params);delete copy.reauth,gw.load(copy).then(function(loaded){reloaded.resolve(loaded)})}),reloaded.promise}for(var i=0;i<cachedAPIS.length;++i){var cached=cachedAPIS[i];if(params.name&&cached.query.name===params.name)return cached.api;if(params.url&&cached.query.url===params.url)return cached.api}var preKeys=Object.keys(gapi.client);function processKey(key){var api;return key in _GWRAP_APIS||(api=gapi.client[key],_GWRAP_APIS[key]={},void 0!==api&&function processObject(obj,dest){Object.keys(obj).forEach(function(key){var original;"object"==typeof obj[key]?(dest[key]={},processObject(obj[key],dest[key])):"function"==typeof obj[key]?(original=obj[key],dest[key]=function(args,skipAuth){return gQ(function(){return original(args)},skipAuth)}):dest[key]=obj[key]})}(api,_GWRAP_APIS[key])),_GWRAP_APIS[key]}function processDelta(){var ret,newKeys=Object.keys(gapi.client).filter(function(k){return-1===preKeys.indexOf(k)});return 1<newKeys.length?ret=newKeys.map(processKey):params.name&&0===newKeys.length?gapi.client[params.name]&&(ret=processKey(params.name)):ret=processKey(newKeys[0]),ret?cachedAPIS.push({query:params,api:ret}):console.warn("loadAPI: Nothing to return!"),ret}var ret,name=params.name||params.url,version=params.version;return params.callback?(gapi.client.load(name,version,function(){params.callback(processDelta())}),null):(ret=Q.defer(),gapi.client.load(name,version,function(){ret.resolve(processDelta())}),ret.promise)}return reauth(immediate).then(function(auth){function makeWrapped(){this.GoogleAPIError=GoogleAPIError,this.GAPIError=GAPIError,this.AuthenticationError=AuthenticationError,this.APIResponseError=APIResponseError,this.load=loadAPI,this.withAuth=function(f){return failCheck(authCheck(f))},this.request=function(params,skipAuth){return gQ(function(){return gapi.client.request(params)},skipAuth)},this.auth=auth,this.hasAuth=function(){return null!==auth}}return makeWrapped.prototype=_GWRAP_APIS,gwrap=new makeWrapped})}function makeUrlFile(url){var p=Q.defer();return p.resolve({shared:!0,getOriginal:function(){throw new Error("Cannot getOriginal for a file created from a URL")},getContents:function(){let ans=Q.defer();return fetch(url).then(async function(contents){ans.resolve(await contents.text())}).catch(function(err){ans.reject(err)}),ans.promise},getName:function(){var lastSlash=String(url).lastIndexOf("/");return-1===lastSlash?url:url.slice(lastSlash+1)},getModifiedTime:function(){return new Date},getUniqueId:function(){return url}}),p.promise}function FilePicker(options){this.options=options=options||{},this.dataHandler=options.onSelect,this.onLoaded=options.onLoaded||function(){},this.onError=options.onError||function(m){throw console.error(m),new gwrap.GAPIError(m)},this.onInternalError=options.onInternalError||this.onError,this.raisedError=!1,storageAPI.then(function(){gapi.load("picker",{callback:function(){this.init(google.picker),this.onLoaded()}.bind(this)})}.bind(this))}function createSheetsAPI(immediate){function createAPI(spreadsheets){var _COLUMNS_ONE_INDEXED=!0;let SHEET_REQ_FIELDS=["properties(defaultFormat,title)","sheets("+["data("+"rowData(values(effectiveFormat/numberFormat,effectiveValue,formattedValue))"+",startColumn,startRow)","properties("+"gridProperties(columnCount,frozenColumnCount,frozenRowCount,rowCount)"+",index,sheetId,title)"].join(",")+")","spreadsheetId"].join(",");function SheetsError(message,extra){"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=message||"",this.extra=extra||{}}function colAsString(col){if(isNaN(col)){if("string"!=typeof col)throw new SheetsError("Invalid column: "+(col&&col.toString()));return col}for(var out="";0<col;){var modulo=(col-(_COLUMNS_ONE_INDEXED?1:0))%26,out=String.fromCharCode(65+modulo)+out;col=Math.floor((col-modulo)/26)}return out}function colAsNumber(col){if("string"==typeof col){for(var colNum=0,power=1,i=col.length-1;0<=i;--i)colNum+=(col.charCodeAt(i)-65+1)*power,power*=26;return colNum-(_COLUMNS_ONE_INDEXED?1:0)}if(isNaN(col))throw new SheetsError("Invalid column: "+(col&&col.toString()));return col}(SheetsError.prototype=Object.create(Error.prototype)).name="SheetsError",SheetsError.prototype.constructor=SheetsError;let VALUE_TYPES={STRING:1,NUMBER:2,BOOL:3,NONE:4};function unifyRows(rowData,skipHeaders,onlyInfer){var errors=[],rowSchemas=[],schema=[],startCol=1/0,endCol=0,startRow=0;function processValue(v,idx){if(!v)throw new SheetsError("Internal Error: unifyRows called with no value");if(!v.effectiveValue)return{value:null,type:VALUE_TYPES.NONE};if(startCol=Math.min(startCol,idx),endCol=Math.max(endCol,idx),void 0===v.effectiveValue.numberValue)return void 0!==v.effectiveValue.boolValue?{value:v.effectiveValue.boolValue,type:VALUE_TYPES.BOOL}:v.effectiveValue.errorValue?("N_A"===v.effectiveValue.errorValue.type?errors.push("Google Sheets Error: there are #N/A values in the sheet, so it cannot be loaded correctly. The #N/A values must first be fixed before importing."):errors.push("Google Sheets Error: "+v.effectiveValue.errorValue),{value:null,type:VALUE_TYPES.NONE}):{value:v.formattedValue,type:VALUE_TYPES.STRING};var idx=v.effectiveFormat&&v.effectiveFormat.numberFormat&&v.effectiveFormat.numberFormat.type,asStr=v.formattedValue||v.effectiveValue.numberValue.toString();switch(idx){case"TEXT":case"DATE":case"TIME":case"DATE_TIME":return{value:asStr,type:VALUE_TYPES.STRING};default:return{value:v.effectiveValue.numberValue,type:VALUE_TYPES.NUMBER}}}function typeName(t){switch(t){case VALUE_TYPES.STRING:return"String";case VALUE_TYPES.NUMBER:return"Number";case VALUE_TYPES.BOOL:return"Bool";default:VALUE_TYPES.NONE;return"Option"}}var foundFirstRow=!1,foundHeaders=!1,emptyRows=[];rowData=rowData.map(function(row,rowNum){if(row.values&&0<row.values.length&&row.values.some(function(v){return void 0!==v.effectiveValue})){if(!foundHeaders&&skipHeaders)return foundHeaders=!0,startRow+=1,rowSchemas.push([]),[];foundFirstRow=!0;var extracted=((row,rowNum)=>row.reduce(function(acc,cur,idx){return acc.values.push(cur.value),acc.schema.push({type:cur.type,isOption:cur.type===VALUE_TYPES.NONE,trueRow:rowNum,trueCol:idx}),acc},{values:[],schema:[]}))(row.values.map(processValue),rowNum);return row.values=extracted.values,rowSchemas.push(extracted.schema),row.values}return foundFirstRow?emptyRows.push(rowNum):startRow+=1,rowSchemas.push([]),[]});for(var i=emptyRows.length-1;0<=i;--i)rowData.splice(emptyRows[i],1),rowSchemas.splice(emptyRows[i],1);rowData.splice(0,startRow),rowSchemas.splice(0,startRow);for(var tableWidth=endCol-startCol+1,i=0;i<rowData.length;++i){rowData[i]=rowData[i].slice(startCol,endCol+1),rowSchemas[i]=rowSchemas[i].slice(startCol,endCol+1);for(var j=rowData[i].length;j<tableWidth;++j)rowData[i][j]=null,rowSchemas[i].push({type:VALUE_TYPES.NONE,isOption:!1})}for(i=0;i<rowSchemas.length;++i)for(j=0;j<Math.max(schema.length,rowSchemas[i].length);++j)schema[j]=((schema1,schema2,row,index)=>{function logFail(){var trueRow,data,trueCol;onlyInfer&&!onlyInfer.includes(schema2.trueCol)||(trueRow=schema2.trueRow,trueCol=schema2.trueCol,"string"==typeof(data=rowData[row][index])&&(data='"'+data+'"'),trueCol="All items in every column must have the same type. We expected to find a "+typeName(schema1.type)+" at cell "+colAsString(trueCol+1)+(trueRow+1)+", but we instead found this "+typeName(schema2.type)+": "+data+".",(schema1.type===VALUE_TYPES.STRING&&schema2.type===VALUE_TYPES.NUMBER||schema1.type===VALUE_TYPES.NUMBER&&schema2.type===VALUE_TYPES.STRING)&&(trueCol+=' If you want some Numbers to be read as Strings, you need to format those cells in Google Sheets as "Plain Text" (Select the cells, click "Format", then click "Number", and then click "Plain Text").'),errors.push(trueCol))}return schema1?schema1.type===VALUE_TYPES.NONE?schema2.type===VALUE_TYPES.NONE?schema1:(schema2.isOption=!0,schema2):(schema1.isOption?schema2.type!==VALUE_TYPES.NONE&&schema2.type!==schema1.type&&logFail():schema2.type===VALUE_TYPES.NONE?schema1.isOption=!0:schema1.type!==schema2.type&&logFail(),schema1):schema2})(schema[j],rowSchemas[i][j],i,j);var ret={values:rowData,schema:schema,startCol:startCol};return 0<errors.length&&(ret.errors=errors),ret}function Spreadsheet(data){this.id=data.spreadsheetId,this.title=data.properties.title,this.defaultFormat=data.properties.defaultFormat||{},data.sheets=data.sheets||[],this.worksheetsInfo=[],this.worksheets=data.sheets.map(function(wsdata){return new Worksheet(this,wsdata)},this)}function Worksheet(spreadsheet,data){if(!data)throw new SheetsError("Worksheet: Internal Error: No data. Please report this error to the developers.");if(!data.properties)throw new SheetsError("Worksheet: Internal Error: No properties. Please report this error to the developers.");this.id=data.properties.sheetId,this.title=data.properties.title,this.rows=data.properties.gridProperties.rowCount,this.cols=data.properties.gridProperties.columnCount,this.index=data.properties.index,spreadsheet.worksheetsInfo[this.index]={properties:data.properties},this.cache=[],this.spreadsheet=spreadsheet,this.rawData=data,this.listener={handleEvent:function(){return this.flushCache(!0)}.bind(this)},void 0===window?(console.warn("No window detected. Sheets may fall out of sync."),this.useTimer=!1):(window.addEventListener("pyret-save",this.flushCache.bind(this),!1),this.useTimer=!0)}return Spreadsheet.prototype.lookupInfoByName=function(name){for(var worksheetIdx=-1,i=0;i<this.worksheetsInfo.length;++i)if(this.worksheetsInfo[i].properties.title===name){worksheetIdx=i;break}if(-1===worksheetIdx)throw new SheetsError('No worksheet with name "'+name+'"');return this.worksheetsInfo[worksheetIdx]},Spreadsheet.prototype.lookupInfoByIndex=function(worksheetIdx){if(worksheetIdx>=this.worksheetsInfo.length)throw new SheetsError("No worksheet with index "+worksheetIdx);return this.worksheetsInfo[worksheetIdx]},Spreadsheet.prototype.getByIndex=function(worksheetIdx,skipHeaders,onlyInfer){this.lookupInfoByIndex(worksheetIdx);worksheetIdx=this.worksheets[worksheetIdx];return worksheetIdx.init(skipHeaders,onlyInfer),worksheetIdx},Spreadsheet.prototype.getByName=function(name,skipHeaders,onlyInfer){name=this.lookupInfoByName(name),name=this.worksheets[name.properties.index];return name.init(skipHeaders,onlyInfer),name},Spreadsheet.prototype.addWorksheet=function(name,index){var request={addSheet:{properties:{title:name}}};return void 0!==index&&(request.addSheet.properties.index=index),spreadsheets.batchUpdate({spreadsheetId:this.id,resource:{requests:[request]}}).then(function(data){return spreadsheets.get({spreadsheetId:this.id,ranges:name,fields:SHEET_REQ_FIELDS})}.bind(this)).then(function(data){if(data.sheets&&0!==data.sheets.length)return(data=new Worksheet(this,data.sheets[0])).init(!1),data;throw new SheetsError('Failed to add worksheet: "'+name+'"')}.bind(this)).fail(function(err){throw err.message&&/already exists/.test(err.message)?new SheetsError('A sheet with name "'+name+'" already exists in this spreadsheet.'):err})},Spreadsheet.prototype.deleteSheetById=function(id){return spreadsheets.batchUpdate({spreadsheetId:this.id,resource:{requests:[{deleteSheet:{sheetId:id}}]}}).then(function(_){return!0}).fail(function(err){throw err.message&&/sheet with ID.*does not exist/.test(err.message)?new SheetsError('A sheet with ID "'+id+'" does not exist in this spreadsheet.'):err})},Spreadsheet.prototype.deleteSheetByName=function(name){return this.deleteSheetById(this.lookupInfoByName(name).properties.sheetId).fail(function(err){throw err.message&&/does not exist in this spreadsheet/.test(err.message)?new SheetsError(err.message.replace(/ID "[^"]*"/,'name "'+name+'"')):err})},Spreadsheet.prototype.deleteSheetByIndex=function(idx){return this.deleteSheetById(this.lookupInfoByIndex(idx).properties.sheetId)},Worksheet.prototype.init=function(skipHeaders,onlyInfer){if(void 0!==this.hasHeaders&&this.hasHeaders!==!skipHeaders)throw new SheetsError("Attempted to load worksheet with"+(skipHeaders?"out":"")+" headers, but worksheet was already previously loaded with"+(skipHeaders?"":"out")+" headers.");if(void 0===this.data){var data=this.rawData;if(this.hasHeaders=!skipHeaders,data.data&&data.data[0]&&data.data[0].rowData){data=unifyRows(data.data[0].rowData,skipHeaders,onlyInfer);if(this.startCol=data.startCol,this.data=data.values,this.schema=data.schema,this.typeErrors=data.errors,!this.data)throw new SheetsError("Worksheet: Internal Error: Type-check yielded no values. Please report this error to the developers.");if(!this.schema)throw new SheetsError("Worksheet: Internal Error: Type-check yielded no schema. Please report this error to the developers.")}else this.data=[],this.startCol=0,this.schema=[]}},Worksheet.prototype.clearTimer=function(){this.useTimer&&void 0!==this.timeoutId&&(window.removeEventListener("beforeunload",this.listener),window.clearTimeout(this.timeoutId),this.timeoutId=void 0)},Worksheet.prototype.resetTimer=function(){this.useTimer&&(this.clearTimer(),window.addEventListener("beforeunload",this.listener),this.timeoutId=window.setTimeout(this.flushCache.bind(this),1e4))},Worksheet.prototype.getCellAt=function(col,row){return this.getCellRange(col,row,col,row).then(function(arr){return arr[0][0]})},Worksheet.prototype.setCellAt=function(col,row,val){return this.setCellRange(col,row,col,row,[[val]])},Worksheet.prototype.setCellRange=function(fromCol,fromRow,toCol,toRow,values){fromCol=((title,fromCol,fromRow,toCol,toRow)=>(toCol=fromCol===toCol?fromCol=colAsString(fromCol):(fromCol=colAsString(fromCol),colAsString(toCol)),title+"!"+fromCol+fromRow+":"+toCol+toRow))(this.title,fromCol,fromRow,toCol,toRow);return this.cache.push({range:fromCol,majorDimension:"ROWS",values:values}),this.resetTimer(),!0},Worksheet.prototype.flushCache=function(noRefresh){var promise;return this.clearTimer(),0===this.cache.length?Q(this):(promise=spreadsheets.values.batchUpdate({spreadsheetId:this.spreadsheet.id,resource:{data:this.cache}}),this.cache=[],promise.then((noRefresh?function(){return this}:this.refresh).bind(this)))},Worksheet.prototype.getAllCells=function(){return this.flushCache().then(function(){return this.data}.bind(this))},Worksheet.prototype.getCellRange=function(fromCol,fromRow,toCol,toRow){return fromCol=colAsNumber(fromCol),toCol=colAsNumber(toCol),this.flushCache().then(function(){return this.data.map(function(row){return row.slice(fromCol-this.startCol,toCol-this.startCol+1)}.bind(this)).slice(fromRow-1,toRow)}.bind(this))},Worksheet.prototype.updateName=function(name){var ret=spreadsheets.batchUpdate({spreadsheetId:this.spreadsheet.id,resource:{requests:[{updateSheetProperties:{properties:{title:name},fields:"title"}}]}});return ret.then(function(_){this.title=name}.bind(this)),ret},Worksheet.prototype.refresh=function(){return spreadsheets.get({spreadsheetId:this.spreadsheet.id,ranges:this.title,fields:SHEET_REQ_FIELDS}).then(function(data){if(data.sheets&&data.sheets[0]&&data.sheets[0].data&&data.sheets[0].data[0]&&data.sheets[0].data[0].rowData)return this.rawData=data.sheets[this.index],this.init(),this;throw new SheetsError("Worksheet data not returned by Google. Please report this error to the developers.")}.bind(this))},Spreadsheet.fromId=function(id){return spreadsheets.get({spreadsheetId:id,fields:SHEET_REQ_FIELDS},!0).then(function(data){return new Spreadsheet(data)},function(err){throw new SheetsError('No Spreadsheet with id "'+id+'" found')})},Spreadsheet.fromFile=function(file){return Spreadsheet.fromId(file.getUniqueId())},{createSpreadsheet:function(name){var opts={mimeType:"application/vnd.google-apps.spreadsheet",fileExtension:!1},ret=Q.defer();return storageAPI.then(function(api){return api.createFile(name,opts)}).then(function(file){return spreadsheets.get({spreadsheetId:file.getUniqueId()})}).then(function(data){ret.resolve(new Spreadsheet(data))}).fail(ret.reject),ret.promise},loadSpreadsheetByName:function(name){return storageAPI.then(function(api){return api.getFileByName(name)}).then(function(res){if(0===res.length)throw new SheetsError('No spreadsheet named "'+name+'" found.');return res[0]}).then(Spreadsheet.fromFile)},loadSpreadsheetById:function(id){return Spreadsheet.fromId(id)},TYPES:VALUE_TYPES}}var ret=Q.defer();return gwrap.load({url:"https://sheets.googleapis.com/$discovery/rest?version=v4",reauth:{immediate:immediate},callback:function(sheets){if(Array.isArray(sheets)){for(var i=0;i<sheets.length;i+=1)if(sheets[i].spreadsheets)return void ret.resolve(createAPI(sheets[i].spreadsheets));ret.reject("Sheets could not load")}else ret.resolve(createAPI(sheets.spreadsheets))}}),ret.promise}window.createProgramCollectionAPI=function(collectionName,immediate,publicOnly){Error.prototype;var drive,FOLDER_MIME="application/vnd.google-apps.folder",BACKREF_KEY="originalProgram";function createAPI(baseCollection){function makeSharedFile(googFileObject,fetchFromGoogle){return{shared:!0,getOriginal:function(){return gapi.client.drive.properties.get({fileId:googFileObject.id,propertyKey:BACKREF_KEY,visibility:"PRIVATE"})},getContents:function(){var reqUrl;return fetchFromGoogle?(reqUrl=googFileObject.selfLink,Q($.get(reqUrl,{alt:"media",key:apiKey}))):Q($.ajax("/shared-program-contents?sharedProgramId="+googFileObject.id,{method:"get",dataType:"text"}))},getName:function(){return googFileObject.title},getModifiedTime:function(){return googFileObject.modifiedDate},getUniqueId:function(){return googFileObject.id}}}function makeFile(googFileObject,mimeType,fileExtension){return{shared:!1,getName:function(){return googFileObject.title},getModifiedTime:function(){return googFileObject.modifiedDate},getUniqueId:function(){return googFileObject.id},getExternalURL:function(){return googFileObject.alternateLink},getShares:function(){return drive.files.list({q:"trashed=false and properties has {key='"+BACKREF_KEY+"' and value='"+googFileObject.id+"' and visibility='PRIVATE'}"}).then(function(files){return files.items?files.items.map(fileBuilder):[]})},getContents:function(){var baseUrl="https://www.googleapis.com/drive/v3/files/"+googFileObject.id+"?alt=media&source=download";return Q($.ajax(baseUrl,{method:"get",dataType:"text",headers:{Authorization:"Bearer "+gapi.auth.getToken().access_token}})).then(function(response){return response})},rename:function(newName){return drive.files.update({fileId:googFileObject.id,resource:{title:newName}}).then(fileBuilder)},makeShareCopy:function(){return shareCollection.then(function(c){return Q($.ajax({url:"/create-shared-program",method:"post",data:{fileId:googFileObject.id,title:googFileObject.title,collectionId:c.id}}))}).then(fileBuilder)},save:function(contents,newRevision){var boundary="-------314159265358979323846",delimiter="\r\n--"+boundary+"\r\n",delimiter=delimiter+"Content-Type: application/json\r\n\r\n"+JSON.stringify({mimeType:mimeType,fileExtension:fileExtension})+delimiter+"Content-Type: text/plain\r\n\r\n"+contents+"\r\n---------314159265358979323846--";return gwrap.request({path:"/upload/drive/v2/files/"+googFileObject.id,method:"PUT",params:{uploadType:"multipart"},headers:{"Content-Type":'multipart/mixed; boundary="'+boundary+'"'},body:delimiter}).then(fileBuilder)},_googObj:googFileObject}}function fileBuilder(googFileObject){return"text/plain"===googFileObject.mimeType&&!googFileObject.fileExtension||"arr"===googFileObject.fileExtension?makeFile(googFileObject,"text/plain","arr"):makeFile(googFileObject,googFileObject.mimeType,googFileObject.fileExtension)}var shareCollectionQ,cacheCollectionQ,shareCollection,api={getCollectionLink:function(){return baseCollection.then(function(bc){return"https://drive.google.com/drive/u/0/folders/"+bc.id})},getCollectionFolderId:function(){return baseCollection.then(function(bc){return bc.id})},getFileById:function(id){return drive.files.get({fileId:id}).then(fileBuilder)},makeUrlFile:function(url){return makeUrlFile(url)},getFileByName:function(name){return this.getAllFiles().then(function(files){return files.filter(function(f){return f.getName()===name})})},getCachedFileByName:function(name){return this.getCachedFiles().then(function(files){return files.filter(function(f){return f.getName()===name})})},getSharedFileById:function(id){var fromServer=(fromDriveQ=publicOnly?((fromDriveQ=Q.defer()).reject("No shared files directly from client with publicOnly=true"),fromDriveQ.promise):drive.files.get({fileId:id},!0).then(function(googFileObject){return makeSharedFile(googFileObject,!0)})).fail(function(){return Q($.get("/shared-file",{sharedProgramId:id})).then(function(googlishFileObject){return makeSharedFile(googlishFileObject,!1)})}),fromDriveQ=Q.any([fromDriveQ,fromServer]);return fromDriveQ.then(function(r){console.log("Got result for shared file: ",r)},function(r){console.log("Got failure: ",r)}),fromDriveQ},getFiles:function(c){return c.then(function(bc){return drive.files.list({q:"trashed=false and '"+bc.id+"' in parents"}).then(function(filesResult){return filesResult.items?filesResult.items.map(fileBuilder):[]})})},getCachedFiles:function(){return this.getFiles(cacheCollection)},getAllFiles:function(){return this.getFiles(baseCollection)},createFile:function(name,opts){var mimeType=(opts=opts||{}).mimeType||"text/plain",fileExtension=opts.fileExtension||"arr";return(opts.saveInCache?cacheCollection:baseCollection).then(function(bc){bc={path:"/drive/v2/files",method:"POST",params:opts.params||{},body:{parents:[{id:bc.id}],mimeType:mimeType,title:name}};return!1!==opts.fileExtension&&(bc.body.fileExtension=fileExtension),gwrap.request(bc).then(fileBuilder)})},checkLogin:function(){return collection.then(function(){return!0})}},cacheCollection=publicOnly?(shareCollectionQ=Q.defer(),cacheCollectionQ=Q.defer(),shareCollectionQ.reject("No share collection with publicOnly=true"),cacheCollectionQ.reject("No cache collection with publicOnly=true"),shareCollection=shareCollectionQ.promise,cacheCollectionQ.promise):(shareCollection=findOrCreateDirectory(collectionName+".shared"),findOrCreateDirectory(collectionName+".compiled"));return{api:api,collection:baseCollection,cacheCollection:cacheCollection,shareCollection:shareCollection,reinitialize:function(){return Q.fcall(function(){return initialize(drive)})}}}function findOrCreateDirectory(name){return drive.files.list({q:"('me' in owners) and trashed=false and title='"+name+"' and mimeType='"+FOLDER_MIME+"'"}).then(function(files){return files.items&&0<files.items.length?files.items[0]:drive.files.insert({resource:{mimeType:FOLDER_MIME,title:name}})})}function initialize(wrappedDrive){return drive=wrappedDrive,createAPI(publicOnly?((wrappedDrive=Q.defer()).reject("No base collection with publicOnly=true"),wrappedDrive.promise):findOrCreateDirectory(collectionName))}var ret=Q.defer();return gwrap.load({name:"drive",version:"v2",reauth:{immediate:immediate,publicOnly:publicOnly},callback:function(drive){ret.resolve(initialize(drive))}}),ret.promise},FilePicker.prototype.init=function(picker){this.open=this.initOpen(picker)},FilePicker.prototype.initOpen=function(picker){var validateSelection=function(sel){if(0===sel.length)this.onInternalError("Internal Error (please report to developers): Should be impossible: Picker selection length is zero");else{var firstType=sel[0][picker.Document.TYPE];switch(sel.forEach(function(f){f[picker.Document.TYPE]!==firstType&&this.onError("Cannot open files of multiple types (Expected: "+firstType+"; Received: "+f[picker.Document.TYPE]+")")}.bind(this)),sel[0][picker.Document.TYPE]){case"file":break;case picker.Type.PHOTO:sel.forEach(function(photo){photo=photo[picker.Document.ID];Q($.ajax({url:"/share-image",method:"post",data:{fileId:photo}})).fail(this.onInternalError)}.bind(this));break;default:this.onError("Cannot open file of unknown type: "+sel[0][picker.Document.TYPE])}}}.bind(this),pickerCallback=function(data){var selection;data[picker.Response.ACTION]==picker.Action.PICKED&&(selection=data[picker.Response.DOCUMENTS],validateSelection(selection),storageAPI.then(function(drive){this.dataHandler(selection,picker,drive)}.bind(this)))}.bind(this),showPicker=function(drive,views,title){var pyretView=new picker.DocsView(picker.ViewId.DOCUMENTS),imageView=new picker.View(picker.ViewId.DOCS),allViews=(imageView.setMimeTypes("image/png,image/jpeg,image/jpg,image/gif"),{imageView:imageView,pyretView:pyretView}),imageView=function(parentId){pyretView.setParent(parentId);for(var pickerBuilder=(new picker.PickerBuilder).enableFeature(picker.Feature.MULTISELECT_ENABLED).setTitle(title),i=0;i<views.length;i+=1)pickerBuilder.addView(allViews[views[i]]);this.pickerInstance=pickerBuilder.setOAuthToken(gapi.auth.getToken().access_token).setDeveloperKey(apiKey).setAppId(appId).setCallback(pickerCallback).build(),this.pickerInstance.setVisible(!0),$(".picker").css("z-index",9e3);var hidePicker=function(e){27===e.which&&($(".picker").remove(),$(document).unbind("keydown",hidePicker))};$(document).on("keydown",hidePicker)}.bind(this);return drive.getCollectionFolderId().then(imageView)}.bind(this);return function(){this.raisedError=!1;var views=this.options.views||[],title=this.options.title||"Select a file";return storageAPI.then(function(drive){return gwrap.withAuth(function(){return showPicker(drive,views,title)})}).catch(function(err){if(this.raisedError)throw err;err&&err.message?this.onInternalError(err.message):this.onInternalError(err)}.bind(this))}.bind(this)},FilePicker.prototype.openOn=function(elt,evt){elt.addEventListener(evt,this.open.bind(this))};var storageAPIDeferred=Q.defer(),sheetsAPIDeferred=Q.defer();window.storageAPI=storageAPIDeferred.promise,window.sheetsAPI=sheetsAPIDeferred.promise,window.handleClientLoad=function(apiKey,publicOnly){window.gapi&&window.gapi.client?(gapi.client.setApiKey(apiKey),(apiKey=createProgramCollectionAPI("code.pyret.org",!0,publicOnly)).then(function(api){storageAPIDeferred.resolve(api);api=createSheetsAPI(!0);api.then(function(sheetsAPI){sheetsAPIDeferred.resolve(sheetsAPI)}),api.fail(function(err){sheetsAPIDeferred.reject(err)})}),apiKey.fail(function(err){storageAPIDeferred.reject(err),sheetsAPIDeferred.reject(err),console.log("Not logged in; proceeding without login info",err)})):(storageAPIDeferred.reject("no gapi.client"),sheetsAPIDeferred.reject("no gapi.client"),console.log("Not logged in; proceeding without login info"))};
|
|
1
|
+
(definition=>{if("function"==typeof bootstrap)bootstrap("promise",definition);else if("object"==typeof exports&&"object"==typeof module)module.exports=definition();else if("function"==typeof define&&define.amd)define(definition);else if("undefined"!=typeof ses)ses.ok()&&(ses.makeQ=definition);else{if("undefined"==typeof window&&"undefined"==typeof self)throw new Error("This environment was not anticipated by Q. Please file a bug.");var global="undefined"!=typeof window?window:self,previousQ=global.Q;global.Q=definition(),global.Q.noConflict=function(){return global.Q=previousQ,this}}})(function(){var hasStacks=!1;try{throw new Error}catch(e){hasStacks=!!e.stack}function noop(){}var qFileName,nextTick,channel,requestPortTick,head,tail,flushing,requestTick,isNodeJS,laterQueue,qStartingLine=captureLine();tail=head={task:void 0,next:null},requestTick=void 0,isNodeJS=flushing=!1,laterQueue=[],nextTick=function(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null},flushing||(flushing=!0,requestTick())},requestTick="object"==typeof process&&"[object process]"===process.toString()&&process.nextTick?(isNodeJS=!0,function(){process.nextTick(flush)}):"function"==typeof setImmediate?"undefined"!=typeof window?setImmediate.bind(window,flush):function(){setImmediate(flush)}:"undefined"!=typeof MessageChannel?((channel=new MessageChannel).port1.onmessage=function(){requestTick=requestPortTick,(channel.port1.onmessage=flush)()},requestPortTick=function(){channel.port2.postMessage(0)},function(){setTimeout(flush,0),requestPortTick()}):function(){setTimeout(flush,0)},nextTick.runAfter=function(task){laterQueue.push(task),flushing||(flushing=!0,requestTick())};function flush(){for(var task,domain;head.next;)task=(head=head.next).task,head.task=void 0,(domain=head.domain)&&(head.domain=void 0,domain.enter()),runSingle(task,domain);for(;laterQueue.length;)runSingle(task=laterQueue.pop());flushing=!1}function runSingle(task,domain){try{task()}catch(e){if(isNodeJS)throw domain&&domain.exit(),setTimeout(flush,0),domain&&domain.enter(),e;setTimeout(function(){throw e},0)}domain&&domain.exit()}var call=Function.call;function uncurryThis(f){return function(){return call.apply(f,arguments)}}var array_slice=uncurryThis(Array.prototype.slice),array_reduce=uncurryThis(Array.prototype.reduce||function(callback,basis){var index=0,length=this.length;if(1===arguments.length)for(;;){if(index in this){basis=this[index++];break}if(++index>=length)throw new TypeError}for(;index<length;index++)index in this&&(basis=callback(basis,this[index],index));return basis}),array_indexOf=uncurryThis(Array.prototype.indexOf||function(value){for(var i=0;i<this.length;i++)if(this[i]===value)return i;return-1}),array_map=uncurryThis(Array.prototype.map||function(callback,thisp){var self=this,collect=[];return array_reduce(self,function(undefined,value,index){collect.push(callback.call(thisp,value,index,self))},void 0),collect}),object_create=Object.create||function(prototype){function Type(){}return Type.prototype=prototype,new Type},object_hasOwnProperty=uncurryThis(Object.prototype.hasOwnProperty),object_keys=Object.keys||function(object){var key,keys=[];for(key in object)object_hasOwnProperty(object,key)&&keys.push(key);return keys},object_toString=uncurryThis(Object.prototype.toString);var QReturnValue="undefined"!=typeof ReturnValue?ReturnValue:function(value){this.value=value},STACK_JUMP_SEPARATOR="From previous event:";function makeStackTraceLong(error,promise){if(hasStacks&&promise.stack&&"object"==typeof error&&null!==error&&error.stack&&-1===error.stack.indexOf(STACK_JUMP_SEPARATOR)){for(var stacks=[],p=promise;p;p=p.source)p.stack&&stacks.unshift(p.stack);stacks.unshift(error.stack);promise=stacks.join("\n"+STACK_JUMP_SEPARATOR+"\n");error.stack=(stackString=>{for(var lines=stackString.split("\n"),desiredLines=[],i=0;i<lines.length;++i){var line=lines[i];(stackLine=>{var fileName;return(stackLine=getFileNameAndLineNumber(stackLine))&&(fileName=stackLine[0],stackLine=stackLine[1],fileName===qFileName)&&qStartingLine<=stackLine&&stackLine<=qEndingLine})(line)||(stackLine=>-1!==stackLine.indexOf("(module.js:")||-1!==stackLine.indexOf("(node.js:"))(line)||!line||desiredLines.push(line)}return desiredLines.join("\n")})(promise)}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);return(attempt1=attempt1||/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine))?[attempt1[1],Number(attempt1[2])]:(attempt1=/.*@(.+):(\d+)$/.exec(stackLine))?[attempt1[1],Number(attempt1[2])]:void 0}function captureLine(){if(hasStacks)try{throw new Error}catch(e){var lines=e.stack.split("\n"),lines=getFileNameAndLineNumber(0<lines[0].indexOf("@")?lines[1]:lines[2]);if(lines)return qFileName=lines[0],lines[1]}}function Q(value){return value instanceof Promise?value:isPromiseAlike(value)?(promise=value,deferred=defer(),Q.nextTick(function(){try{promise.then(deferred.resolve,deferred.reject,deferred.notify)}catch(exception){deferred.reject(exception)}}),deferred.promise):fulfill(value);var promise,deferred}function defer(){var resolvedPromise,messages=[],progressListeners=[],deferred=object_create(defer.prototype),promise=object_create(Promise.prototype);if(promise.promiseDispatch=function(resolve,op,operands){var args=array_slice(arguments);messages?(messages.push(args),"when"===op&&operands[1]&&progressListeners.push(operands[1])):Q.nextTick(function(){resolvedPromise.promiseDispatch.apply(resolvedPromise,args)})},promise.valueOf=function(){var nearerValue;return messages?promise:(isPromise(nearerValue=nearer(resolvedPromise))&&(resolvedPromise=nearerValue),nearerValue)},promise.inspect=function(){return resolvedPromise?resolvedPromise.inspect():{state:"pending"}},Q.longStackSupport&&hasStacks)try{throw new Error}catch(e){promise.stack=e.stack.substring(e.stack.indexOf("\n")+1)}function become(newPromise){resolvedPromise=newPromise,promise.source=newPromise,array_reduce(messages,function(undefined,message){Q.nextTick(function(){newPromise.promiseDispatch.apply(newPromise,message)})},void 0),progressListeners=messages=void 0}return deferred.promise=promise,deferred.resolve=function(value){resolvedPromise||become(Q(value))},deferred.fulfill=function(value){resolvedPromise||become(fulfill(value))},deferred.reject=function(reason){resolvedPromise||become(reject(reason))},deferred.notify=function(progress){resolvedPromise||array_reduce(progressListeners,function(undefined,progressListener){Q.nextTick(function(){progressListener(progress)})},void 0)},deferred}function promise(resolver){if("function"!=typeof resolver)throw new TypeError("resolver must be a function.");var deferred=defer();try{resolver(deferred.resolve,deferred.reject,deferred.notify)}catch(reason){deferred.reject(reason)}return deferred.promise}function race(answerPs){return promise(function(resolve,reject){for(var i=0,len=answerPs.length;i<len;i++)Q(answerPs[i]).then(resolve,reject)})}function Promise(descriptor,fallback,inspect){void 0===fallback&&(fallback=function(op){return reject(new Error("Promise does not support operation: "+op))}),void 0===inspect&&(inspect=function(){return{state:"unknown"}});var inspected,promise=object_create(Promise.prototype);return promise.promiseDispatch=function(resolve,op,args){var result;try{result=descriptor[op]?descriptor[op].apply(promise,args):fallback.call(promise,op,args)}catch(exception){result=reject(exception)}resolve&&resolve(result)},(promise.inspect=inspect)&&("rejected"===(inspected=inspect()).state&&(promise.exception=inspected.reason),promise.valueOf=function(){var inspected=inspect();return"pending"===inspected.state||"rejected"===inspected.state?promise:inspected.value}),promise}function when(value,fulfilled,rejected,progressed){return Q(value).then(fulfilled,rejected,progressed)}function nearer(value){if(isPromise(value)){var inspected=value.inspect();if("fulfilled"===inspected.state)return inspected.value}return value}function isPromise(object){return object instanceof Promise}function isPromiseAlike(object){return object===Object(object)&&"function"==typeof object.then}(Q.resolve=Q).nextTick=nextTick,Q.longStackSupport=!1,"object"==typeof process&&process&&process.env&&process.env.Q_DEBUG&&(Q.longStackSupport=!0),(Q.defer=defer).prototype.makeNodeResolver=function(){var self=this;return function(error,value){error?self.reject(error):2<arguments.length?self.resolve(array_slice(arguments,1)):self.resolve(value)}},Q.Promise=promise,(Q.promise=promise).race=race,promise.all=all,promise.reject=reject,(promise.resolve=Q).passByCopy=function(object){return object},Promise.prototype.passByCopy=function(){return this},Q.join=function(x,y){return Q(x).join(y)},Promise.prototype.join=function(that){return Q([this,that]).spread(function(x,y){if(x===y)return x;throw new Error("Can't join: not the same: "+x+" "+y)})},Q.race=race,Promise.prototype.race=function(){return this.then(Q.race)},(Q.makePromise=Promise).prototype.toString=function(){return"[object Promise]"},Promise.prototype.then=function(fulfilled,rejected,progressed){var self=this,deferred=defer(),done=!1;return Q.nextTick(function(){self.promiseDispatch(function(value){done||(done=!0,deferred.resolve((value=>{try{return"function"==typeof fulfilled?fulfilled(value):value}catch(exception){return reject(exception)}})(value)))},"when",[function(exception){done||(done=!0,deferred.resolve((exception=>{if("function"==typeof rejected){makeStackTraceLong(exception,self);try{return rejected(exception)}catch(newException){return reject(newException)}}return reject(exception)})(exception)))}])}),self.promiseDispatch(void 0,"when",[void 0,function(value){var newValue,threw=!1;try{newValue=(value=>"function"==typeof progressed?progressed(value):value)(value)}catch(e){if(threw=!0,!Q.onerror)throw e;Q.onerror(e)}threw||deferred.notify(newValue)}]),deferred.promise},Q.tap=function(promise,callback){return Q(promise).tap(callback)},Promise.prototype.tap=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall(value).thenResolve(value)})},Q.when=when,Promise.prototype.thenResolve=function(value){return this.then(function(){return value})},Q.thenResolve=function(promise,value){return Q(promise).thenResolve(value)},Promise.prototype.thenReject=function(reason){return this.then(function(){throw reason})},Q.thenReject=function(promise,reason){return Q(promise).thenReject(reason)},Q.nearer=nearer,Q.isPromise=isPromise,Q.isPromiseAlike=isPromiseAlike,Q.isPending=function(object){return isPromise(object)&&"pending"===object.inspect().state},Promise.prototype.isPending=function(){return"pending"===this.inspect().state},Q.isFulfilled=function(object){return!isPromise(object)||"fulfilled"===object.inspect().state},Promise.prototype.isFulfilled=function(){return"fulfilled"===this.inspect().state},Q.isRejected=function(object){return isPromise(object)&&"rejected"===object.inspect().state},Promise.prototype.isRejected=function(){return"rejected"===this.inspect().state};var callback,name,alternative,unhandledReasons=[],unhandledRejections=[],reportedUnhandledRejections=[],trackUnhandledRejections=!0;function resetUnhandledRejections(){unhandledReasons.length=0,unhandledRejections.length=0,trackUnhandledRejections=trackUnhandledRejections||!0}function reject(reason){var rejection=Promise({when:function(rejected){var promise,at;return rejected&&(promise=this,trackUnhandledRejections)&&-1!==(at=array_indexOf(unhandledRejections,promise))&&("object"==typeof process&&"function"==typeof process.emit&&Q.nextTick.runAfter(function(){var atReport=array_indexOf(reportedUnhandledRejections,promise);-1!==atReport&&(process.emit("rejectionHandled",unhandledReasons[at],promise),reportedUnhandledRejections.splice(atReport,1))}),unhandledRejections.splice(at,1),unhandledReasons.splice(at,1)),rejected?rejected(reason):this}},function(){return this},function(){return{state:"rejected",reason:reason}});return((promise,reason)=>{trackUnhandledRejections&&("object"==typeof process&&"function"==typeof process.emit&&Q.nextTick.runAfter(function(){-1!==array_indexOf(unhandledRejections,promise)&&(process.emit("unhandledRejection",reason,promise),reportedUnhandledRejections.push(promise))}),unhandledRejections.push(promise),reason&&void 0!==reason.stack?unhandledReasons.push(reason.stack):unhandledReasons.push("(no stack) "+reason))})(rejection,reason),rejection}function fulfill(value){return Promise({when:function(){return value},get:function(name){return value[name]},set:function(name,rhs){value[name]=rhs},delete:function(name){delete value[name]},post:function(name,args){return null==name?value.apply(void 0,args):value[name].apply(value,args)},apply:function(thisp,args){return value.apply(thisp,args)},keys:function(){return object_keys(value)}},void 0,function(){return{state:"fulfilled",value:value}})}function spread(value,fulfilled,rejected){return Q(value).spread(fulfilled,rejected)}function dispatch(object,op,args){return Q(object).dispatch(op,args)}function all(promises){return when(promises,function(promises){var pendingCount=0,deferred=defer();return array_reduce(promises,function(undefined,promise,index){var snapshot;isPromise(promise)&&"fulfilled"===(snapshot=promise.inspect()).state?promises[index]=snapshot.value:(++pendingCount,when(promise,function(value){promises[index]=value,0==--pendingCount&&deferred.resolve(promises)},deferred.reject,function(progress){deferred.notify({index:index,value:progress})}))},void 0),0===pendingCount&&deferred.resolve(promises),deferred.promise})}function any(promises){var deferred,pendingCount;return 0===promises.length?Q.resolve():(deferred=Q.defer(),array_reduce(promises,function(prev,current,index){var promise=promises[index];pendingCount++,when(promise,function(result){deferred.resolve(result)},function(){0==--pendingCount&&deferred.reject(new Error("Can't get fulfillment value from any promise, all promises were rejected."))},function(progress){deferred.notify({index:index,value:progress})})},void(pendingCount=0)),deferred.promise)}function allResolved(promises){return when(promises,function(promises){return promises=array_map(promises,Q),when(all(array_map(promises,function(promise){return when(promise,noop,noop)})),function(){return promises})})}Q.resetUnhandledRejections=resetUnhandledRejections,Q.getUnhandledReasons=function(){return unhandledReasons.slice()},Q.stopUnhandledRejectionTracking=function(){resetUnhandledRejections(),trackUnhandledRejections=!1},resetUnhandledRejections(),Q.reject=reject,Q.fulfill=fulfill,Q.master=function(object){return Promise({isDef:function(){}},function(op,args){return dispatch(object,op,args)},function(){return Q(object).inspect()})},Q.spread=spread,Promise.prototype.spread=function(fulfilled,rejected){return this.all().then(function(array){return fulfilled.apply(void 0,array)},rejected)},Q.async=function(makeGenerator){return function(){function continuer(verb,arg){var result;if("undefined"==typeof StopIteration){try{result=generator[verb](arg)}catch(exception){return reject(exception)}return result.done?Q(result.value):when(result.value,callback,errback)}try{result=generator[verb](arg)}catch(exception){return(exception=>"[object StopIteration]"===object_toString(exception)||exception instanceof QReturnValue)(exception)?Q(exception.value):reject(exception)}return when(result,callback,errback)}var generator=makeGenerator.apply(this,arguments),callback=continuer.bind(continuer,"next"),errback=continuer.bind(continuer,"throw");return callback()}},Q.spawn=function(makeGenerator){Q.done(Q.async(makeGenerator)())},Q.return=function(value){throw new QReturnValue(value)},Q.promised=function(callback){return function(){return spread([this,all(arguments)],function(self,args){return callback.apply(self,args)})}},Q.dispatch=dispatch,Promise.prototype.dispatch=function(op,args){var self=this,deferred=defer();return Q.nextTick(function(){self.promiseDispatch(deferred.resolve,op,args)}),deferred.promise},Q.get=function(object,key){return Q(object).dispatch("get",[key])},Promise.prototype.get=function(key){return this.dispatch("get",[key])},Q.set=function(object,key,value){return Q(object).dispatch("set",[key,value])},Promise.prototype.set=function(key,value){return this.dispatch("set",[key,value])},Q.del=Q.delete=function(object,key){return Q(object).dispatch("delete",[key])},Promise.prototype.del=Promise.prototype.delete=function(key){return this.dispatch("delete",[key])},Q.mapply=Q.post=function(object,name,args){return Q(object).dispatch("post",[name,args])},Promise.prototype.mapply=Promise.prototype.post=function(name,args){return this.dispatch("post",[name,args])},Q.send=Q.mcall=Q.invoke=function(object,name){return Q(object).dispatch("post",[name,array_slice(arguments,2)])},Promise.prototype.send=Promise.prototype.mcall=Promise.prototype.invoke=function(name){return this.dispatch("post",[name,array_slice(arguments,1)])},Q.fapply=function(object,args){return Q(object).dispatch("apply",[void 0,args])},Promise.prototype.fapply=function(args){return this.dispatch("apply",[void 0,args])},Q.try=Q.fcall=function(object){return Q(object).dispatch("apply",[void 0,array_slice(arguments,1)])},Promise.prototype.fcall=function(){return this.dispatch("apply",[void 0,array_slice(arguments)])},Q.fbind=function(object){var promise=Q(object),args=array_slice(arguments,1);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Promise.prototype.fbind=function(){var promise=this,args=array_slice(arguments);return function(){return promise.dispatch("apply",[this,args.concat(array_slice(arguments))])}},Q.keys=function(object){return Q(object).dispatch("keys",[])},Promise.prototype.keys=function(){return this.dispatch("keys",[])},Q.all=all,Promise.prototype.all=function(){return all(this)},Q.any=any,Promise.prototype.any=function(){return any(this)},Q.allResolved=(callback=allResolved,name="allResolved",alternative="allSettled",function(){return"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(name+" is deprecated, use "+alternative+" instead.",new Error("").stack),callback.apply(callback,arguments)}),Promise.prototype.allResolved=function(){return allResolved(this)},Q.allSettled=function(promises){return Q(promises).allSettled()},Promise.prototype.allSettled=function(){return this.then(function(promises){return all(array_map(promises,function(promise){function regardless(){return promise.inspect()}return(promise=Q(promise)).then(regardless,regardless)}))})},Q.fail=Q.catch=function(object,rejected){return Q(object).then(void 0,rejected)},Promise.prototype.fail=Promise.prototype.catch=function(rejected){return this.then(void 0,rejected)},Q.progress=function(object,progressed){return Q(object).then(void 0,void 0,progressed)},Promise.prototype.progress=function(progressed){return this.then(void 0,void 0,progressed)},Q.fin=Q.finally=function(object,callback){return Q(object).finally(callback)},Promise.prototype.fin=Promise.prototype.finally=function(callback){return callback=Q(callback),this.then(function(value){return callback.fcall().then(function(){return value})},function(reason){return callback.fcall().then(function(){throw reason})})},Q.done=function(object,fulfilled,rejected,progress){return Q(object).done(fulfilled,rejected,progress)},Promise.prototype.done=function(fulfilled,rejected,progress){var onUnhandledError=function(error){Q.nextTick(function(){if(makeStackTraceLong(error,promise),!Q.onerror)throw error;Q.onerror(error)})},promise=fulfilled||rejected||progress?this.then(fulfilled,rejected,progress):this;"object"==typeof process&&process&&process.domain&&(onUnhandledError=process.domain.bind(onUnhandledError)),promise.then(void 0,onUnhandledError)},Q.timeout=function(object,ms,error){return Q(object).timeout(ms,error)},Promise.prototype.timeout=function(ms,error){var deferred=defer(),timeoutId=setTimeout(function(){error&&"string"!=typeof error||((error=new Error(error||"Timed out after "+ms+" ms")).code="ETIMEDOUT"),deferred.reject(error)},ms);return this.then(function(value){clearTimeout(timeoutId),deferred.resolve(value)},function(exception){clearTimeout(timeoutId),deferred.reject(exception)},deferred.notify),deferred.promise},Q.delay=function(object,timeout){return void 0===timeout&&(timeout=object,object=void 0),Q(object).delay(timeout)},Promise.prototype.delay=function(timeout){return this.then(function(value){var deferred=defer();return setTimeout(function(){deferred.resolve(value)},timeout),deferred.promise})},Q.nfapply=function(callback,args){return Q(callback).nfapply(args)},Promise.prototype.nfapply=function(args){var deferred=defer(),args=array_slice(args);return args.push(deferred.makeNodeResolver()),this.fapply(args).fail(deferred.reject),deferred.promise},Q.nfcall=function(callback){var args=array_slice(arguments,1);return Q(callback).nfapply(args)},Promise.prototype.nfcall=function(){var nodeArgs=array_slice(arguments),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.fapply(nodeArgs).fail(deferred.reject),deferred.promise},Q.nfbind=Q.denodeify=function(callback){var baseArgs=array_slice(arguments,1);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(callback).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nfbind=Promise.prototype.denodeify=function(){var args=array_slice(arguments);return args.unshift(this),Q.denodeify.apply(void 0,args)},Q.nbind=function(callback,thisp){var baseArgs=array_slice(arguments,2);return function(){var nodeArgs=baseArgs.concat(array_slice(arguments)),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(function(){return callback.apply(thisp,arguments)}).fapply(nodeArgs).fail(deferred.reject),deferred.promise}},Promise.prototype.nbind=function(){var args=array_slice(arguments,0);return args.unshift(this),Q.nbind.apply(void 0,args)},Q.nmapply=Q.npost=function(object,name,args){return Q(object).npost(name,args)},Promise.prototype.nmapply=Promise.prototype.npost=function(name,args){var args=array_slice(args||[]),deferred=defer();return args.push(deferred.makeNodeResolver()),this.dispatch("post",[name,args]).fail(deferred.reject),deferred.promise},Q.nsend=Q.nmcall=Q.ninvoke=function(object,name){var nodeArgs=array_slice(arguments,2),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),Q(object).dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Promise.prototype.nsend=Promise.prototype.nmcall=Promise.prototype.ninvoke=function(name){var nodeArgs=array_slice(arguments,1),deferred=defer();return nodeArgs.push(deferred.makeNodeResolver()),this.dispatch("post",[name,nodeArgs]).fail(deferred.reject),deferred.promise},Q.nodeify=function(object,nodeback){return Q(object).nodeify(nodeback)},Promise.prototype.nodeify=function(nodeback){if(!nodeback)return this;this.then(function(value){Q.nextTick(function(){nodeback(null,value)})},function(error){Q.nextTick(function(){nodeback(error)})})},Q.noConflict=function(){throw new Error("Q.noConflict only works when Q is used as a global")};var qEndingLine=captureLine();return Q});var texts=["Raising the masts...","Securing the oarlocks...","Hoisting the anchor...","Swabbing the decks...","Debarnacling the keel...","Checking the cargo manifest...","Assembling the crew...","Inspecting the turnbuckles...","Furling the rollers...","Lashing the jib-boom...","Tying the rigging...","Reinforcing the hull...","Bailing the bilge...","Feeding the parrot...","Consulting the map...","Calibrating the compass...","Polishing the spyglass...","Latching the portholes..."],intervalID=($("#loader p").text(texts[Math.floor(Math.random()*texts.length)]),setInterval(function(){$("#loader p").text(texts[Math.floor(Math.random()*texts.length)])},1300)),ConsoleBackend=($("#loader").data("intervalID",intervalID),((global,factory)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):(global=global||self).CodeMirror=factory()})(this,function(){var userAgent=navigator.userAgent,platform=navigator.platform,gecko=/gecko\/\d/i.test(userAgent),ie_upto10=/MSIE \d/.test(userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent),edge=/Edge\/(\d+)/.exec(userAgent),ie=ie_upto10||ie_11up||edge,ie_version=ie&&(ie_upto10?document.documentMode||6:+(edge||ie_11up)[1]),webkit=!edge&&/WebKit\//.test(userAgent),ie_upto10=webkit&&/Qt\/\d+\.\d+/.test(userAgent),chrome=!edge&&/Chrome\//.test(userAgent),presto=/Opera\//.test(userAgent),safari=/Apple Computer/.test(navigator.vendor),mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent),phantom=/PhantomJS/.test(userAgent),ios=!edge&&/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent),android=/Android/.test(userAgent),mobile=ios||android||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent),mac=ios||/Mac/.test(platform),chromeOS=/\bCrOS\b/.test(userAgent),windows=/win/i.test(platform),ie_11up=presto&&userAgent.match(/Version\/(\d*\.\d*)/),flipCtrlCmd=((ie_11up=ie_11up&&Number(ie_11up[1]))&&15<=ie_11up&&(webkit=!(presto=!1)),mac&&(ie_upto10||presto&&(null==ie_11up||ie_11up<12.11))),captureRightClick=gecko||ie&&9<=ie_version;function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}var rmClass=function(node,cls){var after,current=node.className,cls=classTest(cls).exec(current);cls&&(after=current.slice(cls.index+cls[0].length),node.className=current.slice(0,cls.index)+(after?cls[1]+after:""))};function removeChildren(e){for(var count=e.childNodes.length;0<count;--count)e.removeChild(e.firstChild);return e}function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}function elt(tag,content,className,style){var e=document.createElement(tag);if(className&&(e.className=className),style&&(e.style.cssText=style),"string"==typeof content)e.appendChild(document.createTextNode(content));else if(content)for(var i=0;i<content.length;++i)e.appendChild(content[i]);return e}function eltP(tag,content,className,style){tag=elt(tag,content,className,style);return tag.setAttribute("role","presentation"),tag}function contains(parent,child){if(3==child.nodeType&&(child=child.parentNode),parent.contains)return parent.contains(child);do{if((child=11==child.nodeType?child.host:child)==parent)return!0}while(child=child.parentNode)}function activeElt(){var activeElement;try{activeElement=document.activeElement}catch(e){activeElement=document.body||null}for(;activeElement&&activeElement.shadowRoot&&activeElement.shadowRoot.activeElement;)activeElement=activeElement.shadowRoot.activeElement;return activeElement}function addClass(node,cls){var current=node.className;classTest(cls).test(current)||(node.className+=(current?" ":"")+cls)}function joinClasses(a,b){for(var as=a.split(" "),i=0;i<as.length;i++)as[i]&&!classTest(as[i]).test(b)&&(b+=" "+as[i]);return b}var range=document.createRange?function(node,start,end,endNode){var r=document.createRange();return r.setEnd(endNode||node,end),r.setStart(node,start),r}:function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",end),r.moveStart("character",start),r},selectInput=function(node){node.select()};function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}function copyObj(obj,target,overwrite){for(var prop in target=target||{},obj)!obj.hasOwnProperty(prop)||!1===overwrite&&target.hasOwnProperty(prop)||(target[prop]=obj[prop]);return target}function countColumn(string,end,tabSize,startIndex,startValue){null==end&&-1==(end=string.search(/[^\s\u00a0]/))&&(end=string.length);for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i);if(nextTab<0||end<=nextTab)return n+(end-i);n=(n+=nextTab-i)+(tabSize-n%tabSize),i=nextTab+1}}ios?selectInput=function(node){node.selectionStart=0,node.selectionEnd=node.value.length}:ie&&(selectInput=function(node){try{node.select()}catch(_e){}});function Delayed(){this.id=null,this.f=null,this.time=0,this.handler=bind(this.onTimeout,this)}function indexOf(array,elt){for(var i=0;i<array.length;++i)if(array[i]==elt)return i;return-1}Delayed.prototype.onTimeout=function(self){self.id=0,self.time<=+new Date?self.f():setTimeout(self.handler,self.time-+new Date)};var scrollerGap=50,Pass={toString:function(){return"CodeMirror.Pass"}},sel_dontScroll={scroll:!(Delayed.prototype.set=function(ms,f){this.f=f;f=+new Date+ms;(!this.id||f<this.time)&&(clearTimeout(this.id),this.id=setTimeout(this.handler,ms),this.time=f)})},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"};function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos),skipped=(nextTab=-1==nextTab?string.length:nextTab)-pos;if(nextTab==string.length||goal<=col+skipped)return pos+Math.min(skipped,goal-col);if(col+=nextTab-pos,pos=nextTab+1,goal<=(col+=tabSize-col%tabSize))return pos}}var spaceStrs=[""];function spaceStr(n){for(;spaceStrs.length<=n;)spaceStrs.push(lst(spaceStrs)+" ");return spaceStrs[n]}function lst(arr){return arr[arr.length-1]}function map(array,f){for(var out=[],i=0;i<array.length;i++)out[i]=f(array[i],i);return out}function nothing(){}function createObj(base,props){base=Object.create?Object.create(base):(nothing.prototype=base,new nothing);return props&©Obj(props,base),base}var nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;function isWordCharBasic(ch){return/\w/.test(ch)||""<ch&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))}function isWordChar(ch,helper){return helper?!!(-1<helper.source.indexOf("\\w")&&isWordCharBasic(ch))||helper.test(ch):isWordCharBasic(ch)}function isEmpty(obj){for(var n in obj)if(obj.hasOwnProperty(n)&&obj[n])return;return 1}var extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function isExtendingChar(ch){return 768<=ch.charCodeAt(0)&&extendingChars.test(ch)}function skipExtendingChars(str,pos,dir){for(;(dir<0?0<pos:pos<str.length)&&isExtendingChar(str.charAt(pos));)pos+=dir;return pos}function findFirst(pred,from,to){for(var dir=to<from?-1:1;;){if(from==to)return from;var midF=(from+to)/2,midF=dir<0?Math.ceil(midF):Math.floor(midF);if(midF==from)return pred(midF)?from:to;pred(midF)?to=midF:from=midF+dir}}var bidiOther=null;function getBidiPartAt(order,ch,sticky){var found;bidiOther=null;for(var i=0;i<order.length;++i){var cur=order[i];if(cur.from<ch&&cur.to>ch)return i;cur.to==ch&&(cur.from!=cur.to&&"before"==sticky?found=i:bidiOther=i),cur.from==ch&&(cur.from!=cur.to&&"before"!=sticky?found=i:bidiOther=i)}return null!=found?found:bidiOther}bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/;var bidiRE,isNeutral,isStrong,countsAsLeft,countsAsNum,bidiOrdering=function(str,direction){var outerType="ltr"==direction?"L":"R";if(0==str.length||"ltr"==direction&&!bidiRE.test(str))return!1;for(var code,len=str.length,types=[],i=0;i<len;++i)types.push((code=str.charCodeAt(i))<=247?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(code):1424<=code&&code<=1524?"R":1536<=code&&code<=1785?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(code-1536):1774<=code&&code<=2220?"r":8192<=code&&code<=8203?"w":8204==code?"b":"L");for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1];"m"==type?types[i$1]=prev:prev=type}for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2];"1"==type$1&&"r"==cur?types[i$2]="n":isStrong.test(type$1)&&"r"==(cur=type$1)&&(types[i$2]="R")}for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3];"+"==type$2&&"1"==prev$1&&"1"==types[i$3+1]?types[i$3]="1":","!=type$2||prev$1!=types[i$3+1]||"1"!=prev$1&&"n"!=prev$1||(types[i$3]=prev$1),prev$1=type$2}for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4];if(","==type$3)types[i$4]="N";else if("%"==type$3){for(var end=void 0,end=i$4+1;end<len&&"%"==types[end];++end);for(var replace=i$4&&"!"==types[i$4-1]||end<len&&"1"==types[end]?"1":"N",j=i$4;j<end;++j)types[j]=replace;i$4=end-1}}for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5];"L"==cur$1&&"1"==type$4?types[i$5]="L":isStrong.test(type$4)&&(cur$1=type$4)}for(var i$6=0;i$6<len;++i$6)if(isNeutral.test(types[i$6])){for(var end$1=void 0,end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1);for(var before="L"==(i$6?types[i$6-1]:outerType),replace$1=before==("L"==(end$1<len?types[end$1]:outerType))?before?"L":"R":outerType,j$1=i$6;j$1<end$1;++j$1)types[j$1]=replace$1;i$6=end$1-1}for(var m,order=[],i$7=0;i$7<len;)if(countsAsLeft.test(types[i$7])){var start=i$7;for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7);order.push(new BidiSpan(0,start,i$7))}else{var pos=i$7,at=order.length,isRTL="rtl"==direction?1:0;for(++i$7;i$7<len&&"L"!=types[i$7];++i$7);for(var j$2=pos;j$2<i$7;)if(countsAsNum.test(types[j$2])){pos<j$2&&(order.splice(at,0,new BidiSpan(1,pos,j$2)),at+=isRTL);var nstart=j$2;for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2);order.splice(at,0,new BidiSpan(2,nstart,j$2)),at+=isRTL,pos=j$2}else++j$2;pos<i$7&&order.splice(at,0,new BidiSpan(1,pos,i$7))}return"ltr"==direction&&(1==order[0].level&&(m=str.match(/^\s+/))&&(order[0].from=m[0].length,order.unshift(new BidiSpan(0,0,m[0].length))),1==lst(order).level)&&(m=str.match(/\s+$/))&&(lst(order).to-=m[0].length,order.push(new BidiSpan(0,len-m[0].length,len))),"rtl"==direction?order.reverse():order};function BidiSpan(level,from,to){this.level=level,this.from=from,this.to=to}function getOrder(line,direction){var order=line.order;return order=null==order?line.order=bidiOrdering(line.text,direction):order}var noHandlers=[],on=function(emitter,type,f){emitter.addEventListener?emitter.addEventListener(type,f,!1):emitter.attachEvent?emitter.attachEvent("on"+type,f):(emitter=emitter._handlers||(emitter._handlers={}))[type]=(emitter[type]||noHandlers).concat(f)};function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers}function off(emitter,type,f){var arr;emitter.removeEventListener?emitter.removeEventListener(type,f,!1):emitter.detachEvent?emitter.detachEvent("on"+type,f):(arr=(emitter=emitter._handlers)&&emitter[type])&&-1<(f=indexOf(arr,f))&&(emitter[type]=arr.slice(0,f).concat(arr.slice(f+1)))}function signal(emitter,type){var handlers=getHandlers(emitter,type);if(handlers.length)for(var args=Array.prototype.slice.call(arguments,2),i=0;i<handlers.length;++i)handlers[i].apply(null,args)}function signalDOMEvent(cm,e,override){return"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}}),signal(cm,override||e.type,cm,e),e_defaultPrevented(e)||e.codemirrorIgnore}function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(arr)for(var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]),i=0;i<arr.length;++i)-1==indexOf(set,arr[i])&&set.push(arr[i])}function hasHandler(emitter,type){return 0<getHandlers(emitter,type).length}function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)},ctor.prototype.off=function(type,f){off(this,type,f)}}function e_preventDefault(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function e_stopPropagation(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function e_defaultPrevented(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function e_stop(e){e_preventDefault(e),e_stopPropagation(e)}function e_target(e){return e.target||e.srcElement}function e_button(e){var b=e.which;return null==b&&(1&e.button?b=1:2&e.button?b=3:4&e.button&&(b=2)),b=mac&&e.ctrlKey&&1==b?3:b}var zwspSupported,badBidiRects,dragAndDrop=!(ie&&ie_version<9)&&("draggable"in(edge=elt("div"))||"dragDrop"in edge);var splitLinesAuto=3!="\n\nb".split(/\n/).length?function(string){for(var pos=0,result=[],l=string.length;pos<=l;){var nl=string.indexOf("\n",pos),line=(-1==nl&&(nl=string.length),string.slice(pos,"\r"==string.charAt(nl-1)?nl-1:nl)),rt=line.indexOf("\r");-1!=rt?(result.push(line.slice(0,rt)),pos+=rt+1):(result.push(line),pos=nl+1)}return result}:function(string){return string.split(/\r\n?|\n/)},hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}catch(e){return!1}}:function(te){var range;try{range=te.ownerDocument.selection.createRange()}catch(e){}return!(!range||range.parentElement()!=te)&&0!=range.compareEndPoints("StartToEnd",range)},hasCopyEvent="oncopy"in(platform=elt("div"))||(platform.setAttribute("oncopy","return;"),"function"==typeof platform.oncopy),badZoomedRects=null;var modes={},mimeModes={};function resolveMode(spec){if("string"==typeof spec&&mimeModes.hasOwnProperty(spec))spec=mimeModes[spec];else if(spec&&"string"==typeof spec.name&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];(spec=createObj(found="string"==typeof found?{name:found}:found,spec)).name=found.name}else{if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec))return resolveMode("application/xml");if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec))return resolveMode("application/json")}return"string"==typeof spec?{name:spec}:spec||{name:"null"}}function getMode(options,spec){spec=resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)return getMode(options,"text/plain");var modeObj=mfactory(options,spec);if(modeExtensions.hasOwnProperty(spec.name)){var prop,exts=modeExtensions[spec.name];for(prop in exts)exts.hasOwnProperty(prop)&&(modeObj.hasOwnProperty(prop)&&(modeObj["_"+prop]=modeObj[prop]),modeObj[prop]=exts[prop])}if(modeObj.name=spec.name,spec.helperType&&(modeObj.helperType=spec.helperType),spec.modeProps)for(var prop$1 in spec.modeProps)modeObj[prop$1]=spec.modeProps[prop$1];return modeObj}var modeExtensions={};function extendMode(mode,properties){copyObj(properties,modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:modeExtensions[mode]={})}function copyState(mode,state){if(!0===state)return state;if(mode.copyState)return mode.copyState(state);var n,nstate={};for(n in state){var val=state[n];val instanceof Array&&(val=val.concat([])),nstate[n]=val}return nstate}function innerMode(mode,state){for(var info;mode.innerMode&&(info=mode.innerMode(state))&&info.mode!=mode;)state=info.state,mode=info.mode;return info||{mode:mode,state:state}}function startState(mode,a1,a2){return!mode.startState||mode.startState(a1,a2)}var StringStream=function(string,tabSize,lineOracle){this.pos=this.start=0,this.string=string,this.tabSize=tabSize||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=lineOracle};function getLine(doc,n){if((n-=doc.first)<0||n>=doc.size)throw new Error("There is no line "+(n+doc.first)+" in the document.");for(var chunk=doc;!chunk.lines;)for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(n<sz){chunk=child;break}n-=sz}return chunk.lines[n]}function getBetween(doc,start,end){var out=[],n=start.line;return doc.iter(start.line,end.line+1,function(line){line=line.text;n==end.line&&(line=line.slice(0,end.ch)),n==start.line&&(line=line.slice(start.ch)),out.push(line),++n}),out}function getLines(doc,from,to){var out=[];return doc.iter(from,to,function(line){out.push(line.text)}),out}function updateLineHeight(line,height){var diff=height-line.height;if(diff)for(var n=line;n;n=n.parent)n.height+=diff}function lineNo(line){if(null==line.parent)return null;for(var cur=line.parent,no=indexOf(cur.lines,line),chunk=cur.parent;chunk;chunk=(cur=chunk).parent)for(var i=0;chunk.children[i]!=cur;++i)no+=chunk.children[i].chunkSize();return no+cur.first}function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height;if(h<ch){chunk=child;continue outer}h-=ch,n+=child.chunkSize()}return n}while(!chunk.lines);for(var i=0;i<chunk.lines.length;++i){var lh=chunk.lines[i].height;if(h<lh)break;h-=lh}return n+i}function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}function Pos(line,ch,sticky){if(void 0===sticky&&(sticky=null),!(this instanceof Pos))return new Pos(line,ch,sticky);this.line=line,this.ch=ch,this.sticky=sticky}function cmp(a,b){return a.line-b.line||a.ch-b.ch}function equalCursorPos(a,b){return a.sticky==b.sticky&&0==cmp(a,b)}function copyPos(x){return Pos(x.line,x.ch)}function maxPos(a,b){return cmp(a,b)<0?b:a}function minPos(a,b){return cmp(a,b)<0?a:b}function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}function clipPos(doc,pos){var last;return pos.line<doc.first?Pos(doc.first,0):(last=doc.first+doc.size-1)<pos.line?Pos(last,getLine(doc,last).text.length):((pos,linelen)=>{var ch=pos.ch;return null==ch||linelen<ch?Pos(pos.line,linelen):ch<0?Pos(pos.line,0):pos})(pos,getLine(doc,pos.line).text.length)}function clipPosArray(doc,array){for(var out=[],i=0;i<array.length;i++)out[i]=clipPos(doc,array[i]);return out}StringStream.prototype.eol=function(){return this.pos>=this.string.length},StringStream.prototype.sol=function(){return this.pos==this.lineStart},StringStream.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},StringStream.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},StringStream.prototype.eat=function(match){var ch=this.string.charAt(this.pos),match="string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch));if(match)return++this.pos,ch},StringStream.prototype.eatWhile=function(match){for(var start=this.pos;this.eat(match););return this.pos>start},StringStream.prototype.eatSpace=function(){for(var start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>start},StringStream.prototype.skipToEnd=function(){this.pos=this.string.length},StringStream.prototype.skipTo=function(ch){ch=this.string.indexOf(ch,this.pos);if(-1<ch)return this.pos=ch,!0},StringStream.prototype.backUp=function(n){this.pos-=n},StringStream.prototype.column=function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.indentation=function(){return countColumn(this.string,null,this.tabSize)-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},StringStream.prototype.match=function(pattern,consume,caseInsensitive){var match;return"string"!=typeof pattern?(match=this.string.slice(this.pos).match(pattern))&&0<match.index?null:(match&&!1!==consume&&(this.pos+=match[0].length),match):(match=function(str){return caseInsensitive?str.toLowerCase():str})(this.string.substr(this.pos,pattern.length))==match(pattern)?(!1!==consume&&(this.pos+=pattern.length),!0):void 0},StringStream.prototype.current=function(){return this.string.slice(this.start,this.pos)},StringStream.prototype.hideFirstChars=function(n,inner){this.lineStart+=n;try{return inner()}finally{this.lineStart-=n}},StringStream.prototype.lookAhead=function(n){var oracle=this.lineOracle;return oracle&&oracle.lookAhead(n)},StringStream.prototype.baseToken=function(){var oracle=this.lineOracle;return oracle&&oracle.baseToken(this.pos)};var SavedContext=function(state,lookAhead){this.state=state,this.lookAhead=lookAhead},Context=function(doc,state,line,lookAhead){this.state=state,this.doc=doc,this.line=line,this.maxLookAhead=lookAhead||0,this.baseTokens=null,this.baseTokenPos=1};function highlightLine(cm,line,context,forceToEnd){for(var st=[cm.state.modeGen],lineClasses={},state=(runMode(cm,line.text,cm.doc.mode,context,function(end,style){st.push(end,style)},lineClasses,forceToEnd),context.state),o=0;o<cm.state.overlays.length;++o)(o=>{context.baseTokens=st;var overlay=cm.state.overlays[o],i=1,at=0;context.state=!0,runMode(cm,line.text,overlay.mode,context,function(end,style){for(var start=i;at<end;){var i_end=st[i];end<i_end&&st.splice(i,1,end,st[i+1],i_end),i+=2,at=Math.min(end,i_end)}if(style)if(overlay.opaque)st.splice(start,i-start,end,"overlay "+style),i=start+2;else for(;start<i;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"overlay "+style}},lineClasses),context.state=state,context.baseTokens=null,context.baseTokenPos=1})(o);return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}function getLineStyles(cm,line,updateFrontier){var context,resetState,result;return line.styles&&line.styles[0]==cm.state.modeGen||(context=getContextBefore(cm,lineNo(line)),resetState=line.text.length>cm.options.maxHighlightLength&©State(cm.doc.mode,context.state),result=highlightLine(cm,line,context),resetState&&(context.state=resetState),line.stateAfter=context.save(!resetState),line.styles=result.styles,result.classes?line.styleClasses=result.classes:line.styleClasses&&(line.styleClasses=null),updateFrontier===cm.doc.highlightFrontier&&(cm.doc.modeFrontier=Math.max(cm.doc.modeFrontier,++cm.doc.highlightFrontier))),line.styles}function getContextBefore(cm,n,precise){var start,saved,context,doc=cm.doc,display=cm.display;return doc.mode.startState?(start=((cm,n,precise)=>{for(var minindent,minline,doc=cm.doc,lim=precise?-1:n-(cm.doc.mode.innerMode?1e3:100),search=n;lim<search;--search){if(search<=doc.first)return doc.first;var line=getLine(doc,search-1),after=line.stateAfter;if(after&&(!precise||search+(after instanceof SavedContext?after.lookAhead:0)<=doc.modeFrontier))return search;after=countColumn(line.text,null,cm.options.tabSize);(null==minline||after<minindent)&&(minline=search-1,minindent=after)}return minline})(cm,n,precise),saved=doc.first<start&&getLine(doc,start-1).stateAfter,context=saved?Context.fromSaved(doc,saved,start):new Context(doc,startState(doc.mode),start),doc.iter(start,n,function(line){processLine(cm,line.text,context);var pos=context.line;line.stateAfter=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo?context.save():null,context.nextLine()}),precise&&(doc.modeFrontier=context.line),context):new Context(doc,!0,n)}function processLine(cm,text,context,startAt){var mode=cm.doc.mode,stream=new StringStream(text,cm.options.tabSize,context);for(stream.start=stream.pos=startAt||0,""==text&&callBlankLine(mode,context.state);!stream.eol();)readToken(mode,stream,context.state),stream.start=stream.pos}function callBlankLine(mode,state){return mode.blankLine?mode.blankLine(state):mode.innerMode&&(mode=innerMode(mode,state)).mode.blankLine?mode.mode.blankLine(mode.state):void 0}function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){inner&&(inner[0]=innerMode(mode,state).mode);var style=mode.token(stream,state);if(stream.pos>stream.start)return style}throw new Error("Mode "+mode.name+" failed to advance stream.")}Context.prototype.lookAhead=function(n){var line=this.doc.getLine(this.line+n);return null!=line&&n>this.maxLookAhead&&(this.maxLookAhead=n),line},Context.prototype.baseToken=function(n){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=n;)this.baseTokenPos+=2;var type=this.baseTokens[this.baseTokenPos+1];return{type:type&&type.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-n}},Context.prototype.nextLine=function(){this.line++,0<this.maxLookAhead&&this.maxLookAhead--},Context.fromSaved=function(doc,saved,line){return saved instanceof SavedContext?new Context(doc,copyState(doc.mode,saved.state),line,saved.lookAhead):new Context(doc,copyState(doc.mode,saved),line)},Context.prototype.save=function(copy){copy=!1!==copy?copyState(this.doc.mode,this.state):this.state;return 0<this.maxLookAhead?new SavedContext(copy,this.maxLookAhead):copy};var Token=function(stream,type,state){this.start=stream.start,this.end=stream.pos,this.string=stream.current(),this.type=type||null,this.state=state};function takeToken(cm,pos,precise,asArray){var style,tokens,doc=cm.doc,mode=doc.mode,line=getLine(doc,(pos=clipPos(doc,pos)).line),context=getContextBefore(cm,pos.line,precise),stream=new StringStream(line.text,cm.options.tabSize,context);for(asArray&&(tokens=[]);(asArray||stream.pos<pos.ch)&&!stream.eol();)stream.start=stream.pos,style=readToken(mode,stream,context.state),asArray&&tokens.push(new Token(stream,style,copyState(doc.mode,context.state)));return asArray?tokens:new Token(stream,style,context.state)}function extractLineClasses(type,output){if(type)for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass)break;type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";null==output[prop]?output[prop]=lineClass[2]:new RegExp("(?:^|\\s)"+lineClass[2]+"(?:$|\\s)").test(output[prop])||(output[prop]+=" "+lineClass[2])}return type}function runMode(cm,text,mode,context,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans,curStart=(null==flattenSpans&&(flattenSpans=cm.options.flattenSpans),0),curStyle=null,stream=new StringStream(text,cm.options.tabSize,context),inner=cm.options.addModeClass&&[null];for(""==text&&extractLineClasses(callBlankLine(mode,context.state),lineClasses);!stream.eol();){var mName,style=stream.pos>cm.options.maxHighlightLength?(flattenSpans=!1,forceToEnd&&processLine(cm,text,context,stream.pos),stream.pos=text.length,null):extractLineClasses(readToken(mode,stream,context.state,inner),lineClasses);if(inner&&(mName=inner[0].name)&&(style="m-"+(style?mName+" "+style:mName)),!flattenSpans||curStyle!=style){for(;curStart<stream.start;)f(curStart=Math.min(stream.start,curStart+5e3),curStyle);curStyle=style}stream.start=stream.pos}for(;curStart<stream.pos;){var pos=Math.min(stream.pos,curStart+5e3);f(pos,curStyle),curStart=pos}}var sawReadOnlySpans=!1,sawCollapsedSpans=!1;function MarkedSpan(marker,from,to){this.marker=marker,this.from=from,this.to=to}function getMarkedSpanFor(spans,marker){if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker)return span}}function stretchSpansOverChange(doc,change){if(change.full)return null;var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans,doc=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!doc)return null;var startCh=change.from.ch,endCh=change.to.ch,isInsert=0==cmp(change.from,change.to),first=((old,startCh,isInsert)=>{var nw;if(old)for(var i=0;i<old.length;++i){var endsAfter,span=old[i],marker=span.marker;!(null==span.from||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh))&&(span.from!=startCh||"bookmark"!=marker.type||isInsert&&span.marker.insertLeft)||(endsAfter=null==span.to||(marker.inclusiveRight?span.to>=startCh:span.to>startCh),(nw=nw||[]).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to)))}return nw})(oldFirst,startCh,isInsert),last=((old,endCh,isInsert)=>{var nw;if(old)for(var i=0;i<old.length;++i){var startsBefore,span=old[i],marker=span.marker;!(null==span.to||(marker.inclusiveRight?span.to>=endCh:span.to>endCh))&&(span.from!=endCh||"bookmark"!=marker.type||isInsert&&!span.marker.insertLeft)||(startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh),(nw=nw||[]).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,null==span.to?null:span.to-endCh)))}return nw})(doc,endCh,isInsert),sameLine=1==change.text.length,offset=lst(change.text).length+(sameLine?startCh:0);if(first)for(var i=0;i<first.length;++i){var found,span=first[i];null==span.to&&((found=getMarkedSpanFor(last,span.marker))?sameLine&&(span.to=null==found.to?null:found.to+offset):span.to=startCh)}if(last)for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1];null!=span$1.to&&(span$1.to+=offset),null==span$1.from?getMarkedSpanFor(first,span$1.marker)||(span$1.from=offset,sameLine&&(first=first||[]).push(span$1)):(span$1.from+=offset,sameLine&&(first=first||[]).push(span$1))}first=first&&clearEmptySpans(first),last&&last!=first&&(last=clearEmptySpans(last));var newMarkers=[first];if(!sameLine){var gapMarkers,gap=change.text.length-2;if(0<gap&&first)for(var i$2=0;i$2<first.length;++i$2)null==first[i$2].to&&(gapMarkers=gapMarkers||[]).push(new MarkedSpan(first[i$2].marker,null,null));for(var i$3=0;i$3<gap;++i$3)newMarkers.push(gapMarkers);newMarkers.push(last)}return newMarkers}function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];null!=span.from&&span.from==span.to&&!1!==span.marker.clearWhenEmpty&&spans.splice(i--,1)}return spans.length?spans:null}function detachMarkedSpans(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.detachLine(line);line.markedSpans=null}}function attachMarkedSpans(line,spans){if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.attachLine(line);line.markedSpans=spans}}function extraLeft(marker){return marker.inclusiveLeft?-1:0}function extraRight(marker){return marker.inclusiveRight?1:0}function compareCollapsedMarkers(a,b){var bPos,fromCmp,lenDiff=a.lines.length-b.lines.length;return 0!=lenDiff?lenDiff:(lenDiff=a.find(),bPos=b.find(),(fromCmp=cmp(lenDiff.from,bPos.from)||extraLeft(a)-extraLeft(b))?-fromCmp:cmp(lenDiff.to,bPos.to)||extraRight(a)-extraRight(b)||b.id-a.id)}function collapsedSpanAtSide(line,start){var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i)(sp=sps[i]).marker.collapsed&&null==(start?sp.from:sp.to)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker);return found}function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,!0)}function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,!1)}function conflictingCollapsedRange(doc,lineNo,from,to,marker){var doc=getLine(doc,lineNo),sps=sawCollapsedSpans&&doc.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed){var found=sp.marker.find(0),fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker),toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(!(0<=fromCmp&&toCmp<=0||fromCmp<=0&&0<=toCmp)&&(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?0<=cmp(found.to,from):0<cmp(found.to,from))||0<=fromCmp&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0)))return 1}}}function visualLine(line){for(var merged;merged=collapsedSpanAtStart(line);)line=merged.find(-1,!0).line;return line}function visualLineNo(doc,lineN){var doc=getLine(doc,lineN),vis=visualLine(doc);return doc==vis?lineN:lineNo(vis)}function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine())return lineN;var merged,line=getLine(doc,lineN);if(!lineIsHidden(doc,line))return lineN;for(;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return lineNo(line)+1}function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i)if((sp=sps[i]).marker.collapsed){if(null==sp.from)return!0;if(!sp.marker.widgetNode&&0==sp.from&&sp.marker.inclusiveLeft&&function lineIsHiddenInner(doc,line,span){{var end;if(null==span.to)return end=span.marker.find(1,!0),lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}if(span.marker.inclusiveRight&&span.to==line.text.length)return!0;for(var sp=void 0,i=0;i<line.markedSpans.length;++i)if((sp=line.markedSpans[i]).marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(null==sp.to||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp))return!0}(doc,line,sp))return!0}}function heightAtLine(lineObj){for(var h=0,chunk=(lineObj=visualLine(lineObj)).parent,i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj)break;h+=line.height}for(var p=chunk.parent;p;p=(chunk=p).parent)for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1];if(cur==chunk)break;h+=cur.height}return h}function lineLength(line){if(0==line.height)return 0;for(var merged,len=line.text.length,cur=line;merged=collapsedSpanAtStart(cur);){var found=merged.find(0,!0),cur=found.from.line;len+=found.from.ch-found.to.ch}for(cur=line;merged=collapsedSpanAtEnd(cur);)var found$1=merged.find(0,!0),len=(len-=cur.text.length-found$1.from.ch)+((cur=found$1.to.line).text.length-found$1.to.ch);return len}function findMaxLine(cm){var d=cm.display,cm=cm.doc;d.maxLine=getLine(cm,cm.first),d.maxLineLength=lineLength(d.maxLine),d.maxLineChanged=!0,cm.iter(function(line){var len=lineLength(line);len>d.maxLineLength&&(d.maxLineLength=len,d.maxLine=line)})}var Line=function(text,markedSpans,estimateHeight){this.text=text,attachMarkedSpans(this,markedSpans),this.height=estimateHeight?estimateHeight(this):1};Line.prototype.lineNo=function(){return lineNo(this)},eventMixin(Line);var styleToClassCache={},styleToClassCacheWithMode={};function interpretTokenStyle(style,options){return!style||/^\s*$/.test(style)?null:(options=options.addModeClass?styleToClassCacheWithMode:styleToClassCache)[style]||(options[style]=style.replace(/\S+/g,"cm-$&"))}function buildLineContent(cm,lineView){var content=eltP("span",null,null,webkit?"padding-right: .1px":null),builder={pre:eltP("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:!1,splitSpaces:cm.getOption("lineWrapping")};lineView.measure={};for(var r0,txt,i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=void 0,measure=(builder.pos=0,builder.addToken=buildToken,measure=cm.display.measure,txt=r0=void 0,(null!=badBidiRects?badBidiRects:(txt=removeChildrenAndAdd(measure,document.createTextNode("AخA")),r0=range(txt,0,1).getBoundingClientRect(),txt=range(txt,1,2).getBoundingClientRect(),removeChildren(measure),r0&&r0.left!=r0.right&&(badBidiRects=txt.right-r0.right<3)))&&(order=getOrder(line,cm.doc.direction))&&(builder.addToken=((inner,order)=>function(builder,text,style,startStyle,endStyle,css,attributes){style=style?style+" cm-force-border":"cm-force-border";for(var start=builder.pos,end=start+text.length;;){for(var part=void 0,i=0;i<order.length&&!((part=order[i]).to>start&&part.from<=start);i++);if(part.to>=end)return inner(builder,text,style,startStyle,endStyle,css,attributes);inner(builder,text.slice(0,part.to-start),style,startStyle,null,css,attributes),startStyle=null,text=text.slice(part.to-start),start=part.to}})(builder.addToken,order)),builder.map=[],lineView!=cm.display.externalMeasured&&lineNo(line));((line,builder,styles)=>{var spans=line.markedSpans,allText=line.text,at=0;if(spans)for(var style,css,spanStyle,spanEndStyle,spanStartStyle,collapsed,attributes,len=allText.length,pos=0,i=1,text="",nextChange=0;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=css="",collapsed=attributes=null,nextChange=1/0;for(var foundBookmarks=[],endStyles=void 0,j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;if("bookmark"==m.type&&sp.from==pos&&m.widgetNode)foundBookmarks.push(m);else if(sp.from<=pos&&(null==sp.to||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(null!=sp.to&&sp.to!=pos&&nextChange>sp.to&&(nextChange=sp.to,spanEndStyle=""),m.className&&(spanStyle+=" "+m.className),m.css&&(css=(css?css+";":"")+m.css),m.startStyle&&sp.from==pos&&(spanStartStyle+=" "+m.startStyle),m.endStyle&&sp.to==nextChange&&(endStyles=endStyles||[]).push(m.endStyle,sp.to),m.title&&((attributes=attributes||{}).title=m.title),m.attributes)for(var attr in m.attributes)(attributes=attributes||{})[attr]=m.attributes[attr];m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)&&(collapsed=sp)}else sp.from>pos&&nextChange>sp.from&&(nextChange=sp.from)}if(endStyles)for(var j$1=0;j$1<endStyles.length;j$1+=2)endStyles[j$1+1]==nextChange&&(spanEndStyle+=" "+endStyles[j$1]);if(!collapsed||collapsed.from==pos)for(var j$2=0;j$2<foundBookmarks.length;++j$2)buildCollapsedSpan(builder,0,foundBookmarks[j$2]);if(collapsed&&(collapsed.from||0)==pos){if(buildCollapsedSpan(builder,(null==collapsed.to?len+1:collapsed.to)-pos,collapsed.marker,null==collapsed.from),null==collapsed.to)return;collapsed.to==pos&&(collapsed=!1)}}if(len<=pos)break;for(var upto=Math.min(len,nextChange);;){if(text){var tokenText,end=pos+text.length;if(collapsed||(tokenText=upto<end?text.slice(0,upto-pos):text,builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",css,attributes)),upto<=end){text=text.slice(upto-pos),pos=upto;break}pos=end,spanStartStyle=""}text=allText.slice(at,at=styles[i++]),style=interpretTokenStyle(styles[i++],builder.cm.options)}}else for(var i$1=1;i$1<styles.length;i$1+=2)builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options))})(line,builder,getLineStyles(cm,line,measure)),line.styleClasses&&(line.styleClasses.bgClass&&(builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||"")),line.styleClasses.textClass)&&(builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||"")),0==builder.map.length&&builder.map.push(0,0,builder.content.appendChild((measure=>{var test;return(measure=(zwspSupported=null==zwspSupported&&(test=elt("span",""),removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")])),0!=measure.firstChild.offsetHeight)?test.offsetWidth<=1&&2<test.offsetHeight&&!(ie&&ie_version<8):zwspSupported)?elt("span",""):elt("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")).setAttribute("cm-text",""),measure})(cm.display.measure))),0==i?(lineView.measure.map=builder.map,lineView.measure.cache={}):((lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map),(lineView.measure.caches||(lineView.measure.caches=[])).push({}))}return webkit&&(content=builder.content.lastChild,/\bcm-tab\b/.test(content.className)||content.querySelector&&content.querySelector(".cm-tab"))&&(builder.content.className="cm-tab-wrap-hack"),signal(cm,"renderLine",cm,lineView.line,builder.pre),builder.pre.className&&(builder.textClass=joinClasses(builder.pre.className,builder.textClass||"")),builder}function defaultSpecialCharPlaceholder(ch){var token=elt("span","•","cm-invalidchar");return token.title="\\u"+ch.charCodeAt(0).toString(16),token.setAttribute("aria-label",token.title),token}function buildToken(builder,text,style,startStyle,endStyle,css,attributes){if(text){var displayText=builder.splitSpaces?((text,trailingBefore)=>{if(1<text.length&&!/ /.test(text))return text;for(var spaceBefore=trailingBefore,result="",i=0;i<text.length;i++){var ch=text.charAt(i);" "!=ch||!spaceBefore||i!=text.length-1&&32!=text.charCodeAt(i+1)||(ch=" "),result+=ch,spaceBefore=" "==ch}return result})(text,builder.trailingSpace):text,special=builder.cm.state.specialChars,mustWrap=!1;if(special.test(text))for(var content=document.createDocumentFragment(),pos=0;;){special.lastIndex=pos;var m=special.exec(text),skipped=m?m.index-pos:text.length-pos;if(skipped&&(txt=document.createTextNode(displayText.slice(pos,pos+skipped)),ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt),builder.map.push(builder.pos,builder.pos+skipped,txt),builder.col+=skipped,builder.pos+=skipped),!m)break;pos+=1+skipped;var txt=void 0;"\t"==m[0]?(skipped=builder.cm.options.tabSize,(txt=content.appendChild(elt("span",spaceStr(skipped=skipped-builder.col%skipped),"cm-tab"))).setAttribute("role","presentation"),txt.setAttribute("cm-text","\t"),builder.col+=skipped):("\r"==m[0]||"\n"==m[0]?(txt=content.appendChild(elt("span","\r"==m[0]?"␍":"","cm-invalidchar"))).setAttribute("cm-text",m[0]):((txt=builder.cm.options.specialCharPlaceholder(m[0])).setAttribute("cm-text",m[0]),ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt)),builder.col+=1),builder.map.push(builder.pos,builder.pos+1,txt),builder.pos++}else builder.col+=text.length,content=document.createTextNode(displayText),builder.map.push(builder.pos,builder.pos+text.length,content),ie&&ie_version<9&&(mustWrap=!0),builder.pos+=text.length;if(builder.trailingSpace=32==displayText.charCodeAt(text.length-1),style||startStyle||endStyle||mustWrap||css||attributes){var mustWrap=style||"",token=(startStyle&&(mustWrap+=startStyle),endStyle&&(mustWrap+=endStyle),elt("span",[content],mustWrap,css));if(attributes)for(var attr in attributes)attributes.hasOwnProperty(attr)&&"style"!=attr&&"class"!=attr&&token.setAttribute(attr,attributes[attr]);return builder.content.appendChild(token)}builder.content.appendChild(content)}}function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;widget&&builder.map.push(builder.pos,builder.pos+size,widget),!ignoreWidget&&builder.cm.display.input.needsContentAttribute&&(widget=widget||builder.content.appendChild(document.createElement("span"))).setAttribute("cm-marker",marker.id),widget&&(builder.cm.display.input.setUneditable(widget),builder.content.appendChild(widget)),builder.pos+=size,builder.trailingSpace=!1}function LineView(doc,line,lineN){this.line=line,this.rest=(line=>{for(var merged,lines;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line,(lines=lines||[]).push(line);return lines})(line),this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1,this.node=this.text=null,this.hidden=lineIsHidden(doc,line)}function buildViewArray(cm,from,to){for(var array=[],pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos),nextPos=pos+view.size;array.push(view)}return array}var operationGroup=null;function finishOperation(op,endCb){op=op.ownsGroup;if(op)try{(group=>{var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)callbacks[i].call(null);for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)for(;op.cursorActivityCalled<op.cursorActivityHandlers.length;)op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}while(i<callbacks.length)})(op)}finally{operationGroup=null,endCb(op)}}var orphanDelayedCallbacks=null;function signalLater(emitter,type){var arr=getHandlers(emitter,type);if(arr.length)for(var list,args=Array.prototype.slice.call(arguments,2),i=(operationGroup?list=operationGroup.delayedCallbacks:orphanDelayedCallbacks?list=orphanDelayedCallbacks:(list=orphanDelayedCallbacks=[],setTimeout(fireOrphanDelayed,0)),0);i<arr.length;++i)(i=>{list.push(function(){return arr[i].apply(null,args)})})(i)}function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i)delayed[i]()}function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];"text"==type?((cm,lineView)=>{var cls=lineView.text.className,built=getLineContent(cm,lineView);lineView.text==lineView.node&&(lineView.node=built.pre),lineView.text.parentNode.replaceChild(built.pre,lineView.text),lineView.text=built.pre,built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass?(lineView.bgClass=built.bgClass,lineView.textClass=built.textClass,updateLineClasses(cm,lineView)):cls&&(lineView.text.className=cls)})(cm,lineView):"gutter"==type?updateLineGutter(cm,lineView,lineN,dims):"class"==type?updateLineClasses(cm,lineView):"widget"==type&&((cm,lineView,dims)=>{lineView.alignable&&(lineView.alignable=null);for(var isWidget=classTest("CodeMirror-linewidget"),node=lineView.node.firstChild,next=void 0;node;node=next)next=node.nextSibling,isWidget.test(node.className)&&lineView.node.removeChild(node);insertLineWidgets(cm,lineView,dims)})(cm,lineView,dims)}lineView.changes=null}function ensureLineWrapped(lineView){return lineView.node==lineView.text&&(lineView.node=elt("div",null,null,"position: relative"),lineView.text.parentNode&&lineView.text.parentNode.replaceChild(lineView.node,lineView.text),lineView.node.appendChild(lineView.text),ie)&&ie_version<8&&(lineView.node.style.zIndex=2),lineView.node}function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;return ext&&ext.line==lineView.line?(cm.display.externalMeasured=null,lineView.measure=ext.measure,ext.built):buildLineContent(cm,lineView)}function updateLineClasses(cm,lineView){((cm,lineView)=>{var wrap,cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;cls&&(cls+=" CodeMirror-linebackground"),lineView.background?cls?lineView.background.className=cls:(lineView.background.parentNode.removeChild(lineView.background),lineView.background=null):cls&&(wrap=ensureLineWrapped(lineView),lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild),cm.display.input.setUneditable(lineView.background))})(cm,lineView),lineView.line.wrapClass?ensureLineWrapped(lineView).className=lineView.line.wrapClass:lineView.node!=lineView.text&&(lineView.node.className="");cm=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=cm||""}function updateLineGutter(cm,lineView,lineN,dims){lineView.gutter&&(lineView.node.removeChild(lineView.gutter),lineView.gutter=null),lineView.gutterBackground&&(lineView.node.removeChild(lineView.gutterBackground),lineView.gutterBackground=null),lineView.line.gutterClass&&(wrap=ensureLineWrapped(lineView),lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,"left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+dims.gutterTotalWidth+"px"),cm.display.input.setUneditable(lineView.gutterBackground),wrap.insertBefore(lineView.gutterBackground,lineView.text));var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap=ensureLineWrapped(lineView),gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper","left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px");if(cm.display.input.setUneditable(gutterWrap),wrap.insertBefore(gutterWrap,lineView.text),lineView.line.gutterClass&&(gutterWrap.className+=" "+lineView.line.gutterClass),!cm.options.lineNumbers||markers&&markers["CodeMirror-linenumbers"]||(lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+dims.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+cm.display.lineNumInnerWidth+"px"))),markers)for(var k=0;k<cm.display.gutterSpecs.length;++k){var id=cm.display.gutterSpecs[k].className,found=markers.hasOwnProperty(id)&&markers[id];found&&gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt","left: "+dims.gutterLeft[id]+"px; width: "+dims.gutterWidth[id]+"px"))}}}function insertLineWidgets(cm,lineView,dims){if(insertLineWidgetsFor(cm,lineView.line,lineView,dims,!0),lineView.rest)for(var i=0;i<lineView.rest.length;i++)insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,!1)}function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(line.widgets)for(var wrap=ensureLineWrapped(lineView),i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget"+(widget.className?" "+widget.className:""));widget.handleMouseEvents||node.setAttribute("cm-ignore-events","true"),((widget,node,lineView,dims)=>{widget.noHScroll&&((lineView.alignable||(lineView.alignable=[])).push(node),lineView=dims.wrapperWidth,node.style.left=dims.fixedPos+"px",widget.coverGutter||(lineView-=dims.gutterTotalWidth,node.style.paddingLeft=dims.gutterTotalWidth+"px"),node.style.width=lineView+"px"),widget.coverGutter&&(node.style.zIndex=5,node.style.position="relative",widget.noHScroll||(node.style.marginLeft=-dims.gutterTotalWidth+"px"))})(widget,node,lineView,dims),cm.display.input.setUneditable(node),allowAbove&&widget.above?wrap.insertBefore(node,lineView.gutter||lineView.text):wrap.appendChild(node),signalLater(widget,"redraw")}}function widgetHeight(widget){var cm,parentStyle;return null!=widget.height?widget.height:(cm=widget.doc.cm)?(contains(document.body,widget.node)||(parentStyle="position: relative;",widget.coverGutter&&(parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;"),widget.noHScroll&&(parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;"),removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))),widget.height=widget.node.parentNode.offsetHeight):0}function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==display.sizer&&n!=display.mover)return 1}function paddingTop(display){return display.lineSpace.offsetTop}function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}function paddingH(display){var e;return display.cachedPaddingH||(e=removeChildrenAndAdd(display.measure,elt("pre","x","CodeMirror-line-like")),e=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,e={left:parseInt(e.paddingLeft),right:parseInt(e.paddingRight)},isNaN(e.left)||isNaN(e.right)||(display.cachedPaddingH=e),e)}function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}function mapFromLineView(lineView,line,lineN){if(lineView.line==line)return{map:lineView.measure.map,cache:lineView.measure.cache};for(var i=0;i<lineView.rest.length;i++)if(lineView.rest[i]==line)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]};for(var i$1=0;i$1<lineView.rest.length;i$1++)if(lineNo(lineView.rest[i$1])>lineN)return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:!0}}function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}function findViewForLine(cm,lineN){return lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo?cm.display.view[findViewIndex(cm,lineN)]:(cm=cm.display.externalMeasured)&&lineN>=cm.lineN&&lineN<cm.lineN+cm.size?cm:void 0}function prepareMeasureForLine(cm,line){var lineN=lineNo(line),view=findViewForLine(cm,lineN),cm=(view&&!view.text?view=null:view&&view.changes&&(updateLineForChanges(cm,view,lineN,getDimensions(cm)),cm.curOp.forceUpdate=!0),mapFromLineView(view=view||((cm,line)=>{var lineN=lineNo(line=visualLine(line)),lineN=((line=cm.display.externalMeasured=new LineView(cm.doc,line,lineN)).lineN=lineN,line.built=buildLineContent(cm,line));return line.text=lineN.pre,removeChildrenAndAdd(cm.display.lineMeasure,lineN.pre),line})(cm,line),line,lineN));return{line:line,view:view,rect:null,map:cm.map,cache:cm.cache,before:cm.before,hasHeights:!1}}function measureCharPrepared(cm,prepared,ch,bias,varHeight){var found,key=(ch=prepared.before?-1:ch)+(bias||"");return prepared.cache.hasOwnProperty(key)?found=prepared.cache[key]:(prepared.rect||(prepared.rect=prepared.view.text.getBoundingClientRect()),prepared.hasHeights||(((cm,lineView,rect)=>{var wrapping=cm.options.lineWrapping,cm=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=cm){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=cm;for(var rects=lineView.text.firstChild.getClientRects(),i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];2<Math.abs(cur.bottom-next.bottom)&&heights.push((cur.bottom+next.top)/2-rect.top)}}heights.push(rect.bottom-rect.top)}})(cm,prepared.view,prepared.rect),prepared.hasHeights=!0),(found=((cm,prepared,ch,bias)=>{var rect,place=nodeAndOffsetInLineMap(prepared.map,ch,bias),node=place.node,start=place.start,end=place.end,collapse=place.collapse;if(3==node.nodeType){for(var i$1=0;i$1<4;i$1++){for(;start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start));)--start;for(;place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end));)++end;if((rect=ie&&ie_version<9&&0==start&&end==place.coverEnd-place.coverStart?node.parentNode.getBoundingClientRect():((rects,bias)=>{var rect=nullRect;if("left"==bias)for(var i=0;i<rects.length&&(rect=rects[i]).left==rect.right;i++);else for(var i$1=rects.length-1;0<=i$1&&(rect=rects[i$1]).left==rect.right;i$1--);return rect})(range(node,start,end).getClientRects(),bias)).left||rect.right||0==start)break;end=start,start-=1,collapse="right"}ie&&ie_version<11&&(rect=((measure,rect)=>{var scaleY;return window.screen&&null!=screen.logicalXDPI&&screen.logicalXDPI!=screen.deviceXDPI&&(measure=>{var normal;return null!=badZoomedRects?badZoomedRects:(normal=(measure=removeChildrenAndAdd(measure,elt("span","x"))).getBoundingClientRect(),measure=range(measure,0,1).getBoundingClientRect(),badZoomedRects=1<Math.abs(normal.left-measure.left))})(measure)?(measure=screen.logicalXDPI/screen.deviceXDPI,scaleY=screen.logicalYDPI/screen.deviceYDPI,{left:rect.left*measure,right:rect.right*measure,top:rect.top*scaleY,bottom:rect.bottom*scaleY}):rect})(cm.display.measure,rect))}else 0<start&&(collapse=bias="right"),rect=cm.options.lineWrapping&&1<(ch=node.getClientRects()).length?ch["right"==bias?ch.length-1:0]:node.getBoundingClientRect();!(ie&&ie_version<9)||start||rect&&(rect.left||rect.right)||(ch=node.parentNode.getClientRects()[0],rect=ch?{left:ch.left,right:ch.left+charWidth(cm.display),top:ch.top,bottom:ch.bottom}:nullRect);for(var ch=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top,mid=(ch+rbot)/2,heights=prepared.view.measure.heights,i=0;i<heights.length-1&&!(mid<heights[i]);i++);var top=i?heights[i-1]:0,bot=heights[i],top={left:("right"==collapse?rect.right:rect.left)-prepared.rect.left,right:("left"==collapse?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};return rect.left||rect.right||(top.bogus=!0),cm.options.singleCursorHeightPerLine||(top.rtop=ch,top.rbottom=rbot),top})(cm,prepared,ch,bias)).bogus||(prepared.cache[key]=found)),{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}var measureText,nullRect={left:0,right:0,top:0,bottom:0};function nodeAndOffsetInLineMap(map,ch,bias){for(var node,start,end,collapse,mStart,mEnd,i=0;i<map.length;i+=3)if(mEnd=map[i+1],ch<(mStart=map[i])?(start=0,end=1,collapse="left"):ch<mEnd?end=(start=ch-mStart)+1:(i==map.length-3||ch==mEnd&&map[i+3]>ch)&&(start=(end=mEnd-mStart)-1,mEnd<=ch)&&(collapse="right"),null!=start){if(node=map[i+2],mStart==mEnd&&bias==(node.insertLeft?"left":"right")&&(collapse=bias),"left"==bias&&0==start)for(;i&&map[i-2]==map[i-3]&&map[i-1].insertLeft;)node=map[2+(i-=3)],collapse="left";if("right"==bias&&start==mEnd-mStart)for(;i<map.length-3&&map[i+3]==map[i+4]&&!map[i+5].insertLeft;)node=map[(i+=3)+2],collapse="right";break}return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}function clearLineMeasurementCacheFor(lineView){if(lineView.measure&&(lineView.measure.cache={},lineView.measure.heights=null,lineView.rest))for(var i=0;i<lineView.rest.length;i++)lineView.measure.caches[i]={}}function clearLineMeasurementCache(cm){cm.display.externalMeasure=null,removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)clearLineMeasurementCacheFor(cm.display.view[i])}function clearCaches(cm){clearLineMeasurementCache(cm),cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null,cm.options.lineWrapping||(cm.display.maxLineChanged=!0),cm.display.lineNumChars=null}function pageScrollX(){return chrome&&android?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function pageScrollY(){return chrome&&android?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):window.pageYOffset||(document.documentElement||document.body).scrollTop}function widgetTopHeight(lineObj){var height=0;if(lineObj.widgets)for(var i=0;i<lineObj.widgets.length;++i)lineObj.widgets[i].above&&(height+=widgetHeight(lineObj.widgets[i]));return height}function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){return includeWidgets||(includeWidgets=widgetTopHeight(lineObj),rect.top+=includeWidgets,rect.bottom+=includeWidgets),"line"!=context&&(context=context||"local",includeWidgets=heightAtLine(lineObj),"local"==context?includeWidgets+=paddingTop(cm.display):includeWidgets-=cm.display.viewOffset,"page"!=context&&"window"!=context||(includeWidgets+=(lineObj=cm.display.lineSpace.getBoundingClientRect()).top+("window"==context?0:pageScrollY()),cm=lineObj.left+("window"==context?0:pageScrollX()),rect.left+=cm,rect.right+=cm),rect.top+=includeWidgets,rect.bottom+=includeWidgets),rect}function fromCoordSystem(cm,coords,context){var left;return"div"==context?coords:(left=coords.left,coords=coords.top,"page"==context?(left-=pageScrollX(),coords-=pageScrollY()):"local"!=context&&context||(left+=(context=cm.display.sizer.getBoundingClientRect()).left,coords+=context.top),{left:left-(context=cm.display.lineSpace.getBoundingClientRect()).left,top:coords-context.top})}function charCoords(cm,pos,context,lineObj,bias){return intoCoordSystem(cm,lineObj=lineObj||getLine(cm.doc,pos.line),measureChar(cm,lineObj,pos.ch,bias),context)}function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){function get(ch,right){ch=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);return right?ch.left=ch.right:ch.right=ch.left,intoCoordSystem(cm,lineObj,ch,context)}lineObj=lineObj||getLine(cm.doc,pos.line),preparedMeasure=preparedMeasure||prepareMeasureForLine(cm,lineObj);var other,partPos,order=getOrder(lineObj,cm.doc.direction),ch=pos.ch,pos=pos.sticky;return ch>=lineObj.text.length?(ch=lineObj.text.length,pos="before"):ch<=0&&(ch=0,pos="after"),order?(partPos=getBidiPartAt(order,ch,pos),other=bidiOther,partPos=getBidi(ch,partPos,"before"==pos),null!=other&&(partPos.other=getBidi(ch,other,"before"!=pos)),partPos):get("before"==pos?ch-1:ch,"before"==pos);function getBidi(ch,partPos,invert){return get(invert?ch-1:ch,1==order[partPos].level!=invert)}}function estimateCoords(cm,pos){var left=0,pos=(pos=clipPos(cm.doc,pos),cm.options.lineWrapping||(left=charWidth(cm.display)*pos.ch),getLine(cm.doc,pos.line)),cm=heightAtLine(pos)+paddingTop(cm.display);return{left:left,right:left,top:cm,bottom:cm+pos.height}}function PosWithInfo(line,ch,sticky,outside,xRel){line=Pos(line,ch,sticky);return line.xRel=xRel,outside&&(line.outside=outside),line}function coordsChar(cm,x,y){var doc=cm.doc;if((y+=cm.display.viewOffset)<0)return PosWithInfo(doc.first,0,null,-1,-1);var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(last<lineN)return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,null,1,1);x<0&&(x=0);for(var lineObj=getLine(doc,lineN);;){var found=((cm,lineObj,lineNo,x,y)=>{y-=heightAtLine(lineObj);var atLeft,atStart,preparedMeasure=prepareMeasureForLine(cm,lineObj),widgetHeight=widgetTopHeight(lineObj),begin=0,end=lineObj.text.length,ltr=!0,chAround=((order=getOrder(lineObj,cm.doc.direction))&&(ltr=1!=(order=(cm.options.lineWrapping?function(cm,lineObj,_lineNo,preparedMeasure,order,x,y){var y=wrappedLineExtent(cm,lineObj,preparedMeasure,y),begin=y.begin,end=y.end;/\s/.test(lineObj.text.charAt(end-1))&&end--;for(var part=null,closestDist=null,i=0;i<order.length;i++){var endX,p=order[i];p.from>=end||p.to<=begin||(endX=measureCharPrepared(cm,preparedMeasure,1!=p.level?Math.min(end,p.to)-1:Math.max(begin,p.from)).right,endX=endX<x?x-endX+1e9:endX-x,(!part||endX<closestDist)&&(part=p,closestDist=endX))}part=part||order[order.length-1];part.from<begin&&(part={from:begin,to:part.to,level:part.level});part.to>end&&(part={from:part.from,to:end,level:part.level});return part}:function(cm,lineObj,lineNo,preparedMeasure,order,x,y){var index=findFirst(function(i){var i=order[i],ltr=1!=i.level;return boxIsAfter(cursorCoords(cm,Pos(lineNo,ltr?i.to:i.from,ltr?"before":"after"),"line",lineObj,preparedMeasure),x,y,!0)},0,order.length-1),part=order[index];{var ltr;0<index&&(ltr=1!=part.level,boxIsAfter(ltr=cursorCoords(cm,Pos(lineNo,ltr?part.from:part.to,ltr?"after":"before"),"line",lineObj,preparedMeasure),x,y,!0))&<r.top>y&&(part=order[index-1])}return part})(cm,lineObj,lineNo,preparedMeasure,order,x,y)).level,begin=ltr?order.from:order.to-1,end=ltr?order.to:order.from-1),null),boxAround=null,order=findFirst(function(ch){var box=measureCharPrepared(cm,preparedMeasure,ch);return box.top+=widgetHeight,box.bottom+=widgetHeight,boxIsAfter(box,x,y,!1)&&(box.top<=y&&box.left<=x&&(chAround=ch,boxAround=box),1)},begin,end),outside=!1;return boxAround?(atLeft=x-boxAround.left<boxAround.right-x,order=chAround+((atStart=atLeft==ltr)?0:1),atStart=atStart?"after":"before",atLeft=atLeft?boxAround.left:boxAround.right):(ltr||order!=end&&order!=begin||order++,atStart=0==order||order!=lineObj.text.length&&measureCharPrepared(cm,preparedMeasure,order-(ltr?1:0)).bottom+widgetHeight<=y==ltr?"after":"before",end=cursorCoords(cm,Pos(lineNo,order,atStart),"line",lineObj,preparedMeasure),atLeft=end.left,outside=y<end.top?-1:y>=end.bottom?1:0),order=skipExtendingChars(lineObj.text,order,1),PosWithInfo(lineNo,order,atStart,outside,x-atLeft)})(cm,lineObj,lineN,x,y),collapsed=((line,ch)=>{var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];sp.marker.collapsed&&(null==sp.from||sp.from<ch)&&(null==sp.to||sp.to>ch)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker)}return found})(lineObj,found.ch+(0<found.xRel||0<found.outside?1:0));if(!collapsed)return found;found=collapsed.find(1);if(found.line==lineN)return found;lineObj=getLine(doc,lineN=found.line)}}function wrappedLineExtent(cm,lineObj,preparedMeasure,y){y-=widgetTopHeight(lineObj);var lineObj=lineObj.text.length,begin=findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch-1).bottom<=y},lineObj,0);return{begin:begin,end:findFirst(function(ch){return measureCharPrepared(cm,preparedMeasure,ch).top>y},begin,lineObj)}}function wrappedLineExtentChar(cm,lineObj,preparedMeasure,target){return wrappedLineExtent(cm,lineObj,preparedMeasure=preparedMeasure||prepareMeasureForLine(cm,lineObj),intoCoordSystem(cm,lineObj,measureCharPrepared(cm,preparedMeasure,target),"line").top)}function boxIsAfter(box,x,y,left){return!(box.bottom<=y)&&(box.top>y||(left?box.left:box.right)>x)}function textHeight(display){if(null!=display.cachedTextHeight)return display.cachedTextHeight;if(null==measureText){measureText=elt("pre",null,"CodeMirror-line-like");for(var i=0;i<49;++i)measureText.appendChild(document.createTextNode("x")),measureText.appendChild(elt("br"));measureText.appendChild(document.createTextNode("x"))}removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;return 3<height&&(display.cachedTextHeight=height),removeChildren(display.measure),height||1}function charWidth(display){var pre,anchor;return null!=display.cachedCharWidth?display.cachedCharWidth:(anchor=elt("span","xxxxxxxxxx"),pre=elt("pre",[anchor],"CodeMirror-line-like"),removeChildrenAndAdd(display.measure,pre),2<(anchor=((pre=anchor.getBoundingClientRect()).right-pre.left)/10)&&(display.cachedCharWidth=anchor),anchor||10)}function getDimensions(cm){for(var d=cm.display,left={},width={},gutterLeft=d.gutters.clientLeft,n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){var id=cm.display.gutterSpecs[i].className;left[id]=n.offsetLeft+n.clientLeft+gutterLeft,width[id]=n.clientWidth}return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping,perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line))return 0;var widgetsHeight=0;if(line.widgets)for(var i=0;i<line.widgets.length;i++)line.widgets[i].height&&(widgetsHeight+=line.widgets[i].height);return wrapping?widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th:widgetsHeight+th}}function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);estHeight!=line.height&&updateLineHeight(line,estHeight)})}function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&"true"==e_target(e).getAttribute("cm-not-content"))return null;var x,y,liberal=display.lineSpace.getBoundingClientRect();try{x=e.clientX-liberal.left,y=e.clientY-liberal.top}catch(e$1){return null}display=coordsChar(cm,x,y);return forRect&&0<display.xRel&&(e=getLine(cm.doc,display.line).text).length==display.ch&&(liberal=countColumn(e,e.length,cm.options.tabSize)-e.length,display=Pos(display.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-liberal))),display}function findViewIndex(cm,n){if(n>=cm.display.viewTo)return null;if((n-=cm.display.viewFrom)<0)return null;for(var view=cm.display.view,i=0;i<view.length;i++)if((n-=view[i].size)<0)return i}function regChange(cm,from,to,lendiff){null==from&&(from=cm.doc.first),null==to&&(to=cm.doc.first+cm.doc.size);var cutBot,display=cm.display,cut=((lendiff=lendiff||0)&&to<display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>from)&&(display.updateLineNumbers=from),cm.curOp.viewChanged=!0,from>=display.viewTo?sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo&&resetView(cm):to<=display.viewFrom?sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom?resetView(cm):(display.viewFrom+=lendiff,display.viewTo+=lendiff):from<=display.viewFrom&&to>=display.viewTo?resetView(cm):from<=display.viewFrom?(cut=viewCuttingPoint(cm,to,to+lendiff,1))?(display.view=display.view.slice(cut.index),display.viewFrom=cut.lineN,display.viewTo+=lendiff):resetView(cm):to>=display.viewTo?(cut=viewCuttingPoint(cm,from,from,-1))?(display.view=display.view.slice(0,cut.index),display.viewTo=cut.lineN):resetView(cm):(cut=viewCuttingPoint(cm,from,from,-1),cutBot=viewCuttingPoint(cm,to,to+lendiff,1),cut&&cutBot?(display.view=display.view.slice(0,cut.index).concat(buildViewArray(cm,cut.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index)),display.viewTo+=lendiff):resetView(cm)),display.externalMeasured);cut&&(to<cut.lineN?cut.lineN+=lendiff:from<cut.lineN+cut.size&&(display.externalMeasured=null))}function regLineChange(cm,line,type){cm.curOp.viewChanged=!0;var display=cm.display,ext=cm.display.externalMeasured;ext&&line>=ext.lineN&&line<ext.lineN+ext.size&&(display.externalMeasured=null),line<display.viewFrom||line>=display.viewTo||null!=(ext=display.view[findViewIndex(cm,line)]).node&&-1==indexOf(display=ext.changes||(ext.changes=[]),type)&&display.push(type)}function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first,cm.display.view=[],cm.display.viewOffset=0}function viewCuttingPoint(cm,oldN,newN,dir){var diff,index=findViewIndex(cm,oldN),view=cm.display.view;if(sawCollapsedSpans&&newN!=cm.doc.first+cm.doc.size){for(var n=cm.display.viewFrom,i=0;i<index;i++)n+=view[i].size;if(n!=oldN){if(0<dir){if(index==view.length-1)return null;diff=n+view[index].size-oldN,index++}else diff=n-oldN;oldN+=diff,newN+=diff}for(;visualLineNo(cm.doc,newN)!=newN;){if(index==(dir<0?0:view.length-1))return null;newN+=dir*view[index-(dir<0?1:0)].size,index+=dir}}return{index:index,lineN:newN}}function countDirtyView(cm){for(var view=cm.display.view,dirty=0,i=0;i<view.length;i++){var lineView=view[i];lineView.hidden||lineView.node&&!lineView.changes||++dirty}return dirty}function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())}function prepareSelection(cm,primary){void 0===primary&&(primary=!0);for(var range,collapsed,doc=cm.doc,result={},curFragment=result.cursors=document.createDocumentFragment(),selFragment=result.selection=document.createDocumentFragment(),i=0;i<doc.sel.ranges.length;i++)!primary&&i==doc.sel.primIndex||(range=doc.sel.ranges[i]).from().line>=cm.display.viewTo||range.to().line<cm.display.viewFrom||(((collapsed=range.empty())||cm.options.showCursorWhenSelecting)&&drawSelectionCursor(cm,range.head,curFragment),collapsed)||((cm,range,output)=>{var toLine,display=cm.display,doc=cm.doc,fragment=document.createDocumentFragment(),padding=paddingH(cm.display),leftSide=padding.left,rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right,docLTR="ltr"==doc.direction;function add(left,top,width,bottom){top<0&&(top=0),top=Math.round(top),bottom=Math.round(bottom),fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(null==width?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"))}function drawForLine(line,fromArg,toArg){var start,end,lineObj=getLine(doc,line),lineLen=lineObj.text.length;function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}function wrapX(pos,dir,side){pos=wrappedLineExtentChar(cm,lineObj,null,pos),dir="ltr"==dir==("after"==side)?"left":"right";return coords("after"==side?pos.begin:pos.end-(/\s/.test(lineObj.text.charAt(pos.end-1))?2:1),dir)[dir]}var order=getOrder(lineObj,doc.direction);return((order,from,to,f)=>{if(!order)return f(from,to,"ltr",0);for(var found=!1,i=0;i<order.length;++i){var part=order[i];(part.from<to&&part.to>from||from==to&&part.to==from)&&(f(Math.max(part.from,from),Math.min(part.to,to),1==part.level?"rtl":"ltr",i),found=!0)}found||f(from,to,"ltr")})(order,fromArg||0,null==toArg?lineLen:toArg,function(from,to,dir,i){var left,topLeft,topRight,botLeft,right,ltr="ltr"==dir,fromPos=coords(from,ltr?"left":"right"),toPos=coords(to-1,ltr?"right":"left"),openStart=null==fromArg&&0==from,openEnd=null==toArg&&to==lineLen,first=0==i,i=!order||i==order.length-1;toPos.top-fromPos.top<=3?(left=(docLTR?openStart:openEnd)&&first?leftSide:(ltr?fromPos:toPos).left,right=(docLTR?openEnd:openStart)&&i?rightSide:(ltr?toPos:fromPos).right,add(left,fromPos.top,right-left,fromPos.bottom)):(right=ltr?(topLeft=docLTR&&openStart&&first?leftSide:fromPos.left,topRight=docLTR?rightSide:wrapX(from,dir,"before"),botLeft=docLTR?leftSide:wrapX(to,dir,"after"),docLTR&&openEnd&&i?rightSide:toPos.right):(topLeft=docLTR?wrapX(from,dir,"before"):leftSide,topRight=!docLTR&&openStart&&first?rightSide:fromPos.right,botLeft=!docLTR&&openEnd&&i?leftSide:toPos.left,docLTR?wrapX(to,dir,"after"):rightSide),add(topLeft,fromPos.top,topRight-topLeft,fromPos.bottom),fromPos.bottom<toPos.top&&add(leftSide,fromPos.bottom,null,toPos.top),add(botLeft,toPos.top,right-botLeft,toPos.bottom)),(!start||cmpCoords(fromPos,start)<0)&&(start=fromPos),cmpCoords(toPos,start)<0&&(start=toPos),(!end||cmpCoords(fromPos,end)<0)&&(end=fromPos),cmpCoords(toPos,end)<0&&(end=toPos)}),{start:start,end:end}}display=range.from(),padding=range.to(),display.line==padding.line?drawForLine(display.line,display.ch,padding.ch):(range=getLine(doc,display.line),toLine=getLine(doc,padding.line),toLine=visualLine(range)==visualLine(toLine),display=drawForLine(display.line,display.ch,toLine?range.text.length+1:null).end,range=drawForLine(padding.line,toLine?0:null,padding.ch).start,toLine&&(display.top<range.top-2?(add(display.right,display.top,null,display.bottom),add(leftSide,range.top,range.left,range.bottom)):add(display.right,display.top,range.left-display.right,display.bottom)),display.bottom<range.top&&add(leftSide,display.bottom,null,range.top)),output.appendChild(fragment)})(cm,range,selFragment);return result}function drawSelectionCursor(cm,head,output){var head=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine),cursor=output.appendChild(elt("div"," ","CodeMirror-cursor"));cursor.style.left=head.left+"px",cursor.style.top=head.top+"px",cursor.style.height=Math.max(0,head.bottom-head.top)*cm.options.cursorHeight+"px",head.other&&((cursor=output.appendChild(elt("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"))).style.display="",cursor.style.left=head.other.left+"px",cursor.style.top=head.other.top+"px",cursor.style.height=.85*(head.other.bottom-head.other.top)+"px")}function cmpCoords(a,b){return a.top-b.top||a.left-b.left}function restartBlink(cm){var display,on;cm.state.focused&&(display=cm.display,clearInterval(display.blinker),on=!0,display.cursorDiv.style.visibility="",0<cm.options.cursorBlinkRate?display.blinker=setInterval(function(){cm.hasFocus()||onBlur(cm),display.cursorDiv.style.visibility=(on=!on)?"":"hidden"},cm.options.cursorBlinkRate):cm.options.cursorBlinkRate<0&&(display.cursorDiv.style.visibility="hidden"))}function ensureFocus(cm){cm.hasFocus()||(cm.display.input.focus(),cm.state.focused)||onFocus(cm)}function delayBlurEvent(cm){cm.state.delayingBlurEvent=!0,setTimeout(function(){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1,cm.state.focused)&&onBlur(cm)},100)}function onFocus(cm,e){cm.state.delayingBlurEvent&&!cm.state.draggingText&&(cm.state.delayingBlurEvent=!1),"nocursor"!=cm.options.readOnly&&(cm.state.focused||(signal(cm,"focus",cm,e),cm.state.focused=!0,addClass(cm.display.wrapper,"CodeMirror-focused"),cm.curOp||cm.display.selForContextMenu==cm.doc.sel||(cm.display.input.reset(),webkit&&setTimeout(function(){return cm.display.input.reset(!0)},20)),cm.display.input.receivedFocus()),restartBlink(cm))}function onBlur(cm,e){cm.state.delayingBlurEvent||(cm.state.focused&&(signal(cm,"blur",cm,e),cm.state.focused=!1,rmClass(cm.display.wrapper,"CodeMirror-focused")),clearInterval(cm.display.blinker),setTimeout(function(){cm.state.focused||(cm.display.shift=!1)},150))}function updateHeightsInViewport(cm){for(var display=cm.display,prevBottom=display.lineDiv.offsetTop,i=0;i<display.view.length;i++){var cur=display.view[i],wrapping=cm.options.lineWrapping,height=void 0,width=0;if(!cur.hidden){ie&&ie_version<8?(height=(bot=cur.node.offsetTop+cur.node.offsetHeight)-prevBottom,prevBottom=bot):(height=(bot=cur.node.getBoundingClientRect()).bottom-bot.top,!wrapping&&cur.text.firstChild&&(width=cur.text.firstChild.getBoundingClientRect().right-bot.left-1));var bot,wrapping=cur.line.height-height;if((.005<wrapping||wrapping<-.005)&&(updateLineHeight(cur.line,height),updateWidgetHeight(cur.line),cur.rest))for(var j=0;j<cur.rest.length;j++)updateWidgetHeight(cur.rest[j]);width>cm.display.sizerWidth&&(wrapping=Math.ceil(width/charWidth(cm.display)))>cm.display.maxLineLength&&(cm.display.maxLineLength=wrapping,cm.display.maxLine=cur.line,cm.display.maxLineChanged=!0)}}}function updateWidgetHeight(line){if(line.widgets)for(var i=0;i<line.widgets.length;++i){var w=line.widgets[i],parent=w.node.parentNode;parent&&(w.height=parent.offsetHeight)}}function visibleLines(display,doc,viewport){var ensureFrom,top=viewport&&null!=viewport.top?Math.max(0,viewport.top):display.scroller.scrollTop,top=Math.floor(top-paddingTop(display)),bottom=viewport&&null!=viewport.bottom?viewport.bottom:top+display.wrapper.clientHeight,top=lineAtHeight(doc,top),bottom=lineAtHeight(doc,bottom);return viewport&&viewport.ensure&&(ensureFrom=viewport.ensure.from.line,viewport=viewport.ensure.to.line,ensureFrom<top?bottom=lineAtHeight(doc,heightAtLine(getLine(doc,top=ensureFrom))+display.wrapper.clientHeight):Math.min(viewport,doc.lastLine())>=bottom&&(top=lineAtHeight(doc,heightAtLine(getLine(doc,viewport))-display.wrapper.clientHeight),bottom=viewport)),{from:top,to:Math.max(bottom,top+1)}}function calculateScrollPos(cm,rect){var display=cm.display,snapMargin=textHeight(cm.display),screentop=(rect.top<0&&(rect.top=0),(cm.curOp&&null!=cm.curOp.scrollTop?cm.curOp:display.scroller).scrollTop),screen=displayHeight(cm),result={},docBottom=(screen<rect.bottom-rect.top&&(rect.bottom=rect.top+screen),cm.doc.height+paddingVert(display)),atBottom=docBottom-snapMargin<rect.bottom,atBottom=(rect.top<screentop?result.scrollTop=rect.top<snapMargin?0:rect.top:rect.bottom>screentop+screen&&(snapMargin=Math.min(rect.top,(atBottom?docBottom:rect.bottom)-screen))!=screentop&&(result.scrollTop=snapMargin),cm.options.fixedGutter?0:display.gutters.offsetWidth),docBottom=cm.curOp&&null!=cm.curOp.scrollLeft?cm.curOp.scrollLeft:display.scroller.scrollLeft-atBottom,screen=displayWidth(cm)-display.gutters.offsetWidth,screentop=screen<rect.right-rect.left;return screentop&&(rect.right=rect.left+screen),rect.left<10?result.scrollLeft=0:rect.left<docBottom?result.scrollLeft=Math.max(0,rect.left+atBottom-(screentop?0:10)):rect.right>screen+docBottom-3&&(result.scrollLeft=rect.right+(screentop?0:10)-screen),result}function addToScrollTop(cm,top){null!=top&&(resolveScrollToPos(cm),cm.curOp.scrollTop=(null==cm.curOp.scrollTop?cm.doc:cm.curOp).scrollTop+top)}function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor();cm.curOp.scrollToPos={from:cur,to:cur,margin:cm.options.cursorScrollMargin}}function scrollToCoords(cm,x,y){null==x&&null==y||resolveScrollToPos(cm),null!=x&&(cm.curOp.scrollLeft=x),null!=y&&(cm.curOp.scrollTop=y)}function resolveScrollToPos(cm){var range=cm.curOp.scrollToPos;range&&(cm.curOp.scrollToPos=null,scrollToCoordsRange(cm,estimateCoords(cm,range.from),estimateCoords(cm,range.to),range.margin))}function scrollToCoordsRange(cm,from,to,margin){from=calculateScrollPos(cm,{left:Math.min(from.left,to.left),top:Math.min(from.top,to.top)-margin,right:Math.max(from.right,to.right),bottom:Math.max(from.bottom,to.bottom)+margin});scrollToCoords(cm,from.scrollLeft,from.scrollTop)}function updateScrollTop(cm,val){Math.abs(cm.doc.scrollTop-val)<2||(gecko||updateDisplaySimple(cm,{top:val}),setScrollTop(cm,val,!0),gecko&&updateDisplaySimple(cm),startWorker(cm,100))}function setScrollTop(cm,val,forceScroll){val=Math.max(0,Math.min(cm.display.scroller.scrollHeight-cm.display.scroller.clientHeight,val)),cm.display.scroller.scrollTop==val&&!forceScroll||(cm.doc.scrollTop=val,cm.display.scrollbars.setScrollTop(val),cm.display.scroller.scrollTop==val)||(cm.display.scroller.scrollTop=val)}function setScrollLeft(cm,val,isScroller,forceScroll){val=Math.max(0,Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth)),(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)&&!forceScroll||(cm.doc.scrollLeft=val,alignHorizontally(cm),cm.display.scroller.scrollLeft!=val&&(cm.display.scroller.scrollLeft=val),cm.display.scrollbars.setScrollLeft(val))}function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth,docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}function NativeScrollbars(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");vert.tabIndex=horiz.tabIndex=-1,place(vert),place(horiz),on(vert,"scroll",function(){vert.clientHeight&&scroll(vert.scrollTop,"vertical")}),on(horiz,"scroll",function(){horiz.clientWidth&&scroll(horiz.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,ie&&ie_version<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function NullScrollbars(){}NativeScrollbars.prototype.update=function(measure){var totalHeight,needsH=measure.scrollWidth>measure.clientWidth+1,needsV=measure.clientHeight+1<measure.scrollHeight,sWidth=measure.nativeBarWidth;return needsV?(this.vert.style.display="block",this.vert.style.bottom=needsH?sWidth+"px":"0",totalHeight=measure.viewHeight-(needsH?sWidth:0),this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"):(this.vert.style.display="",this.vert.firstChild.style.height="0"),needsH?(this.horiz.style.display="block",this.horiz.style.right=needsV?sWidth+"px":"0",this.horiz.style.left=measure.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,measure.scrollWidth-measure.clientWidth+(measure.viewWidth-measure.barLeft-(needsV?sWidth:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0"),!this.checkedZeroWidth&&0<measure.clientHeight&&(0==sWidth&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:needsV?sWidth:0,bottom:needsH?sWidth:0}},NativeScrollbars.prototype.setScrollLeft=function(pos){this.horiz.scrollLeft!=pos&&(this.horiz.scrollLeft=pos),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},NativeScrollbars.prototype.setScrollTop=function(pos){this.vert.scrollTop!=pos&&(this.vert.scrollTop=pos),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},NativeScrollbars.prototype.zeroWidthHack=function(){this.horiz.style.height=this.vert.style.width=mac&&!mac_geMountainLion?"12px":"18px",this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new Delayed,this.disableVert=new Delayed},NativeScrollbars.prototype.enableZeroWidthBar=function(bar,delay,type){bar.style.pointerEvents="auto",delay.set(1e3,function maybeDisable(){var box=bar.getBoundingClientRect();("vert"==type?document.elementFromPoint(box.right-1,(box.top+box.bottom)/2):document.elementFromPoint((box.right+box.left)/2,box.bottom-1))!=bar?bar.style.pointerEvents="none":delay.set(1e3,maybeDisable)})},NativeScrollbars.prototype.clear=function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz),parent.removeChild(this.vert)};function updateScrollbars(cm,measure){measure=measure||measureForScrollbars(cm);var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++)startWidth!=cm.display.barWidth&&cm.options.lineWrapping&&updateHeightsInViewport(cm),updateScrollbarsInner(cm,measureForScrollbars(cm)),startWidth=cm.display.barWidth,startHeight=cm.display.barHeight}function updateScrollbarsInner(cm,measure){var d=cm.display,sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px",d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px",d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent",sizes.right&&sizes.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=sizes.bottom+"px",d.scrollbarFiller.style.width=sizes.right+"px"):d.scrollbarFiller.style.display="",sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter?(d.gutterFiller.style.display="block",d.gutterFiller.style.height=sizes.bottom+"px",d.gutterFiller.style.width=measure.gutterWidth+"px"):d.gutterFiller.style.display=""}NullScrollbars.prototype.update=function(){return{bottom:0,right:0}},NullScrollbars.prototype.setScrollLeft=function(){},NullScrollbars.prototype.setScrollTop=function(){},NullScrollbars.prototype.clear=function(){};var scrollbarModel={native:NativeScrollbars,null:NullScrollbars};function initScrollbars(cm){cm.display.scrollbars&&(cm.display.scrollbars.clear(),cm.display.scrollbars.addClass)&&rmClass(cm.display.wrapper,cm.display.scrollbars.addClass),cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller),on(node,"mousedown",function(){cm.state.focused&&setTimeout(function(){return cm.display.input.focus()},0)}),node.setAttribute("cm-not-content","true")},function(pos,axis){("horizontal"==axis?setScrollLeft:updateScrollTop)(cm,pos)},cm),cm.display.scrollbars.addClass&&addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}var nextOpId=0;function startOperation(cm){cm.curOp={cm:cm,viewChanged:!1,startHeight:cm.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++nextOpId},cm=cm.curOp,operationGroup?operationGroup.ops.push(cm):cm.ownsGroup=operationGroup={ops:[cm],delayedCallbacks:[]}}function endOperation(cm){cm=cm.curOp;cm&&finishOperation(cm,function(group){for(var i=0;i<group.ops.length;i++)group.ops[i].cm.curOp=null;(group=>{for(var ops=group.ops,i=0;i<ops.length;i++)(op=>{var cm=op.cm,display=cm.display;(cm=>{var display=cm.display;!display.scrollbarsClipped&&display.scroller.offsetWidth&&(display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth,display.heightForcer.style.height=scrollGap(cm)+"px",display.sizer.style.marginBottom=-display.nativeBarWidth+"px",display.sizer.style.borderRightWidth=scrollGap(cm)+"px",display.scrollbarsClipped=!0)})(cm),op.updateMaxLine&&findMaxLine(cm),op.mustUpdate=op.viewChanged||op.forceUpdate||null!=op.scrollTop||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping,op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)})(ops[i]);for(var i$1=0;i$1<ops.length;i$1++)(op=>{op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)})(ops[i$1]);for(var i$2=0;i$2<ops.length;i$2++)(op=>{var cm=op.cm,display=cm.display;op.updatedDisplay&&updateHeightsInViewport(cm),op.barMeasure=measureForScrollbars(cm),display.maxLineChanged&&!cm.options.lineWrapping&&(op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3,cm.display.sizerWidth=op.adjustWidthTo,op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth),op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))),(op.updatedDisplay||op.selectionChanged)&&(op.preparedSelection=display.input.prepareSelection())})(ops[i$2]);for(var i$3=0;i$3<ops.length;i$3++){op=void 0;cm=void 0;takeFocus=void 0;var op=ops[i$3];var cm=op.cm,takeFocus=(null!=op.adjustWidthTo&&(cm.display.sizer.style.minWidth=op.adjustWidthTo+"px",op.maxScrollLeft<cm.doc.scrollLeft&&setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),!0),cm.display.maxLineChanged=!1),op.focus&&op.focus==activeElt());op.preparedSelection&&cm.display.input.showSelection(op.preparedSelection,takeFocus),!op.updatedDisplay&&op.startHeight==cm.doc.height||updateScrollbars(cm,op.barMeasure),op.updatedDisplay&&setDocumentHeight(cm,op.barMeasure),op.selectionChanged&&restartBlink(cm),cm.state.focused&&op.updateInput&&cm.display.input.reset(op.typing),takeFocus&&ensureFocus(op.cm)}for(var i$4=0;i$4<ops.length;i$4++)(op=>{var rect,cm=op.cm,display=cm.display,doc=cm.doc,hidden=(op.updatedDisplay&&postUpdateDisplay(cm,op.update),null==display.wheelStartX||null==op.scrollTop&&null==op.scrollLeft&&!op.scrollToPos||(display.wheelStartX=display.wheelStartY=null),null!=op.scrollTop&&setScrollTop(cm,op.scrollTop,op.forceScroll),null!=op.scrollLeft&&setScrollLeft(cm,op.scrollLeft,!0,!0),op.scrollToPos&&(rect=((cm,pos,end,margin)=>{null==margin&&(margin=0),cm.options.lineWrapping||pos!=end||(end="before"==(pos=pos.ch?Pos(pos.line,"before"==pos.sticky?pos.ch-1:pos.ch,"after"):pos).sticky?Pos(pos.line,pos.ch+1,"before"):pos);for(var limit=0;limit<5;limit++){var rect,changed=!1,coords=cursorCoords(cm,pos),endCoords=end&&end!=pos?cursorCoords(cm,end):coords,coords=calculateScrollPos(cm,rect={left:Math.min(coords.left,endCoords.left),top:Math.min(coords.top,endCoords.top)-margin,right:Math.max(coords.left,endCoords.left),bottom:Math.max(coords.bottom,endCoords.bottom)+margin}),endCoords=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(null!=coords.scrollTop&&(updateScrollTop(cm,coords.scrollTop),1<Math.abs(cm.doc.scrollTop-endCoords))&&(changed=!0),!(changed=null!=coords.scrollLeft&&(setScrollLeft(cm,coords.scrollLeft),1<Math.abs(cm.doc.scrollLeft-startLeft))?!0:changed))break}return rect})(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin),((cm,rect)=>{var display,doScroll,box;signalDOMEvent(cm,"scrollCursorIntoView")||(box=(display=cm.display).sizer.getBoundingClientRect(),doScroll=null,rect.top+box.top<0?doScroll=!0:rect.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)&&(doScroll=!1),null==doScroll)||phantom||(box=elt("div","",null,"position: absolute;\n top: "+(rect.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(rect.bottom-rect.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+rect.left+"px; width: "+Math.max(2,rect.right-rect.left)+"px;"),cm.display.lineSpace.appendChild(box),box.scrollIntoView(doScroll),cm.display.lineSpace.removeChild(box))})(cm,rect)),op.maybeHiddenMarkers),unhidden=op.maybeUnhiddenMarkers;if(hidden)for(var i=0;i<hidden.length;++i)hidden[i].lines.length||signal(hidden[i],"hide");if(unhidden)for(var i$1=0;i$1<unhidden.length;++i$1)unhidden[i$1].lines.length&&signal(unhidden[i$1],"unhide");display.wrapper.offsetHeight&&(doc.scrollTop=cm.display.scroller.scrollTop),op.changeObjs&&signal(cm,"changes",cm,op.changeObjs),op.update&&op.update.finish()})(ops[i$4])})(group)})}function runInOp(cm,f){if(cm.curOp)return f();startOperation(cm);try{return f()}finally{endOperation(cm)}}function operation(cm,f){return function(){if(cm.curOp)return f.apply(cm,arguments);startOperation(cm);try{return f.apply(cm,arguments)}finally{endOperation(cm)}}}function methodOp(f){return function(){if(this.curOp)return f.apply(this,arguments);startOperation(this);try{return f.apply(this,arguments)}finally{endOperation(this)}}}function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp)return f.apply(this,arguments);startOperation(cm);try{return f.apply(this,arguments)}finally{endOperation(cm)}}}function startWorker(cm,time){cm.doc.highlightFrontier<cm.display.viewTo&&cm.state.highlight.set(time,bind(highlightWorker,cm))}function highlightWorker(cm){var end,context,changedLines,doc=cm.doc;doc.highlightFrontier>=cm.display.viewTo||(end=+new Date+cm.options.workTime,context=getContextBefore(cm,doc.highlightFrontier),changedLines=[],doc.iter(context.line,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(context.line>=cm.display.viewFrom){for(var oldStyles=line.styles,resetState=line.text.length>cm.options.maxHighlightLength?copyState(doc.mode,context.state):null,highlighted=highlightLine(cm,line,context,!0),resetState=(resetState&&(context.state=resetState),line.styles=highlighted.styles,line.styleClasses),highlighted=highlighted.classes,ischange=(highlighted?line.styleClasses=highlighted:resetState&&(line.styleClasses=null),!oldStyles||oldStyles.length!=line.styles.length||resetState!=highlighted&&(!resetState||!highlighted||resetState.bgClass!=highlighted.bgClass||resetState.textClass!=highlighted.textClass)),i=0;!ischange&&i<oldStyles.length;++i)ischange=oldStyles[i]!=line.styles[i];ischange&&changedLines.push(context.line),line.stateAfter=context.save()}else line.text.length<=cm.options.maxHighlightLength&&processLine(cm,line.text,context),line.stateAfter=context.line%5==0?context.save():null;if(context.nextLine(),+new Date>end)return startWorker(cm,cm.options.workDelay),!0}),doc.highlightFrontier=context.line,doc.modeFrontier=Math.max(doc.modeFrontier,context.line),changedLines.length&&runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)regLineChange(cm,changedLines[i],"text")}))}var DisplayUpdate=function(cm,viewport,force){var display=cm.display;this.viewport=viewport,this.visible=visibleLines(display,cm.doc,viewport),this.editorIsHidden=!display.wrapper.offsetWidth,this.wrapperHeight=display.wrapper.clientHeight,this.wrapperWidth=display.wrapper.clientWidth,this.oldDisplayWidth=displayWidth(cm),this.force=force,this.dims=getDimensions(cm),this.events=[]};function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden)return resetView(cm),!1;if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&0==countDirtyView(cm))return!1;maybeUpdateLineNumberWidth(cm)&&(resetView(cm),update.dims=getDimensions(cm));var end=doc.first+doc.size,from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first),to=Math.min(end,update.visible.to+cm.options.viewportMargin),doc=(display.viewFrom<from&&from-display.viewFrom<20&&(from=Math.max(doc.first,display.viewFrom)),display.viewTo>to&&display.viewTo-to<20&&(to=Math.min(end,display.viewTo)),sawCollapsedSpans&&(from=visualLineNo(cm.doc,from),to=visualLineEndNo(cm.doc,to)),from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth),end=(((cm,from,to)=>{var display=cm.display;0==display.view.length||from>=display.viewTo||to<=display.viewFrom?(display.view=buildViewArray(cm,from,to),display.viewFrom=from):(display.viewFrom>from?display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view):display.viewFrom<from&&(display.view=display.view.slice(findViewIndex(cm,from))),display.viewFrom=from,display.viewTo<to?display.view=display.view.concat(buildViewArray(cm,display.viewTo,to)):display.viewTo>to&&(display.view=display.view.slice(0,findViewIndex(cm,to)))),display.viewTo=to})(cm,from,to),display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom)),cm.display.mover.style.top=display.viewOffset+"px",countDirtyView(cm));return!(!doc&&0==end&&!update.force&&display.renderedView==display.view&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)||(from=(cm=>{var active,sel;return!cm.hasFocus()&&(active=activeElt())&&contains(cm.display.lineDiv,active)?(active={activeElt:active},window.getSelection&&(sel=window.getSelection()).anchorNode&&sel.extend&&contains(cm.display.lineDiv,sel.anchorNode)&&(active.anchorNode=sel.anchorNode,active.anchorOffset=sel.anchorOffset,active.focusNode=sel.focusNode,active.focusOffset=sel.focusOffset),active):null})(cm),4<end&&(display.lineDiv.style.display="none"),((cm,updateNumbersFrom,dims)=>{var display=cm.display,lineNumbers=cm.options.lineNumbers,container=display.lineDiv,cur=container.firstChild;function rm(node){var next=node.nextSibling;return webkit&&mac&&cm.display.currentWheelTarget==node?node.style.display="none":node.parentNode.removeChild(node),next}for(var view=display.view,lineN=display.viewFrom,i=0;i<view.length;i++){var lineView=view[i];if(!lineView.hidden)if(lineView.node&&lineView.node.parentNode==container){for(;cur!=lineView.node;)cur=rm(cur);var updateNumber=lineNumbers&&null!=updateNumbersFrom&&updateNumbersFrom<=lineN&&lineView.lineNumber;lineView.changes&&(-1<indexOf(lineView.changes,"gutter")&&(updateNumber=!1),updateLineForChanges(cm,lineView,lineN,dims)),updateNumber&&(removeChildren(lineView.lineNumber),lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))),cur=lineView.node.nextSibling}else{updateNumber=((cm,lineView,lineN,dims)=>{var built=getLineContent(cm,lineView);return lineView.text=lineView.node=built.pre,built.bgClass&&(lineView.bgClass=built.bgClass),built.textClass&&(lineView.textClass=built.textClass),updateLineClasses(cm,lineView),updateLineGutter(cm,lineView,lineN,dims),insertLineWidgets(cm,lineView,dims),lineView.node})(cm,lineView,lineN,dims);container.insertBefore(updateNumber,cur)}lineN+=lineView.size}for(;cur;)cur=rm(cur)})(cm,display.updateLineNumbers,update.dims),4<end&&(display.lineDiv.style.display=""),display.renderedView=display.view,(to=from)&&to.activeElt&&to.activeElt!=activeElt()&&(to.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(to.activeElt.nodeName))&&to.anchorNode&&contains(document.body,to.anchorNode)&&contains(document.body,to.focusNode)&&(end=window.getSelection(),(from=document.createRange()).setEnd(to.anchorNode,to.anchorOffset),from.collapse(!1),end.removeAllRanges(),end.addRange(from),end.extend(to.focusNode,to.focusOffset)),removeChildren(display.cursorDiv),removeChildren(display.selectionDiv),display.gutters.style.height=display.sizer.style.minHeight=0,doc&&(display.lastWrapHeight=update.wrapperHeight,display.lastWrapWidth=update.wrapperWidth,startWorker(cm,400)),display.updateLineNumbers=null))}function postUpdateDisplay(cm,update){for(var viewport=update.viewport,first=!0;;first=!1){if(first&&cm.options.lineWrapping&&update.oldDisplayWidth!=displayWidth(cm))first&&(update.visible=visibleLines(cm.display,cm.doc,viewport));else if(viewport&&null!=viewport.top&&(viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)}),update.visible=visibleLines(cm.display,cm.doc,viewport),update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)break;if(!updateDisplayIfNeeded(cm,update))break;updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),update.force=!1}update.signal(cm,"update",cm),cm.display.viewFrom==cm.display.reportedViewFrom&&cm.display.viewTo==cm.display.reportedViewTo||(update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo),cm.display.reportedViewFrom=cm.display.viewFrom,cm.display.reportedViewTo=cm.display.viewTo)}function updateDisplaySimple(cm,viewport){var barMeasure,viewport=new DisplayUpdate(cm,viewport);updateDisplayIfNeeded(cm,viewport)&&(updateHeightsInViewport(cm),postUpdateDisplay(cm,viewport),barMeasure=measureForScrollbars(cm),updateSelection(cm),updateScrollbars(cm,barMeasure),setDocumentHeight(cm,barMeasure),viewport.finish())}function updateGutterSpace(display){var width=display.gutters.offsetWidth;display.sizer.style.marginLeft=width+"px"}function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px",cm.display.heightForcer.style.top=measure.docHeight+"px",cm.display.gutters.style.height=measure.docHeight+cm.display.barHeight+scrollGap(cm)+"px"}function alignHorizontally(cm){var display=cm.display,view=display.view;if(display.alignWidgets||display.gutters.firstChild&&cm.options.fixedGutter){for(var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft,gutterW=display.gutters.offsetWidth,left=comp+"px",i=0;i<view.length;i++)if(!view[i].hidden){cm.options.fixedGutter&&(view[i].gutter&&(view[i].gutter.style.left=left),view[i].gutterBackground)&&(view[i].gutterBackground.style.left=left);var align=view[i].alignable;if(align)for(var j=0;j<align.length;j++)align[j].style.left=left}cm.options.fixedGutter&&(display.gutters.style.left=comp+gutterW+"px")}}function maybeUpdateLineNumberWidth(cm){var doc,display,innerW,test;return cm.options.lineNumbers&&(doc=lineNumberFor(cm.options,(doc=cm.doc).first+doc.size-1)).length!=(display=cm.display).lineNumChars?(innerW=(test=display.measure.appendChild(elt("div",[elt("div",doc)],"CodeMirror-linenumber CodeMirror-gutter-elt"))).firstChild.offsetWidth,test=test.offsetWidth-innerW,display.lineGutter.style.width="",display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-test)+1,display.lineNumWidth=display.lineNumInnerWidth+test,display.lineNumChars=display.lineNumInnerWidth?doc.length:-1,display.lineGutter.style.width=display.lineNumWidth+"px",updateGutterSpace(cm.display),1):void 0}function getGutters(gutters,lineNumbers){for(var result=[],sawLineNumbers=!1,i=0;i<gutters.length;i++){var name=gutters[i],style=null;if("string"!=typeof name&&(style=name.style,name=name.className),"CodeMirror-linenumbers"==name){if(!lineNumbers)continue;sawLineNumbers=!0}result.push({className:name,style:style})}return lineNumbers&&!sawLineNumbers&&result.push({className:"CodeMirror-linenumbers",style:null}),result}function renderGutters(display){var gutters=display.gutters,specs=display.gutterSpecs;removeChildren(gutters),display.lineGutter=null;for(var i=0;i<specs.length;++i){var ref=specs[i],className=ref.className,ref=ref.style,gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+className));ref&&(gElt.style.cssText=ref),"CodeMirror-linenumbers"==className&&((display.lineGutter=gElt).style.width=(display.lineNumWidth||1)+"px")}gutters.style.display=specs.length?"":"none",updateGutterSpace(display)}function updateGutters(cm){renderGutters(cm.display),regChange(cm),alignHorizontally(cm)}function Display(place,doc,input,options){var d=this,lines=(this.input=input,d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler"),d.scrollbarFiller.setAttribute("cm-not-content","true"),d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler"),d.gutterFiller.setAttribute("cm-not-content","true"),d.lineDiv=eltP("div",null,"CodeMirror-code"),d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1"),d.cursorDiv=elt("div",null,"CodeMirror-cursors"),d.measure=elt("div",null,"CodeMirror-measure"),d.lineMeasure=elt("div",null,"CodeMirror-measure"),d.lineSpace=eltP("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none"),eltP("div",[d.lineSpace],"CodeMirror-lines"));d.mover=elt("div",[lines],null,"position: relative"),d.sizer=elt("div",[d.mover],"CodeMirror-sizer"),d.sizerWidth=null,d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;"),d.gutters=elt("div",null,"CodeMirror-gutters"),d.lineGutter=null,d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll"),d.scroller.setAttribute("tabIndex","-1"),d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror"),ie&&ie_version<8&&(d.gutters.style.zIndex=-1,d.scroller.style.paddingRight=0),webkit||gecko&&mobile||(d.scroller.draggable=!0),place&&(place.appendChild?place.appendChild(d.wrapper):place(d.wrapper)),d.viewFrom=d.viewTo=doc.first,d.reportedViewFrom=d.reportedViewTo=doc.first,d.view=[],d.renderedView=null,d.externalMeasured=null,d.viewOffset=0,d.lastWrapHeight=d.lastWrapWidth=0,d.updateLineNumbers=null,d.nativeBarWidth=d.barHeight=d.barWidth=0,d.scrollbarsClipped=!1,d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null,d.alignWidgets=!1,d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.maxLine=null,d.maxLineLength=0,d.maxLineChanged=!1,d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null,d.shift=!1,d.selForContextMenu=null,d.activeTouch=null,d.gutterSpecs=getGutters(options.gutters,options.lineNumbers),renderGutters(d),input.init(d)}DisplayUpdate.prototype.signal=function(emitter,type){hasHandler(emitter,type)&&this.events.push(arguments)},DisplayUpdate.prototype.finish=function(){for(var i=0;i<this.events.length;i++)signal.apply(null,this.events[i])};var wheelSamples=0,wheelPixelsPerUnit=null;function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;return null==dx&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(dx=e.detail),null==dy&&e.detail&&e.axis==e.VERTICAL_AXIS?dy=e.detail:null==dy&&(dy=e.wheelDelta),{x:dx,y:dy}}function wheelEventPixels(e){e=wheelEventDelta(e);return e.x*=wheelPixelsPerUnit,e.y*=wheelPixelsPerUnit,e}function onScrollWheel(cm,e){var top,bot,delta=wheelEventDelta(e),dx=delta.x,delta=delta.y,display=cm.display,scroll=display.scroller,canScrollX=scroll.scrollWidth>scroll.clientWidth,canScrollY=scroll.clientHeight<scroll.scrollHeight;if(dx&&canScrollX||delta&&canScrollY){if(delta&&mac&&webkit)outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode)for(var i=0;i<view.length;i++)if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}!dx||gecko||presto||null==wheelPixelsPerUnit?(delta&&null!=wheelPixelsPerUnit&&(canScrollX=delta*wheelPixelsPerUnit,bot=(top=cm.doc.scrollTop)+display.wrapper.clientHeight,canScrollX<0?top=Math.max(0,top+canScrollX-50):bot=Math.min(cm.doc.height,bot+canScrollX+50),updateDisplaySimple(cm,{top:top,bottom:bot})),wheelSamples<20&&(null==display.wheelStartX?(display.wheelStartX=scroll.scrollLeft,display.wheelStartY=scroll.scrollTop,display.wheelDX=dx,display.wheelDY=delta,setTimeout(function(){var movedX,movedY;null!=display.wheelStartX&&(movedX=scroll.scrollLeft-display.wheelStartX,movedY=(movedY=scroll.scrollTop-display.wheelStartY)&&display.wheelDY&&movedY/display.wheelDY||movedX&&display.wheelDX&&movedX/display.wheelDX,display.wheelStartX=display.wheelStartY=null,movedY)&&(wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+movedY)/(wheelSamples+1),++wheelSamples)},200)):(display.wheelDX+=dx,display.wheelDY+=delta))):(delta&&canScrollY&&updateScrollTop(cm,Math.max(0,scroll.scrollTop+delta*wheelPixelsPerUnit)),setScrollLeft(cm,Math.max(0,scroll.scrollLeft+dx*wheelPixelsPerUnit)),delta&&!canScrollY||e_preventDefault(e),display.wheelStartX=null)}}ie?wheelPixelsPerUnit=-.53:gecko?wheelPixelsPerUnit=15:chrome?wheelPixelsPerUnit=-.7:safari&&(wheelPixelsPerUnit=-1/3);var Selection=function(ranges,primIndex){this.ranges=ranges,this.primIndex=primIndex},Range=(Selection.prototype.primary=function(){return this.ranges[this.primIndex]},Selection.prototype.equals=function(other){if(other!=this){if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length)return!1;for(var i=0;i<this.ranges.length;i++){var here=this.ranges[i],there=other.ranges[i];if(!equalCursorPos(here.anchor,there.anchor)||!equalCursorPos(here.head,there.head))return!1}}return!0},Selection.prototype.deepCopy=function(){for(var out=[],i=0;i<this.ranges.length;i++)out[i]=new Range(copyPos(this.ranges[i].anchor),copyPos(this.ranges[i].head));return new Selection(out,this.primIndex)},Selection.prototype.somethingSelected=function(){for(var i=0;i<this.ranges.length;i++)if(!this.ranges[i].empty())return!0;return!1},Selection.prototype.contains=function(pos,end){end=end||pos;for(var i=0;i<this.ranges.length;i++){var range=this.ranges[i];if(0<=cmp(end,range.from())&&cmp(pos,range.to())<=0)return i}return-1},function(anchor,head){this.anchor=anchor,this.head=head});function normalizeSelection(cm,ranges,primIndex){var mayTouch=cm&&cm.options.selectionsMayTouch,cm=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from())}),primIndex=indexOf(ranges,cm);for(var i=1;i<ranges.length;i++){var to,cur=ranges[i],prev=ranges[i-1],diff=cmp(prev.to(),cur.from());(mayTouch&&!cur.empty()?0<diff:0<=diff)&&(diff=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()),cur=prev.empty()?cur.from()==cur.head:prev.from()==prev.head,i<=primIndex&&--primIndex,ranges.splice(--i,2,new Range(cur?to:diff,cur?diff:to)))}return new Selection(ranges,primIndex)}function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}function changeEnd(change){return change.text?Pos(change.from.line+change.text.length-1,lst(change.text).length+(1==change.text.length?change.from.ch:0)):change.to}function adjustForChange(pos,change){var line,ch;return cmp(pos,change.from)<0?pos:cmp(pos,change.to)<=0?changeEnd(change):(line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch,pos.line==change.to.line&&(ch+=changeEnd(change).ch-change.to.ch),Pos(line,ch))}function computeSelAfterChange(doc,change){for(var out=[],i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))}return normalizeSelection(doc.cm,out,doc.sel.primIndex)}function offsetPos(pos,old,nw){return pos.line==old.line?Pos(nw.line,pos.ch-old.ch+nw.ch):Pos(nw.line+(pos.line-old.line),pos.ch)}function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption),resetModeState(cm)}function resetModeState(cm){cm.doc.iter(function(line){line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null)}),cm.doc.modeFrontier=cm.doc.highlightFrontier=cm.doc.first,startWorker(cm,100),cm.state.modeGen++,cm.curOp&®Change(cm)}function isWholeLineUpdate(doc,change){return 0==change.from.ch&&0==change.to.ch&&""==lst(change.text)&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}function updateDoc(doc,change,markedSpans,estimateHeight){function spansFor(n){return markedSpans?markedSpans[n]:null}function update(line,text,spans){((line,text,markedSpans,estimateHeight)=>{line.text=text,line.stateAfter&&(line.stateAfter=null),line.styles&&(line.styles=null),null!=line.order&&(line.order=null),detachMarkedSpans(line),attachMarkedSpans(line,markedSpans),(text=estimateHeight?estimateHeight(line):1)!=line.height&&updateLineHeight(line,text)})(line,text,spans,estimateHeight),signalLater(line,"change",line,change)}function linesFor(start,end){for(var result=[],i=start;i<end;++i)result.push(new Line(text[i],spansFor(i),estimateHeight));return result}var added,from=change.from,to=change.to,text=change.text,firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line),lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;change.full?(doc.insert(0,linesFor(0,text.length)),doc.remove(text.length,doc.size-text.length)):isWholeLineUpdate(doc,change)?(added=linesFor(0,text.length-1),update(lastLine,lastLine.text,lastSpans),nlines&&doc.remove(from.line,nlines),added.length&&doc.insert(from.line,added)):firstLine==lastLine?1==text.length?update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans):((added=linesFor(1,text.length-1)).push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight)),update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),doc.insert(from.line+1,added)):1==text.length?(update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0)),doc.remove(from.line+1,nlines)):(update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0)),update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans),added=linesFor(1,text.length-1),1<nlines&&doc.remove(from.line+1,nlines-1),doc.insert(from.line+1,added)),signalLater(doc,"change",doc,change)}function linkedDocs(doc,f,sharedHistOnly){!function propagate(doc,skip,sharedHist){if(doc.linked)for(var i=0;i<doc.linked.length;++i){var shared,rel=doc.linked[i];rel.doc!=skip&&(shared=sharedHist&&rel.sharedHist,!sharedHistOnly||shared)&&(f(rel.doc,shared),propagate(rel.doc,doc,shared))}}(doc,null,!0)}function attachDoc(cm,doc){if(doc.cm)throw new Error("This document is already in use.");cm.doc=doc,estimateLineHeights(doc.cm=cm),loadMode(cm),setDirectionClass(cm),cm.options.lineWrapping||findMaxLine(cm),cm.options.mode=doc.modeOption,regChange(cm)}function setDirectionClass(cm){("rtl"==cm.doc.direction?addClass:rmClass)(cm.display.lineDiv,"CodeMirror-rtl")}function History(startGen){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=startGen||1}function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1),linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1)},!0),histChange}function clearSelectionEvents(array){for(;array.length;){if(!lst(array).ranges)break;array.pop()}}function addChangeToHistory(doc,change,selAfter,opId){var cur,last,hist=doc.history,time=(hist.undone.length=0,+new Date);if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&("+"==change.origin.charAt(0)&&hist.lastModTime>time-(doc.cm?doc.cm.options.historyEventDelay:500)||"*"==change.origin.charAt(0)))&&(cur=((hist,force)=>force?(clearSelectionEvents(hist.done),lst(hist.done)):hist.done.length&&!lst(hist.done).ranges?lst(hist.done):1<hist.done.length&&!hist.done[hist.done.length-2].ranges?(hist.done.pop(),lst(hist.done)):void 0)(hist,hist.lastOp==opId)))last=lst(cur.changes),0==cmp(change.from,change.to)&&0==cmp(change.from,last.to)?last.to=changeEnd(change):cur.changes.push(historyChangeFromChange(doc,change));else{var before=lst(hist.done);for(before&&before.ranges||pushSelectionToHistory(doc.sel,hist.done),cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation},hist.done.push(cur);hist.done.length>hist.undoDepth;)hist.done.shift(),hist.done[0].ranges||hist.done.shift()}hist.done.push(selAfter),hist.generation=++hist.maxGeneration,hist.lastModTime=hist.lastSelTime=time,hist.lastOp=hist.lastSelOp=opId,hist.lastOrigin=hist.lastSelOrigin=change.origin,last||signal(doc,"historyAdded")}function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;opId==hist.lastSelOp||origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||((doc,origin,prev,sel)=>"*"==(origin=origin.charAt(0))||"+"==origin&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500))(doc,origin,lst(hist.done),sel))?hist.done[hist.done.length-1]=sel:pushSelectionToHistory(sel,hist.done),hist.lastSelTime=+new Date,hist.lastSelOrigin=origin,hist.lastSelOp=opId,options&&!1!==options.clearRedo&&clearSelectionEvents(hist.undone)}function pushSelectionToHistory(sel,dest){var top=lst(dest);top&&top.ranges&&top.equals(sel)||dest.push(sel)}function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){line.markedSpans&&((existing=existing||(change["spans_"+doc.id]={}))[n]=line.markedSpans),++n})}function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found)return null;for(var nw=[],i=0;i<change.text.length;++i)nw.push((spans=>{if(!spans)return null;for(var out,i=0;i<spans.length;++i)spans[i].marker.explicitlyCleared?out=out||spans.slice(0,i):out&&out.push(spans[i]);return out?out.length?out:null:spans})(found[i]));return nw}function mergeOldSpans(doc,change){var old=getOldSpans(doc,change),stretched=stretchSpansOverChange(doc,change);if(!old)return stretched;if(stretched)for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur)spans:for(var j=0;j<stretchCur.length;++j){for(var span=stretchCur[j],k=0;k<oldCur.length;++k)if(oldCur[k].marker==span.marker)continue spans;oldCur.push(span)}else stretchCur&&(old[i]=stretchCur)}return old}function copyHistoryArray(events,newGroup,instantiateSel){for(var copy=[],i=0;i<events.length;++i){var event=events[i];if(event.ranges)copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);else{var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var m,change=changes[j];if(newChanges.push({from:change.from,to:change.to,text:change.text}),newGroup)for(var prop in change)(m=prop.match(/^spans_(\d+)$/))&&-1<indexOf(newGroup,Number(m[1]))&&(lst(newChanges)[prop]=change[prop],delete change[prop])}}}return copy}function extendRange(range,head,other,extend){return extend?(extend=range.anchor,other&&((range=cmp(head,extend)<0)!=cmp(other,extend)<0?(extend=head,head=other):range!=cmp(head,other)<0&&(head=other)),new Range(extend,head)):new Range(other||head,head)}function extendSelection(doc,head,other,options,extend){null==extend&&(extend=doc.cm&&(doc.cm.display.shift||doc.extend)),setSelection(doc,new Selection([extendRange(doc.sel.primary(),head,other,extend)],0),options)}function extendSelections(doc,heads,options){for(var out=[],extend=doc.cm&&(doc.cm.display.shift||doc.extend),i=0;i<doc.sel.ranges.length;i++)out[i]=extendRange(doc.sel.ranges[i],heads[i],null,extend);setSelection(doc,normalizeSelection(doc.cm,out,doc.sel.primIndex),options)}function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range,setSelection(doc,normalizeSelection(doc.cm,ranges,doc.sel.primIndex),options)}function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)}function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);last&&last.ranges?setSelectionNoUndo(doc,done[done.length-1]=sel,options):setSelection(doc,sel,options)}function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options),addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)}function setSelectionNoUndo(doc,sel,options){(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))&&(sel=((doc,sel,options)=>(options={ranges:sel.ranges,update:function(ranges){this.ranges=[];for(var i=0;i<ranges.length;i++)this.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))},origin:options&&options.origin},signal(doc,"beforeSelectionChange",doc,options),doc.cm&&signal(doc.cm,"beforeSelectionChange",doc.cm,options),options.ranges!=sel.ranges?normalizeSelection(doc.cm,options.ranges,options.ranges.length-1):sel))(doc,sel,options));var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1);setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,!0)),options&&!1===options.scroll||!doc.cm||ensureCursorVisible(doc.cm)}function setSelectionInner(doc,sel){sel.equals(doc.sel)||(doc.sel=sel,doc.cm&&(doc.cm.curOp.updateInput=1,doc.cm.curOp.selectionChanged=!0,signalCursorActivity(doc.cm)),signalLater(doc,"cursorActivity",doc))}function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,!1))}function skipAtomicInSelection(doc,sel,bias,mayClear){for(var out,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i],old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i],newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear),old=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);!out&&newAnchor==range.anchor&&old==range.head||((out=out||sel.ranges.slice(0,i))[i]=new Range(newAnchor,old))}return out?normalizeSelection(doc.cm,out,sel.primIndex):sel}function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker,preventCursorLeft="selectLeft"in m?!m.selectLeft:m.inclusiveLeft,preventCursorRight="selectRight"in m?!m.selectRight:m.inclusiveRight;if((null==sp.from||(preventCursorLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(null==sp.to||(preventCursorRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear&&(signal(m,"beforeCursorEnter"),m.explicitlyCleared)){if(line.markedSpans){--i;continue}break}if(m.atomic){if(oldPos){var sp=m.find(dir<0?1:-1),diff=void 0;if((sp=(dir<0?preventCursorRight:preventCursorLeft)?movePos(doc,sp,-dir,sp&&sp.line==pos.line?line:null):sp)&&sp.line==pos.line&&(diff=cmp(sp,oldPos))&&(dir<0?diff<0:0<diff))return skipAtomicInner(doc,sp,pos,dir,mayClear)}diff=m.find(dir<0?-1:1);return(diff=(dir<0?preventCursorLeft:preventCursorRight)?movePos(doc,diff,dir,diff.line==pos.line?line:null):diff)?skipAtomicInner(doc,diff,pos,dir,mayClear):null}}}return pos}function skipAtomic(doc,pos,oldPos,bias,mayClear){bias=bias||1,mayClear=skipAtomicInner(doc,pos,oldPos,bias,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,bias,!0)||skipAtomicInner(doc,pos,oldPos,-bias,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,-bias,!0);return mayClear||(doc.cantEdit=!0,Pos(doc.first,0))}function movePos(doc,pos,dir,line){return dir<0&&0==pos.ch?pos.line>doc.first?clipPos(doc,Pos(pos.line-1)):null:0<dir&&pos.ch==(line||getLine(doc,pos.line)).text.length?pos.line<doc.first+doc.size-1?Pos(pos.line+1,0):null:new Pos(pos.line,pos.ch+dir)}function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)}function filterChange(doc,change,update){var obj={canceled:!1,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=!0}};return update&&(obj.update=function(from,to,text,origin){from&&(obj.from=clipPos(doc,from)),to&&(obj.to=clipPos(doc,to)),text&&(obj.text=text),void 0!==origin&&(obj.origin=origin)}),signal(doc,"beforeChange",doc,obj),doc.cm&&signal(doc.cm,"beforeChange",doc.cm,obj),obj.canceled?(doc.cm&&(doc.cm.curOp.updateInput=2),null):{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp)return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly);if(doc.cm.state.suppressEdits)return}if(!(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"))||(change=filterChange(doc,change,!0))){var split=sawReadOnlySpans&&!ignoreReadOnly&&((doc,from,to)=>{var markers=null;if(doc.iter(from.line,to.line+1,function(line){if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;!mark.readOnly||markers&&-1!=indexOf(markers,mark)||(markers=markers||[]).push(mark)}}),!markers)return null;for(var parts=[{from:from,to:to}],i=0;i<markers.length;++i)for(var mk=markers[i],m=mk.find(0),j=0;j<parts.length;++j){var newParts,dfrom,dto,p=parts[j];cmp(p.to,m.from)<0||0<cmp(p.from,m.to)||(newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to),(dfrom<0||!mk.inclusiveLeft&&!dfrom)&&newParts.push({from:p.from,to:m.from}),(0<dto||!mk.inclusiveRight&&!dto)&&newParts.push({from:m.to,to:p.to}),parts.splice.apply(parts,newParts),j+=newParts.length-3)}return parts})(doc,change.from,change.to);if(split)for(var i=split.length-1;0<=i;--i)makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text,origin:change.origin});else makeChangeInner(doc,change)}}function makeChangeInner(doc,change){var selAfter,rebased;1==change.text.length&&""==change.text[0]&&0==cmp(change.from,change.to)||(selAfter=computeSelAfterChange(doc,change),addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN),makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change)),rebased=[],linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))}))}function makeChangeFromHistory(doc,type,allowSelectionOnly){var suppress=doc.cm&&doc.cm.state.suppressEdits;if(!suppress||allowSelectionOnly){for(var event,hist=doc.history,selAfter=doc.sel,source="undo"==type?hist.done:hist.undone,dest="undo"==type?hist.undone:hist.done,i=0;i<source.length&&(event=source[i],allowSelectionOnly?!event.ranges||event.equals(doc.sel):event.ranges);i++);if(i!=source.length){for(hist.lastOrigin=hist.lastSelOrigin=null;;){if(!(event=source.pop()).ranges){if(suppress)return void source.push(event);break}if(pushSelectionToHistory(event,dest),allowSelectionOnly&&!event.equals(doc.sel))return void setSelection(doc,event,{clearRedo:!1});selAfter=event}for(var antiChanges=[],filter=(pushSelectionToHistory(selAfter,dest),dest.push({changes:antiChanges,generation:hist.generation}),hist.generation=event.generation||++hist.maxGeneration,hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")),i$1=event.changes.length-1;0<=i$1;--i$1){var returned=(i=>{var change=event.changes[i];if(change.origin=type,filter&&!filterChange(doc,change,!1))return source.length=0,{};antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source),rebased=(makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change)),!i&&doc.cm&&doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)}),[]);linkedDocs(doc,function(doc,sharedHist){sharedHist||-1!=indexOf(rebased,doc.history)||(rebaseHist(doc.history,change),rebased.push(doc.history)),makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})})(i$1);if(returned)return returned.v}}}}function shiftDoc(doc,distance){if(0!=distance&&(doc.first+=distance,doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch))}),doc.sel.primIndex),doc.cm)){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)regLineChange(doc.cm,l,"gutter")}}function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans);var shift;change.to.line<doc.first?shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line)):change.from.line>doc.lastLine()||(change.from.line<doc.first&&(shiftDoc(doc,shift=change.text.length-1-(doc.first-change.from.line)),change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}),shift=doc.lastLine(),(change=change.to.line>shift?{from:change.from,to:Pos(shift,getLine(doc,shift).text.length),text:[change.text[0]],origin:change.origin}:change).removed=getBetween(doc,change.from,change.to),selAfter=selAfter||computeSelAfterChange(doc,change),doc.cm?((cm,change,spans)=>{var doc=cm.doc,display=cm.display,from=change.from,to=change.to,recomputeMaxLength=!1,checkWidthStart=from.line;cm.options.lineWrapping||(checkWidthStart=lineNo(visualLine(getLine(doc,from.line))),doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine)return recomputeMaxLength=!0})),-1<doc.sel.contains(change.from,change.to)&&signalCursorActivity(cm),updateDoc(doc,change,spans,estimateHeight(cm)),cm.options.lineWrapping||(doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);len>display.maxLineLength&&(display.maxLine=line,display.maxLineLength=len,display.maxLineChanged=!0,recomputeMaxLength=!1)}),recomputeMaxLength&&(cm.curOp.updateMaxLine=!0)),((doc,n)=>{if(doc.modeFrontier=Math.min(doc.modeFrontier,n),!(doc.highlightFrontier<n-10)){for(var start=doc.first,line=n-1;start<line;line--){var saved=getLine(doc,line).stateAfter;if(saved&&(!(saved instanceof SavedContext)||line+saved.lookAhead<n)){start=line+1;break}}doc.highlightFrontier=Math.min(doc.highlightFrontier,start)}})(doc,from.line),startWorker(cm,400),spans=change.text.length-(to.line-from.line)-1,change.full?regChange(cm):from.line!=to.line||1!=change.text.length||isWholeLineUpdate(cm.doc,change)?regChange(cm,from.line,to.line+1,spans):regLineChange(cm,from.line,"text"),checkWidthStart=hasHandler(cm,"changes"),((doc=hasHandler(cm,"change"))||checkWidthStart)&&(spans={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin},doc&&signalLater(cm,"change",cm,spans),checkWidthStart)&&(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(spans),cm.display.selForContextMenu=null})(doc.cm,change,spans):updateDoc(doc,change,spans),setSelectionNoUndo(doc,selAfter,sel_dontScroll),doc.cantEdit&&skipAtomic(doc,Pos(doc.firstLine(),0))&&(doc.cantEdit=!1))}function replaceRange(doc,code,from,to,origin){var assign;cmp(to=to||from,from)<0&&(from=(assign=[to,from])[0],to=assign[1]),"string"==typeof code&&(code=doc.splitLines(code)),makeChange(doc,{from:from,to:to,text:code,origin:origin})}function rebaseHistSelSingle(pos,from,to,diff){to<pos.line?pos.line+=diff:from<pos.line&&(pos.line=from,pos.ch=0)}function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=!0;if(sub.ranges){sub.copied||((sub=array[i]=sub.deepCopy()).copied=!0);for(var j=0;j<sub.ranges.length;j++)rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff),rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)}else{for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1];if(to<cur.from.line)cur.from=Pos(cur.from.line+diff,cur.from.ch),cur.to=Pos(cur.to.line+diff,cur.to.ch);else if(from<=cur.to.line){ok=!1;break}}ok||(array.splice(0,i+1),i=0)}}}function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,change=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,change),rebaseHistArray(hist.undone,from,to,change)}function changeLine(doc,handle,changeType,op){var no=handle,line=handle;return"number"==typeof handle?line=getLine(doc,clipLine(doc,handle)):no=lineNo(handle),null==no?null:(op(line,no)&&doc.cm&®LineChange(doc.cm,no,changeType),line)}function LeafChunk(lines){this.lines=lines,this.parent=null;for(var height=0,i=0;i<lines.length;++i)lines[i].parent=this,height+=lines[i].height;this.height=height}function BranchChunk(children){this.children=children;for(var size=0,height=0,i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize(),height+=ch.height,ch.parent=this}this.size=size,this.height=height,this.parent=null}Range.prototype.from=function(){return minPos(this.anchor,this.head)},Range.prototype.to=function(){return maxPos(this.anchor,this.head)},Range.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var i=at,e=at+n;i<e;++i){var line=this.lines[i];this.height-=line.height,(line=>{line.parent=null,detachMarkedSpans(line)})(line),signalLater(line,"delete")}this.lines.splice(at,n)},collapse:function(lines){lines.push.apply(lines,this.lines)},insertInner:function(at,lines,height){this.height+=height,this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i)lines[i].parent=this},iterN:function(at,n,op){for(var e=at+n;at<e;++at)if(op(this.lines[at]))return!0}},BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){this.size-=n;for(var lines,i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height;if(child.removeInner(at,rm),this.height-=oldHeight-child.height,sz==rm&&(this.children.splice(i--,1),child.parent=null),0==(n-=rm))break;at=0}else at-=sz}this.size-n<25&&(1<this.children.length||!(this.children[0]instanceof LeafChunk))&&(this.collapse(lines=[]),this.children=[new LeafChunk(lines)],this.children[0].parent=this)},collapse:function(lines){for(var i=0;i<this.children.length;++i)this.children[i].collapse(lines)},insertInner:function(at,lines,height){this.size+=lines.length,this.height+=height;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<=sz){if(child.insertInner(at,lines,height),child.lines&&50<child.lines.length){for(var remaining=child.lines.length%25+25,pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25));child.height-=leaf.height,this.children.splice(++i,0,leaf),leaf.parent=this}child.lines=child.lines.slice(0,remaining),this.maybeSpill()}break}at-=sz}},maybeSpill:function(){if(!(this.children.length<=10)){var me=this;do{var myIndex,sibling=new BranchChunk(me.children.splice(me.children.length-5,5))}while(me.parent?(me.size-=sibling.size,me.height-=sibling.height,myIndex=indexOf(me.parent.children,me),me.parent.children.splice(myIndex+1,0,sibling)):(((myIndex=new BranchChunk(me.children)).parent=me).children=[myIndex,sibling],me=myIndex),sibling.parent=me.parent,10<me.children.length);me.parent.maybeSpill()}},iterN:function(at,n,op){for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(at<sz){var used=Math.min(n,sz-at);if(child.iterN(at,used,op))return!0;if(0==(n-=used))break;at=0}else at-=sz}}};function LineWidget(doc,node,options){if(options)for(var opt in options)options.hasOwnProperty(opt)&&(this[opt]=options[opt]);this.doc=doc,this.node=node}function adjustScrollWhenAboveVisible(cm,line,diff){heightAtLine(line)<(cm.curOp&&cm.curOp.scrollTop||cm.doc.scrollTop)&&addToScrollTop(cm,diff)}LineWidget.prototype.clear=function(){var cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(null!=no&&ws){for(var i=0;i<ws.length;++i)ws[i]==this&&ws.splice(i--,1);ws.length||(line.widgets=null);var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height)),cm&&(runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height),regLineChange(cm,no,"widget")}),signalLater(cm,"lineWidgetCleared",cm,this,no))}},LineWidget.prototype.changed=function(){var this$1=this,oldH=this.height,cm=this.doc.cm,line=this.line,diff=(this.height=null,widgetHeight(this)-oldH);diff&&(lineIsHidden(this.doc,line)||updateLineHeight(line,line.height+diff),cm)&&runInOp(cm,function(){cm.curOp.forceUpdate=!0,adjustScrollWhenAboveVisible(cm,line,diff),signalLater(cm,"lineWidgetChanged",cm,this$1,lineNo(line))})},eventMixin(LineWidget);function TextMarker(doc,type){this.lines=[],this.type=type,this.doc=doc,this.id=++nextMarkerId}var nextMarkerId=0;function markText(doc,from,to,options,type){if(options&&options.shared)return((doc,from,to,options,type)=>{(options=copyObj(options)).shared=!1;var markers=[markText(doc,from,to,options,type)],primary=markers[0],widget=options.widgetNode;return linkedDocs(doc,function(doc){widget&&(options.widgetNode=widget.cloneNode(!0)),markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)if(doc.linked[i].isParent)return;primary=lst(markers)}),new SharedTextMarker(markers,primary)})(doc,from,to,options,type);if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,markText)(doc,from,to,options,type);var marker=new TextMarker(doc,type),type=cmp(from,to);if(options&©Obj(options,marker,!1),!(0<type||0==type&&!1!==marker.clearWhenEmpty)){if(marker.replacedWith&&(marker.collapsed=!0,marker.widgetNode=eltP("span",[marker.replacedWith],"CodeMirror-widget"),options.handleMouseEvents||marker.widgetNode.setAttribute("cm-ignore-events","true"),options.insertLeft)&&(marker.widgetNode.insertLeft=!0),marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))throw new Error("Inserting collapsed marker partially overlapping an existing one");sawCollapsedSpans=!0}marker.addToHistory&&addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);var updateMaxLine,curLine=from.line,cm=doc.cm;if(doc.iter(curLine,to.line+1,function(line){cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine&&(updateMaxLine=!0),marker.collapsed&&curLine!=from.line&&updateLineHeight(line,0),((line,span)=>{line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span],span.marker.attachLine(line)})(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null)),++curLine}),marker.collapsed&&doc.iter(from.line,to.line+1,function(line){lineIsHidden(doc,line)&&updateLineHeight(line,0)}),marker.clearOnEnter&&on(marker,"beforeCursorEnter",function(){return marker.clear()}),marker.readOnly&&(sawReadOnlySpans=!0,doc.history.done.length||doc.history.undone.length)&&doc.clearHistory(),marker.collapsed&&(marker.id=++nextMarkerId,marker.atomic=!0),cm){if(updateMaxLine&&(cm.curOp.updateMaxLine=!0),marker.collapsed)regChange(cm,from.line,to.line+1);else if(marker.className||marker.startStyle||marker.endStyle||marker.css||marker.attributes||marker.title)for(var i=from.line;i<=to.line;i++)regLineChange(cm,i,"text");marker.atomic&&reCheckSelection(cm.doc),signalLater(cm,"markerAdded",cm,marker)}}return marker}TextMarker.prototype.clear=function(){if(!this.explicitlyCleared){for(var found,cm=this.doc.cm,withOp=cm&&!cm.curOp,min=(withOp&&startOperation(cm),hasHandler(this,"clear")&&(found=this.find())&&signalLater(this,"clear",found.from,found.to),null),max=null,i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);cm&&!this.collapsed?regLineChange(cm,lineNo(line),"text"):cm&&(null!=span.to&&(max=lineNo(line)),null!=span.from)&&(min=lineNo(line)),line.markedSpans=((spans,span)=>{for(var r,i=0;i<spans.length;++i)spans[i]!=span&&(r=r||[]).push(spans[i]);return r})(line.markedSpans,span),null==span.from&&this.collapsed&&!lineIsHidden(this.doc,line)&&cm&&updateLineHeight(line,textHeight(cm.display))}if(cm&&this.collapsed&&!cm.options.lineWrapping)for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this.lines[i$1]),len=lineLength(visual);len>cm.display.maxLineLength&&(cm.display.maxLine=visual,cm.display.maxLineLength=len,cm.display.maxLineChanged=!0)}null!=min&&cm&&this.collapsed&®Change(cm,min,max+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,cm)&&reCheckSelection(cm.doc),cm&&signalLater(cm,"markerCleared",cm,this,min,max),withOp&&endOperation(cm),this.parent&&this.parent.clear()}},TextMarker.prototype.find=function(side,lineObj){var from,to;null==side&&"bookmark"==this.type&&(side=1);for(var i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);if(null!=span.from&&(from=Pos(lineObj?line:lineNo(line),span.from),-1==side))return from;if(null!=span.to&&(to=Pos(lineObj?line:lineNo(line),span.to),1==side))return to}return from&&{from:from,to:to}},TextMarker.prototype.changed=function(){var this$1=this,pos=this.find(-1,!0),widget=this,cm=this.doc.cm;pos&&cm&&runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line),lineN=findViewForLine(cm,lineN);lineN&&(clearLineMeasurementCacheFor(lineN),cm.curOp.selectionChanged=cm.curOp.forceUpdate=!0),cm.curOp.updateMaxLine=!0,!lineIsHidden(widget.doc,line)&&null!=widget.height&&(lineN=widget.height,widget.height=null,lineN=widgetHeight(widget)-lineN)&&updateLineHeight(line,line.height+lineN),signalLater(cm,"markerChanged",cm,this$1)})},TextMarker.prototype.attachLine=function(line){var op;this.lines.length||!this.doc.cm||(op=this.doc.cm.curOp).maybeHiddenMarkers&&-1!=indexOf(op.maybeHiddenMarkers,this)||(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this),this.lines.push(line)},TextMarker.prototype.detachLine=function(line){this.lines.splice(indexOf(this.lines,line),1),!this.lines.length&&this.doc.cm&&((line=this.doc.cm.curOp).maybeHiddenMarkers||(line.maybeHiddenMarkers=[])).push(this)},eventMixin(TextMarker);var SharedTextMarker=function(markers,primary){this.markers=markers,this.primary=primary;for(var i=0;i<markers.length;++i)markers[i].parent=this};function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent})}function detachSharedMarkers(markers){for(var i=0;i<markers.length;i++)(i=>{var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){return linked.push(d)});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];-1==indexOf(linked,subMarker.doc)&&(subMarker.parent=null,marker.markers.splice(j--,1))}})(i)}SharedTextMarker.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var i=0;i<this.markers.length;++i)this.markers[i].clear();signalLater(this,"clear")}},SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)},eventMixin(SharedTextMarker);function Doc(text,mode,firstLine,lineSep,direction){if(!(this instanceof Doc))return new Doc(text,mode,firstLine,lineSep,direction);null==firstLine&&(firstLine=0),BranchChunk.call(this,[new LeafChunk([new Line("",null)])]),this.first=firstLine,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,firstLine=Pos(this.modeFrontier=this.highlightFrontier=firstLine,0),this.sel=simpleSelection(firstLine),this.history=new History(null),this.id=++nextDocId,this.modeOption=mode,this.lineSep=lineSep,this.direction="rtl"==direction?"rtl":"ltr",this.extend=!1,"string"==typeof text&&(text=this.splitLines(text)),updateDoc(this,{from:firstLine,to:firstLine,text:text}),setSelection(this,simpleSelection(firstLine),sel_dontScroll)}var nextDocId=0,lastDrop=((Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){op?this.iterN(from-this.first,to-from,op):this.iterN(this.first,this.first+this.size,from)},insert:function(at,lines){for(var height=0,i=0;i<lines.length;++i)height+=lines[i].height;this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:!0},!0),this.cm&&scrollToCoords(this.cm,0,0),setSelection(this,simpleSelection(top),sel_dontScroll)}),replaceRange:function(code,from,to,origin){replaceRange(this,code,from=clipPos(this,from),to=to?clipPos(this,to):from,origin)},getRange:function(from,to,lineSep){from=getBetween(this,clipPos(this,from),clipPos(this,to));return!1===lineSep?from:from.join(lineSep||this.lineSeparator())},getLine:function(line){line=this.getLineHandle(line);return line&&line.text},getLineHandle:function(line){if(isLine(this,line))return getLine(this,line)},getLineNumber:lineNo,getLineHandleVisualStart:function(line){return visualLine(line="number"==typeof line?getLine(this,line):line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var range=this.sel.primary(),start=null==start||"head"==start?range.head:"anchor"==start?range.anchor:"end"==start||"to"==start||!1===start?range.to():range.from();return start},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,"number"==typeof line?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){extendSelections(this,clipPosArray(this,map(this.sel.ranges,f)),options)}),setSelections:docMethodOp(function(ranges,primary,options){if(ranges.length){for(var out=[],i=0;i<ranges.length;i++)out[i]=new Range(clipPos(this,ranges[i].anchor),clipPos(this,ranges[i].head));null==primary&&(primary=Math.min(ranges.length-1,this.sel.primIndex)),setSelection(this,normalizeSelection(this.cm,out,primary),options)}}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor))),setSelection(this,normalizeSelection(this.cm,ranges,ranges.length-1),options)}),getSelection:function(lineSep){for(var ranges=this.sel.ranges,i=0;i<ranges.length;i++)var sel=getBetween(this,ranges[i].from(),ranges[i].to()),lines=lines?lines.concat(sel):sel;return!1===lineSep?lines:lines.join(lineSep||this.lineSeparator())},getSelections:function(lineSep){for(var parts=[],ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());!1!==lineSep&&(sel=sel.join(lineSep||this.lineSeparator())),parts[i]=sel}return parts},replaceSelection:function(code,collapse,origin){for(var dup=[],i=0;i<this.sel.ranges.length;i++)dup[i]=code;this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){for(var changes=[],sel=this.sel,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i];changes[i]={from:range.from(),to:range.to(),text:this.splitLines(code[i]),origin:origin}}for(var collapse=collapse&&"end"!=collapse&&((doc,changes,hint)=>{for(var out=[],newPrev=oldPrev=Pos(doc.first,0),i=0;i<changes.length;i++){var change=changes[i],from=offsetPos(change.from,oldPrev,newPrev),to=offsetPos(changeEnd(change),oldPrev,newPrev),oldPrev=change.to,newPrev=to;"around"==hint?(change=cmp((change=doc.sel.ranges[i]).head,change.anchor)<0,out[i]=new Range(change?to:from,change?from:to)):out[i]=new Range(from,from)}return new Selection(out,doc.sel.primIndex)})(this,changes,collapse),i$1=changes.length-1;0<=i$1;i$1--)makeChange(this,changes[i$1]);collapse?setSelectionReplaceHistory(this,collapse):this.cm&&ensureCursorVisible(this.cm)}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",!0)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",!0)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){for(var hist=this.history,done=0,undone=0,i=0;i<hist.done.length;i++)hist.done[i].ranges||++done;for(var i$1=0;i$1<hist.undone.length;i$1++)hist.undone[i$1].ranges||++undone;return{undo:done,redo:undone}},clearHistory:function(){var this$1=this;this.history=new History(this.history.maxGeneration),linkedDocs(this,function(doc){return doc.history=this$1.history},!0)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(forceSplit){return forceSplit&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,!0),hist.undone=copyHistoryArray(histData.undone.slice(0),null,!0)},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});return!(markers[gutterID]=value)&&isEmpty(markers)&&(line.gutterMarkers=null),1})}),clearGutter:docMethodOp(function(gutterID){var this$1=this;this.iter(function(line){line.gutterMarkers&&line.gutterMarkers[gutterID]&&changeLine(this$1,line,"gutter",function(){return line.gutterMarkers[gutterID]=null,isEmpty(line.gutterMarkers)&&(line.gutterMarkers=null),1})})}),lineInfo:function(line){var n;if("number"==typeof line){if(!isLine(this,line))return null;if(n=line,!(line=getLine(this,line)))return null}else if(null==(n=lineNo(line)))return null;return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass";if(line[prop]){if(classTest(cls).test(line[prop]))return;line[prop]+=" "+cls}else line[prop]=cls;return 1})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass",cur=line[prop];if(cur){if(null==cls)line[prop]=null;else{var found=cur.match(classTest(cls));if(!found)return;var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(found.index&&end!=cur.length?" ":"")+cur.slice(end)||null}return 1}})}),addLineWidget:docMethodOp(function(handle,node,options){return((doc,handle,node,options)=>{var widget=new LineWidget(doc,node,options),cm=doc.cm;return cm&&widget.noHScroll&&(cm.display.alignWidgets=!0),changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);return null==widget.insertAt?widgets.push(widget):widgets.splice(Math.min(widgets.length,Math.max(0,widget.insertAt)),0,widget),widget.line=line,cm&&!lineIsHidden(doc,line)&&(widgets=heightAtLine(line)<doc.scrollTop,updateLineHeight(line,line.height+widgetHeight(widget)),widgets&&addToScrollTop(cm,widget.height),cm.curOp.forceUpdate=!0),1}),cm&&signalLater(cm,"lineWidgetAdded",cm,widget,"number"==typeof handle?handle:lineNo(handle)),widget})(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){options={replacedWith:options&&(null==options.nodeType?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:!1,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};return markText(this,pos=clipPos(this,pos),pos,options,"bookmark")},findMarksAt:function(pos){var markers=[],spans=getLine(this,(pos=clipPos(this,pos)).line).markedSpans;if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];(null==span.from||span.from<=pos.ch)&&(null==span.to||span.to>=pos.ch)&&markers.push(span.marker.parent||span.marker)}return markers},findMarks:function(from,to,filter){from=clipPos(this,from),to=clipPos(this,to);var found=[],lineNo=from.line;return this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans)for(var i=0;i<spans.length;i++){var span=spans[i];null!=span.to&&lineNo==from.line&&from.ch>=span.to||null==span.from&&lineNo!=from.line||null!=span.from&&lineNo==to.line&&span.from>=to.ch||filter&&!filter(span.marker)||found.push(span.marker.parent||span.marker)}++lineNo}),found},getAllMarks:function(){var markers=[];return this.iter(function(line){var sps=line.markedSpans;if(sps)for(var i=0;i<sps.length;++i)null!=sps[i].from&&markers.push(sps[i].marker)}),markers},posFromIndex:function(off){var ch,lineNo=this.first,sepSize=this.lineSeparator().length;return this.iter(function(line){line=line.text.length+sepSize;if(off<line)return ch=off,!0;off-=line,++lineNo}),clipPos(this,Pos(lineNo,ch))},indexFromPos:function(coords){var sepSize,index=(coords=clipPos(this,coords)).ch;return coords.line<this.first||coords.ch<0?0:(sepSize=this.lineSeparator().length,this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize}),index)},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);return doc.scrollTop=this.scrollTop,doc.scrollLeft=this.scrollLeft,doc.sel=this.sel,doc.extend=!1,copyHistory&&(doc.history.undoDepth=this.history.undoDepth,doc.setHistory(this.getHistory())),doc},linkedDoc:function(options){for(var from=this.first,to=this.first+this.size,to=(null!=(options=options||{}).from&&options.from>from&&(from=options.from),null!=options.to&&options.to<to&&(to=options.to),new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep,this.direction)),doc=(options.sharedHist&&(to.history=this.history),(this.linked||(this.linked=[])).push({doc:to,sharedHist:options.sharedHist}),to.linked=[{doc:this,isParent:!0,sharedHist:options.sharedHist}],to),markers=findSharedMarkers(this),i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find(),mFrom=doc.clipPos(pos.from),pos=doc.clipPos(pos.to);cmp(mFrom,pos)&&(mFrom=markText(doc,mFrom,pos,marker.primary,marker.primary.type),marker.markers.push(mFrom),mFrom.parent=marker)}return to},unlinkDoc:function(other){if(other instanceof CodeMirror&&(other=other.doc),this.linked)for(var i=0;i<this.linked.length;++i){var link=this.linked[i];if(link.doc==other){this.linked.splice(i,1),other.unlinkDoc(this),detachSharedMarkers(findSharedMarkers(this));break}}var splitIds;other.history==this.history&&(splitIds=[other.id],linkedDocs(other,function(doc){return splitIds.push(doc.id)},!0),other.history=new History(null),other.history.done=copyHistoryArray(this.history.done,splitIds),other.history.undone=copyHistoryArray(this.history.undone,splitIds))},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){return this.lineSep?str.split(this.lineSep):splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:docMethodOp(function(dir){var cm;(dir="rtl"!=dir?"ltr":dir)!=this.direction&&(this.direction=dir,this.iter(function(line){return line.order=null}),this.cm)&&runInOp(cm=this.cm,function(){setDirectionClass(cm),regChange(cm)})})})).eachLine=Doc.prototype.iter,0);function onDrop(e){var cm=this;if(clearDragCursor(cm),!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e),ie&&(lastDrop=+new Date);var pos=posFromMouse(cm,e,!0),files=e.dataTransfer.files;if(pos&&!cm.isReadOnly())if(files&&files.length&&window.FileReader&&window.File)for(var n=files.length,text=Array(n),read=0,markAsReadAndPasteIfAllFilesAreRead=function(){++read==n&&operation(cm,function(){var change={from:pos=clipPos(cm.doc,pos),to:pos,text:cm.doc.splitLines(text.filter(function(t){return null!=t}).join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change),setSelectionReplaceHistory(cm.doc,simpleSelection(clipPos(cm.doc,pos),clipPos(cm.doc,changeEnd(change))))})()},i=0;i<files.length;i++)((file,i)=>{var reader;cm.options.allowDropFileTypes&&-1==indexOf(cm.options.allowDropFileTypes,file.type)?markAsReadAndPasteIfAllFilesAreRead():((reader=new FileReader).onerror=function(){return markAsReadAndPasteIfAllFilesAreRead()},reader.onload=function(){var content=reader.result;/[\x00-\x08\x0e-\x1f]{2}/.test(content)||(text[i]=content),markAsReadAndPasteIfAllFilesAreRead()},reader.readAsText(file))})(files[i],i);else if(cm.state.draggingText&&-1<cm.doc.sel.contains(pos))cm.state.draggingText(e),setTimeout(function(){return cm.display.input.focus()},20);else try{var selected,text$1=e.dataTransfer.getData("Text");if(text$1){if(cm.state.draggingText&&!cm.state.draggingText.copy&&(selected=cm.listSelections()),setSelectionNoUndo(cm.doc,simpleSelection(pos,pos)),selected)for(var i$1=0;i$1<selected.length;++i$1)replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag");cm.replaceSelection(text$1,"around","paste"),cm.display.input.focus()}}catch(e$1){}}}function clearDragCursor(cm){cm.display.dragCursor&&(cm.display.lineSpace.removeChild(cm.display.dragCursor),cm.display.dragCursor=null)}function forEachCodeMirror(f){if(document.getElementsByClassName){for(var byClass=document.getElementsByClassName("CodeMirror"),editors=[],i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;cm&&editors.push(cm)}editors.length&&editors[0].operation(function(){for(var i=0;i<editors.length;i++)f(editors[i])})}}var globalsRegistered=!1;function ensureGlobalHandlers(){var resizeTimer;globalsRegistered||(on(window,"resize",function(){null==resizeTimer&&(resizeTimer=setTimeout(function(){resizeTimer=null,forEachCodeMirror(onResize)},100))}),on(window,"blur",function(){return forEachCodeMirror(onBlur)}),globalsRegistered=!0)}function onResize(cm){var d=cm.display;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null,d.scrollbarsClipped=!1,cm.setSize()}for(var keyNames={3:"Pause",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",224:"Mod",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},i=0;i<10;i++)keyNames[i+48]=keyNames[i+96]=String(i);for(var i$1=65;i$1<=90;i$1++)keyNames[i$1]=String.fromCharCode(i$1);for(var i$2=1;i$2<=12;i$2++)keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2;var keyMap={};function normalizeKeyName(name){var alt,ctrl,shift,cmd,parts=name.split(/-(?!$)/);name=parts[parts.length-1];for(var i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))cmd=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else{if(!/^s(hift)?$/i.test(mod))throw new Error("Unrecognized modifier name: "+mod);shift=!0}}return alt&&(name="Alt-"+name),ctrl&&(name="Ctrl-"+name),cmd&&(name="Cmd-"+name),name=shift?"Shift-"+name:name}function normalizeKeyMap(keymap){var keyname,prop,copy={};for(keyname in keymap)if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(!/^(name|fallthrough|(de|at)tach)$/.test(keyname)){if("..."!=value)for(var keys=map(keyname.split(" "),normalizeKeyName),i=0;i<keys.length;i++){var val=void 0,name=void 0,val=i==keys.length-1?(name=keys.join(" "),value):(name=keys.slice(0,i+1).join(" "),"..."),prev=copy[name];if(prev){if(prev!=val)throw new Error("Inconsistent bindings for "+name)}else copy[name]=val}delete keymap[keyname]}}for(prop in copy)keymap[prop]=copy[prop];return keymap}function lookupKey(key,map,handle,context){var found=(map=getKeyMap(map)).call?map.call(key,context):map[key];if(!1===found)return"nothing";if("..."===found)return"multi";if(null!=found&&handle(found))return"handled";if(map.fallthrough){if("[object Array]"!=Object.prototype.toString.call(map.fallthrough))return lookupKey(key,map.fallthrough,handle,context);for(var i=0;i<map.fallthrough.length;i++){var result=lookupKey(key,map.fallthrough[i],handle,context);if(result)return result}}}function isModifierKey(value){value="string"==typeof value?value:keyNames[value.keyCode];return"Ctrl"==value||"Alt"==value||"Shift"==value||"Mod"==value}function addModifierNames(name,event,noShift){var base=name;return event.altKey&&"Alt"!=base&&(name="Alt-"+name),(flipCtrlCmd?event.metaKey:event.ctrlKey)&&"Ctrl"!=base&&(name="Ctrl-"+name),(flipCtrlCmd?event.ctrlKey:event.metaKey)&&"Mod"!=base&&(name="Cmd-"+name),name=!noShift&&event.shiftKey&&"Shift"!=base?"Shift-"+name:name}function keyName(event,noShift){var name;return!(presto&&34==event.keyCode&&event.char||null==(name=keyNames[event.keyCode])||event.altGraphKey)&&addModifierNames(name=3==event.keyCode&&event.code?event.code:name,event,noShift)}function getKeyMap(val){return"string"==typeof val?keyMap[val]:val}function deleteNearSelection(cm,compute){for(var ranges=cm.doc.sel.ranges,kill=[],i=0;i<ranges.length;i++){for(var toKill=compute(ranges[i]);kill.length&&cmp(toKill.from,lst(kill).to)<=0;){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}kill.push(toKill)}runInOp(cm,function(){for(var i=kill.length-1;0<=i;i--)replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");ensureCursorVisible(cm)})}function moveCharLogically(line,ch,dir){ch=skipExtendingChars(line.text,ch+dir,dir);return ch<0||ch>line.text.length?null:ch}function moveLogically(line,start,dir){line=moveCharLogically(line,start.ch,dir);return null==line?null:new Pos(start.line,line,dir<0?"after":"before")}function endOfLine(visually,cm,lineObj,lineNo,dir){if(visually){"rtl"==cm.doc.direction&&(dir=-dir);var sticky,prep,ch,targetTop,visually=getOrder(lineObj,cm.doc.direction);if(visually)return sticky=dir<0==(1==(visually=dir<0?lst(visually):visually[0]).level)?"after":"before",0<visually.level||"rtl"==cm.doc.direction?(prep=prepareMeasureForLine(cm,lineObj),ch=dir<0?lineObj.text.length-1:0,targetTop=measureCharPrepared(cm,prep,ch).top,ch=findFirst(function(ch){return measureCharPrepared(cm,prep,ch).top==targetTop},dir<0==(1==visually.level)?visually.from:visually.to-1,ch),"before"==sticky&&(ch=moveCharLogically(lineObj,ch,1))):ch=dir<0?visually.to:visually.from,new Pos(lineNo,ch,sticky)}return new Pos(lineNo,dir<0?lineObj.text.length:0,dir<0?"before":"after")}function moveVisually(cm,line,start,dir){var bidi=getOrder(line,cm.doc.direction);if(!bidi)return moveLogically(line,start,dir);start.ch>=line.text.length?(start.ch=line.text.length,start.sticky="before"):start.ch<=0&&(start.ch=0,start.sticky="after");var partPos=getBidiPartAt(bidi,start.ch,start.sticky),part=bidi[partPos];if("ltr"==cm.doc.direction&&part.level%2==0&&(0<dir?part.to>start.ch:part.from<start.ch))return moveLogically(line,start,dir);function mv(pos,dir){return moveCharLogically(line,pos instanceof Pos?pos.ch:pos,dir)}function getWrappedLineExtent(ch){return cm.options.lineWrapping?(prep=prep||prepareMeasureForLine(cm,line),wrappedLineExtentChar(cm,line,prep,ch)):{begin:0,end:line.text.length}}var prep,wrappedLineExtent=getWrappedLineExtent("before"==start.sticky?mv(start,-1):start.ch);if("rtl"==cm.doc.direction||1==part.level){var moveInStorageOrder=1==part.level==dir<0,ch=mv(start,moveInStorageOrder?1:-1);if(null!=ch&&(moveInStorageOrder?ch<=part.to&&ch<=wrappedLineExtent.end:ch>=part.from&&ch>=wrappedLineExtent.begin))return new Pos(start.line,ch,moveInStorageOrder?"before":"after")}function searchInVisualLine(partPos,dir,wrappedLineExtent){for(var getRes=function(ch,moveInStorageOrder){return moveInStorageOrder?new Pos(start.line,mv(ch,1),"before"):new Pos(start.line,ch,"after")};0<=partPos&&partPos<bidi.length;partPos+=dir){var part=bidi[partPos],moveInStorageOrder=0<dir==(1!=part.level),ch=moveInStorageOrder?wrappedLineExtent.begin:mv(wrappedLineExtent.end,-1);if(part.from<=ch&&ch<part.to)return getRes(ch,moveInStorageOrder);if(ch=moveInStorageOrder?part.from:mv(part.to,-1),wrappedLineExtent.begin<=ch&&ch<wrappedLineExtent.end)return getRes(ch,moveInStorageOrder)}}part=searchInVisualLine(partPos+dir,dir,wrappedLineExtent);return part||(null==(ch=0<dir?wrappedLineExtent.end:mv(wrappedLineExtent.begin,-1))||0<dir&&ch==line.text.length||!(part=searchInVisualLine(0<dir?0:bidi.length-1,dir,getWrappedLineExtent(ch)))?null:part)}keyMap.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},keyMap.default=mac?keyMap.macDefault:keyMap.pcDefault;var commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll)},killLine:function(cm){return deleteNearSelection(cm,function(range){var len;return range.empty()?(len=getLine(cm.doc,range.head.line).text.length,range.head.ch==len&&range.head.line<cm.lastLine()?{from:range.head,to:Pos(range.head.line+1,0)}:{from:range.head,to:Pos(range.head.line,len)}):{from:range.from(),to:range.to()}})},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))}})},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:range.from()}})},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5;return{from:cm.coordsChar({left:0,top:top},"div"),to:range.from()}})},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,top=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:top}})},undo:function(cm){return cm.undo()},redo:function(cm){return cm.redo()},undoSelection:function(cm){return cm.undoSelection()},redoSelection:function(cm){return cm.redoSelection()},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0))},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()))},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head)},{origin:"+move",bias:1})},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return((cm,lineN)=>{var line=getLine(cm.doc,lineN),visual=(line=>{for(var merged;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return line})(line);return visual!=line&&(lineN=lineNo(visual)),endOfLine(!0,cm,line,lineN,-1)})(cm,range.head.line)},{origin:"+move",bias:-1})},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){range=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:range},"div")},sel_move)},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){range=cm.cursorCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:range},"div")},sel_move)},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.cursorCoords(range.head,"div").top+5,top=cm.coordsChar({left:0,top:top},"div");return top.ch<cm.getLine(top.line).search(/\S/)?lineStartSmart(cm,range.head):top},sel_move)},goLineUp:function(cm){return cm.moveV(-1,"line")},goLineDown:function(cm){return cm.moveV(1,"line")},goPageUp:function(cm){return cm.moveV(-1,"page")},goPageDown:function(cm){return cm.moveV(1,"page")},goCharLeft:function(cm){return cm.moveH(-1,"char")},goCharRight:function(cm){return cm.moveH(1,"char")},goColumnLeft:function(cm){return cm.moveH(-1,"column")},goColumnRight:function(cm){return cm.moveH(1,"column")},goWordLeft:function(cm){return cm.moveH(-1,"word")},goGroupRight:function(cm){return cm.moveH(1,"group")},goGroupLeft:function(cm){return cm.moveH(-1,"group")},goWordRight:function(cm){return cm.moveH(1,"word")},delCharBefore:function(cm){return cm.deleteH(-1,"codepoint")},delCharAfter:function(cm){return cm.deleteH(1,"char")},delWordBefore:function(cm){return cm.deleteH(-1,"word")},delWordAfter:function(cm){return cm.deleteH(1,"word")},delGroupBefore:function(cm){return cm.deleteH(-1,"group")},delGroupAfter:function(cm){return cm.deleteH(1,"group")},indentAuto:function(cm){return cm.indentSelection("smart")},indentMore:function(cm){return cm.indentSelection("add")},indentLess:function(cm){return cm.indentSelection("subtract")},insertTab:function(cm){return cm.replaceSelection("\t")},insertSoftTab:function(cm){for(var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize,i=0;i<ranges.length;i++){var pos=ranges[i].from(),pos=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(spaceStr(tabSize-pos%tabSize))}cm.replaceSelections(spaces)},defaultTab:function(cm){cm.somethingSelected()?cm.indentSelection("add"):cm.execCommand("insertTab")},transposeChars:function(cm){return runInOp(cm,function(){for(var cur,line,prev,ranges=cm.listSelections(),newSel=[],i=0;i<ranges.length;i++)ranges[i].empty()&&(cur=ranges[i].head,(line=getLine(cm.doc,cur.line).text)&&(0<(cur=cur.ch==line.length?new Pos(cur.line,cur.ch-1):cur).ch?(cur=new Pos(cur.line,cur.ch+1),cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose")):cur.line>cm.doc.first&&(prev=getLine(cm.doc,cur.line-1).text)&&(cur=new Pos(cur.line,1),cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose"))),newSel.push(new Range(cur,cur)));cm.setSelections(newSel)})},newlineAndIndent:function(cm){return runInOp(cm,function(){for(var i=(sels=cm.listSelections()).length-1;0<=i;i--)cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input");for(var sels=cm.listSelections(),i$1=0;i$1<sels.length;i$1++)cm.indentLine(sels[i$1].from().line,null,!0);ensureCursorVisible(cm)})},openLine:function(cm){return cm.replaceSelection("\n","start")},toggleOverwrite:function(cm){return cm.toggleOverwrite()}};function lineStart(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLine(line);return endOfLine(!0,cm,visual,lineN=visual!=line?lineNo(visual):lineN,1)}function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line),line=getLine(cm.doc,start.line),cm=getOrder(line,cm.doc.direction);return cm&&0!=cm[0].level?start:(cm=Math.max(start.ch,line.text.search(/\S/)),line=pos.line==start.line&&pos.ch<=cm&&pos.ch,Pos(start.line,line?0:cm,start.sticky))}function doHandleBinding(cm,bound,dropShift){if("string"==typeof bound&&!(bound=commands[bound]))return!1;cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),dropShift&&(cm.display.shift=!1),done=bound(cm)!=Pass}finally{cm.display.shift=prevShift,cm.state.suppressEdits=!1}return done}var stopSeq=new Delayed;function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name))return"handled";if(/\'$/.test(name)?cm.state.keySeq=null:stopSeq.set(50,function(){cm.state.keySeq==seq&&(cm.state.keySeq=null,cm.display.input.reset())}),dispatchKeyInner(cm,seq+" "+name,e,handle))return!0}return dispatchKeyInner(cm,name,e,handle)}function dispatchKeyInner(cm,name,e,handle){handle=((cm,name,handle)=>{for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result)return result}return cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm)||lookupKey(name,cm.options.keyMap,handle,cm)})(cm,name,handle);return"multi"==handle&&(cm.state.keySeq=name),"handled"==handle&&signalLater(cm,"keyHandled",cm,name,e),"handled"!=handle&&"multi"!=handle||(e_preventDefault(e),restartBlink(cm)),!!handle}function handleKeyBinding(cm,e){var name=keyName(e,!0);return!!name&&(e.shiftKey&&!cm.state.keySeq?dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,!0)})||dispatchKey(cm,name,e,function(b){if("string"==typeof b?/^go[A-Z]/.test(b):b.motion)return doHandleBinding(cm,b)}):dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b)}))}var lastStoppedKey=null;function onKeyDown(e){var code,handled,cm=this;e.target&&e.target!=cm.display.input.getField()||(cm.curOp.focus=activeElt(),signalDOMEvent(cm,e))||(ie&&ie_version<11&&27==e.keyCode&&(e.returnValue=!1),cm.display.shift=16==(code=e.keyCode)||e.shiftKey,handled=handleKeyBinding(cm,e),presto&&(lastStoppedKey=handled?code:null,!handled)&&88==code&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)&&cm.replaceSelection("",null,"cut"),gecko&&!mac&&!handled&&46==code&&e.shiftKey&&!e.ctrlKey&&document.execCommand&&document.execCommand("cut"),18!=code)||/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)||(cm=>{var lineDiv=cm.display.lineDiv;function up(e){18!=e.keyCode&&e.altKey||(rmClass(lineDiv,"CodeMirror-crosshair"),off(document,"keyup",up),off(document,"mouseover",up))}addClass(lineDiv,"CodeMirror-crosshair"),on(document,"keyup",up),on(document,"mouseover",up)})(cm)}function onKeyUp(e){16==e.keyCode&&(this.doc.sel.shift=!1),signalDOMEvent(this,e)}function onKeyPress(e){var charCode,keyCode,cm=this;e.target&&e.target!=cm.display.input.getField()||eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey||(keyCode=e.keyCode,charCode=e.charCode,presto&&keyCode==lastStoppedKey?(lastStoppedKey=null,e_preventDefault(e)):presto&&(!e.which||e.which<10)&&handleKeyBinding(cm,e)||"\b"==(keyCode=String.fromCharCode(null==charCode?keyCode:charCode))||((cm,e,ch)=>dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,!0)}))(cm,e,keyCode)||cm.display.input.onKeyPress(e))}var lastClick,lastDoubleClick,PastClick=function(time,pos,button){this.time=time,this.pos=pos,this.button=button};function onMouseDown(e){var pos,button,repeat,cm=this,display=cm.display;signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch()||(display.input.ensurePolled(),display.shift=e.shiftKey,eventInWidget(display,e)?webkit||(display.scroller.draggable=!1,setTimeout(function(){return display.scroller.draggable=!0},100)):clickInGutter(cm,e)||(pos=posFromMouse(cm,e),button=e_button(e),repeat=pos?((pos,button)=>{var now=+new Date;return lastDoubleClick&&lastDoubleClick.compare(now,pos,button)?(lastClick=lastDoubleClick=null,"triple"):lastClick&&lastClick.compare(now,pos,button)?(lastDoubleClick=new PastClick(now,pos,button),lastClick=null,"double"):(lastClick=new PastClick(now,pos,button),lastDoubleClick=null,"single")})(pos,button):"single",window.focus(),1==button&&cm.state.selectingText&&cm.state.selectingText(e),pos&&((cm,button,pos,repeat,event)=>{var name="Click";return"double"==repeat?name="Double"+name:"triple"==repeat&&(name="Triple"+name),dispatchKey(cm,addModifierNames(name=(1==button?"Left":2==button?"Middle":"Right")+name,event),event,function(bound){if(!(bound="string"==typeof bound?commands[bound]:bound))return!1;var done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0),done=bound(cm,pos)!=Pass}finally{cm.state.suppressEdits=!1}return done})})(cm,button,pos,repeat,e))||(1==button?pos?((cm,pos,repeat,event)=>{ie?setTimeout(bind(ensureFocus,cm),0):cm.curOp.focus=activeElt();var behavior=((cm,repeat,event)=>{var rect,option=cm.getOption("configureMouse");return null==(option=option?option(cm,repeat,event):{}).unit&&(rect=chromeOS?event.shiftKey&&event.metaKey:event.altKey,option.unit=rect?"rectangle":"single"==repeat?"char":"double"==repeat?"word":"line"),null!=option.extend&&!cm.doc.extend||(option.extend=cm.doc.extend||event.shiftKey),null==option.addNew&&(option.addNew=mac?event.metaKey:event.ctrlKey),null==option.moveOnDrag&&(option.moveOnDrag=!(mac?event.altKey:event.ctrlKey)),option})(cm,repeat,event),sel=cm.doc.sel;(cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&"single"==repeat&&-1<(repeat=sel.contains(pos))&&(cmp((repeat=sel.ranges[repeat]).from(),pos)<0||0<pos.xRel)&&(0<cmp(repeat.to(),pos)||pos.xRel<0)?(cm,event,pos,behavior)=>{var display=cm.display,moved=!1,dragEnd=operation(cm,function(e){webkit&&(display.scroller.draggable=!1),cm.state.draggingText=!1,cm.state.delayingBlurEvent&&(cm.hasFocus()?cm.state.delayingBlurEvent=!1:delayBlurEvent(cm)),off(display.wrapper.ownerDocument,"mouseup",dragEnd),off(display.wrapper.ownerDocument,"mousemove",mouseMove),off(display.scroller,"dragstart",dragStart),off(display.scroller,"drop",dragEnd),moved||(e_preventDefault(e),behavior.addNew||extendSelection(cm.doc,pos,null,null,behavior.extend),webkit&&!safari||ie&&9==ie_version?setTimeout(function(){display.wrapper.ownerDocument.body.focus({preventScroll:!0}),display.input.focus()},20):display.input.focus())}),mouseMove=function(e2){moved=moved||10<=Math.abs(event.clientX-e2.clientX)+Math.abs(event.clientY-e2.clientY)},dragStart=function(){return moved=!0};webkit&&(display.scroller.draggable=!0),(cm.state.draggingText=dragEnd).copy=!behavior.moveOnDrag,on(display.wrapper.ownerDocument,"mouseup",dragEnd),on(display.wrapper.ownerDocument,"mousemove",mouseMove),on(display.scroller,"dragstart",dragStart),on(display.scroller,"drop",dragEnd),cm.state.delayingBlurEvent=!0,setTimeout(function(){return display.input.focus()},20),display.scroller.dragDrop&&display.scroller.dragDrop()}:(cm,event,start,behavior)=>{ie&&delayBlurEvent(cm);var display=cm.display,doc=cm.doc;e_preventDefault(event);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges,lastPos=(behavior.addNew&&!behavior.extend?(ourIndex=doc.sel.contains(start),ourRange=-1<ourIndex?ranges[ourIndex]:new Range(start,start)):(ourRange=doc.sel.primary(),ourIndex=doc.sel.primIndex),"rectangle"==behavior.unit?(behavior.addNew||(ourRange=new Range(start,start)),start=posFromMouse(cm,event,!0,!0),ourIndex=-1):(event=rangeForUnit(cm,start,behavior.unit),ourRange=behavior.extend?extendRange(ourRange,event.anchor,event.head,behavior.extend):event),behavior.addNew?-1==ourIndex?(ourIndex=ranges.length,setSelection(doc,normalizeSelection(cm,ranges.concat([ourRange]),ourIndex),{scroll:!1,origin:"*mouse"})):1<ranges.length&&ranges[ourIndex].empty()&&"char"==behavior.unit&&!behavior.extend?(setSelection(doc,normalizeSelection(cm,ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:!1,origin:"*mouse"}),startSel=doc.sel):replaceOneSelection(doc,ourIndex,ourRange,sel_mouse):(setSelection(doc,new Selection([ourRange],ourIndex=0),sel_mouse),startSel=doc.sel),start);function extendTo(pos){if(0!=cmp(lastPos,pos))if(lastPos=pos,"rectangle"==behavior.unit){for(var ranges=[],tabSize=cm.options.tabSize,startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize),posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize),left=Math.min(startCol,posCol),right=Math.max(startCol,posCol),line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);left==right?ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos))):text.length>leftPos&&ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}ranges.length||ranges.push(new Range(start,start)),setSelection(doc,normalizeSelection(cm,startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:!1}),cm.scrollIntoView(pos)}else{var head,startCol=ourRange,posCol=rangeForUnit(cm,pos,behavior.unit),pos=startCol.anchor,pos=0<cmp(posCol.anchor,pos)?(head=posCol.head,minPos(startCol.from(),posCol.anchor)):(head=posCol.anchor,maxPos(startCol.to(),posCol.head)),startCol=startSel.ranges.slice(0);startCol[ourIndex]=((cm,range)=>{var index,part,boundary,anchor=range.anchor,head=range.head,anchorLine=getLine(cm.doc,anchor.line);return 0==cmp(anchor,head)&&anchor.sticky==head.sticky||!(anchorLine=getOrder(anchorLine))||(index=getBidiPartAt(anchorLine,anchor.ch,anchor.sticky),(part=anchorLine[index]).from!=anchor.ch&&part.to!=anchor.ch)||0==(boundary=index+(part.from==anchor.ch==(1!=part.level)?0:1))||boundary==anchorLine.length||(index=(part=head.line!=anchor.line?0<(head.line-anchor.line)*("ltr"==cm.doc.direction?1:-1):(cm=getBidiPartAt(anchorLine,head.ch,head.sticky),index=cm-index||(head.ch-anchor.ch)*(1==part.level?-1:1),cm==boundary-1||cm==boundary?index<0:0<index))==(1==(cm=anchorLine[boundary+(part?-1:0)]).level),anchorLine=index?cm.from:cm.to,boundary=index?"after":"before",anchor.ch==anchorLine&&anchor.sticky==boundary)?range:new Range(new Pos(anchor.line,anchorLine,boundary),head)})(cm,new Range(clipPos(doc,pos),head)),setSelection(doc,normalizeSelection(cm,startCol,ourIndex),sel_mouse)}}var editorSize=display.wrapper.getBoundingClientRect(),counter=0;function done(e){cm.state.selectingText=!1,counter=1/0,e&&(e_preventDefault(e),display.input.focus()),off(display.wrapper.ownerDocument,"mousemove",move),off(display.wrapper.ownerDocument,"mouseup",up),doc.history.lastSelOrigin=null}var move=operation(cm,function(e){(0!==e.buttons&&e_button(e)?function extend(e){var visible,outside,curCount=++counter,cur=posFromMouse(cm,e,!0,"rectangle"==behavior.unit);cur&&(0!=cmp(cur,lastPos)?(cm.curOp.focus=activeElt(),extendTo(cur),visible=visibleLines(display,doc),(cur.line>=visible.to||cur.line<visible.from)&&setTimeout(operation(cm,function(){counter==curCount&&extend(e)}),150)):(outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0)&&setTimeout(operation(cm,function(){counter==curCount&&(display.scroller.scrollTop+=outside,extend(e))}),50))}:done)(e)}),up=operation(cm,done);cm.state.selectingText=up,on(display.wrapper.ownerDocument,"mousemove",move),on(display.wrapper.ownerDocument,"mouseup",up)})(cm,event,pos,behavior)})(cm,pos,repeat,e):e_target(e)==display.scroller&&e_preventDefault(e):2==button?(pos&&extendSelection(cm.doc,pos),setTimeout(function(){return display.input.focus()},20)):3==button&&(captureRightClick?cm.display.input.onContextMenu(e):delayBlurEvent(cm))))}function rangeForUnit(cm,pos,unit){return"char"==unit?new Range(pos,pos):"word"==unit?cm.findWordAt(pos):"line"==unit?new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0))):(unit=unit(cm,pos),new Range(unit.from,unit.to))}function gutterEvent(cm,e,type,prevent){var mX,mY;if(e.touches)mX=e.touches[0].clientX,mY=e.touches[0].clientY;else try{mX=e.clientX,mY=e.clientY}catch(e$1){return!1}if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right))return!1;prevent&&e_preventDefault(e);var display=cm.display,prevent=display.lineDiv.getBoundingClientRect();if(mY>prevent.bottom||!hasHandler(cm,type))return e_defaultPrevented(e);mY-=prevent.top-display.viewOffset;for(var i=0;i<cm.display.gutterSpecs.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX)return signal(cm,type,cm,lineAtHeight(cm.doc,mY),cm.display.gutterSpecs[i].className,e),e_defaultPrevented(e)}}function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",!0)}function onContextMenu(cm,e){eventInWidget(cm.display,e)||((cm,e)=>hasHandler(cm,"gutterContextMenu")&&gutterEvent(cm,e,"gutterContextMenu",!1))(cm,e)||signalDOMEvent(cm,e,"contextmenu")||captureRightClick||cm.display.input.onContextMenu(e)}function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+cm.options.theme.replace(/(^|\s)\s*/g," cm-s-"),clearCaches(cm)}PastClick.prototype.compare=function(time,pos,button){return this.time+400>time&&0==cmp(pos,this.pos)&&button==this.button};var Init={toString:function(){return"CodeMirror.Init"}},defaults={},optionHandlers={};function dragDropChanged(cm,value,old){!value!=!(old&&old!=Init)&&(old=cm.display.dragFunctions,(value=value?on:off)(cm.display.scroller,"dragstart",old.start),value(cm.display.scroller,"dragenter",old.enter),value(cm.display.scroller,"dragover",old.over),value(cm.display.scroller,"dragleave",old.leave),value(cm.display.scroller,"drop",old.drop))}function wrappingChanged(cm){cm.options.lineWrapping?(addClass(cm.display.wrapper,"CodeMirror-wrap"),cm.display.sizer.style.minWidth="",cm.display.sizerWidth=null):(rmClass(cm.display.wrapper,"CodeMirror-wrap"),findMaxLine(cm)),estimateLineHeights(cm),regChange(cm),clearCaches(cm),setTimeout(function(){return updateScrollbars(cm)},100)}function CodeMirror(place,options){var this$1=this;if(!(this instanceof CodeMirror))return new CodeMirror(place,options);this.options=options=options?copyObj(options):{},copyObj(defaults,options,!1);var opt,doc=options.value,input=("string"==typeof doc?doc=new Doc(doc,options.mode,null,options.lineSeparator,options.direction):options.mode&&(doc.modeOption=options.mode),this.doc=doc,new CodeMirror.inputStyles[options.inputStyle](this)),place=this.display=new Display(place,doc,input,options),cm=(themeChanged(place.wrapper.CodeMirror=this),options.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),initScrollbars(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Delayed,keySeq:null,specialChars:null},options.autofocus&&!mobile&&place.input.focus(),ie&&ie_version<11&&setTimeout(function(){return this$1.display.input.reset(!0)},20),this),d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown)),on(d.scroller,"dblclick",ie&&ie_version<11?operation(cm,function(e){var pos;signalDOMEvent(cm,e)||!(pos=posFromMouse(cm,e))||clickInGutter(cm,e)||eventInWidget(cm.display,e)||(e_preventDefault(e),e=cm.findWordAt(pos),extendSelection(cm.doc,e.anchor,e.head))}):function(e){return signalDOMEvent(cm,e)||e_preventDefault(e)}),on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e)}),on(d.input.getField(),"contextmenu",function(e){d.scroller.contains(e.target)||onContextMenu(cm,e)});var touchFinished,prevTouch={end:0};function finishTouch(){d.activeTouch&&(touchFinished=setTimeout(function(){return d.activeTouch=null},1e3),(prevTouch=d.activeTouch).end=+new Date)}function farAway(touch,other){var dx;return null==other.left||400<(dx=other.left-touch.left)*dx+(dx=other.top-touch.top)*dx}on(d.scroller,"touchstart",function(e){var now;signalDOMEvent(cm,e)||(e=>1==e.touches.length&&(e=e.touches[0]).radiusX<=1&&e.radiusY<=1)(e)||clickInGutter(cm,e)||(d.input.ensurePolled(),clearTimeout(touchFinished),now=+new Date,d.activeTouch={start:now,moved:!1,prev:now-prevTouch.end<=300?prevTouch:null},1==e.touches.length&&(d.activeTouch.left=e.touches[0].pageX,d.activeTouch.top=e.touches[0].pageY))}),on(d.scroller,"touchmove",function(){d.activeTouch&&(d.activeTouch.moved=!0)}),on(d.scroller,"touchend",function(e){var pos,touch=d.activeTouch;touch&&!eventInWidget(d,e)&&null!=touch.left&&!touch.moved&&new Date-touch.start<300&&(pos=cm.coordsChar(d.activeTouch,"page"),touch=!touch.prev||farAway(touch,touch.prev)?new Range(pos,pos):!touch.prev.prev||farAway(touch,touch.prev.prev)?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0))),cm.setSelection(touch.anchor,touch.head),cm.focus(),e_preventDefault(e)),finishTouch()}),on(d.scroller,"touchcancel",finishTouch),on(d.scroller,"scroll",function(){d.scroller.clientHeight&&(updateScrollTop(cm,d.scroller.scrollTop),setScrollLeft(cm,d.scroller.scrollLeft,!0),signal(cm,"scroll",cm))}),on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e)}),on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e)}),on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0}),d.dragFunctions={enter:function(e){signalDOMEvent(cm,e)||e_stop(e)},over:function(e){signalDOMEvent(cm,e)||(((cm,e)=>{(e=posFromMouse(cm,e))&&(drawSelectionCursor(cm,e,e=document.createDocumentFragment()),cm.display.dragCursor||(cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)),removeChildrenAndAdd(cm.display.dragCursor,e))})(cm,e),e_stop(e))},start:function(e){return((cm,e)=>{var img;ie&&(!cm.state.draggingText||+new Date-lastDrop<100)?e_stop(e):signalDOMEvent(cm,e)||eventInWidget(cm.display,e)||(e.dataTransfer.setData("Text",cm.getSelection()),e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setDragImage&&!safari&&((img=elt("img",null,null,"position: fixed; left: 0; top: 0;")).src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",presto&&(img.width=img.height=1,cm.display.wrapper.appendChild(img),img._top=img.offsetTop),e.dataTransfer.setDragImage(img,0,0),presto)&&img.parentNode.removeChild(img))})(cm,e)},drop:operation(cm,onDrop),leave:function(e){signalDOMEvent(cm,e)||clearDragCursor(cm)}};input=d.input.getField();for(opt in on(input,"keyup",function(e){return onKeyUp.call(cm,e)}),on(input,"keydown",operation(cm,onKeyDown)),on(input,"keypress",operation(cm,onKeyPress)),on(input,"focus",function(e){return onFocus(cm,e)}),on(input,"blur",function(e){return onBlur(cm,e)}),ensureGlobalHandlers(),startOperation(this),this.curOp.forceUpdate=!0,attachDoc(this,doc),options.autofocus&&!mobile||this.hasFocus()?setTimeout(function(){this$1.hasFocus()&&!this$1.state.focused&&onFocus(this$1)},20):onBlur(this),optionHandlers)optionHandlers.hasOwnProperty(opt)&&optionHandlers[opt](this,options[opt],Init);maybeUpdateLineNumberWidth(this),options.finishInit&&options.finishInit(this);for(var i=0;i<initHooks.length;++i)initHooks[i](this);endOperation(this),webkit&&options.lineWrapping&&"optimizelegibility"==getComputedStyle(place.lineDiv).textRendering&&(place.lineDiv.style.textRendering="auto")}CodeMirror.defaults=defaults,CodeMirror.optionHandlers=optionHandlers;var initHooks=[];function indentLine(cm,n,how,aggressive){var state,doc=cm.doc,tabSize=("smart"==(how=null==how?"add":how)&&(doc.mode.indent?state=getContextBefore(cm,n).state:how="prev"),cm.options.tabSize),line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize),curSpaceString=(line.stateAfter&&(line.stateAfter=null),line.text.match(/^\s*/)[0]);if(aggressive||/\S/.test(line.text)){if("smart"==how&&((indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text))==Pass||150<indentation)){if(!aggressive)return;how="prev"}}else indentation=0,how="not";"prev"==how?indentation=n>doc.first?countColumn(getLine(doc,n-1).text,null,tabSize):0:"add"==how?indentation=curSpace+cm.options.indentUnit:"subtract"==how?indentation=curSpace-cm.options.indentUnit:"number"==typeof how&&(indentation=curSpace+how);var indentation=Math.max(0,indentation),indentString="",pos=0;if(cm.options.indentWithTabs)for(var i=Math.floor(indentation/tabSize);i;--i)pos+=tabSize,indentString+="\t";if(pos<indentation&&(indentString+=spaceStr(indentation-pos)),indentString!=curSpaceString)return replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input"),!(line.stateAfter=null);for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1];if(range.head.line==n&&range.head.ch<curSpaceString.length){range=Pos(n,curSpaceString.length);replaceOneSelection(doc,i$1,new Range(range,range));break}}}CodeMirror.defineInitHook=function(f){return initHooks.push(f)};var lastCopied=null;function setLastCopied(newLastCopied){lastCopied=newLastCopied}function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc,recent=(cm.display.shift=!1,sel=sel||doc.sel,+new Date-200),paste="paste"==origin||cm.state.pasteIncoming>recent,textLines=splitLinesAuto(inserted),multiPaste=null;if(paste&&1<sel.ranges.length)if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0)for(var multiPaste=[],i=0;i<lastCopied.text.length;i++)multiPaste.push(doc.splitLines(lastCopied.text[i]))}else textLines.length==sel.ranges.length&&cm.options.pasteLinesPerSelection&&(multiPaste=map(textLines,function(l){return[l]}));for(var updateInput=cm.curOp.updateInput,i$1=sel.ranges.length-1;0<=i$1;i$1--){var range=sel.ranges[i$1],from=range.from(),to=range.to(),range=(range.empty()&&(deleted&&0<deleted?from=Pos(from.line,from.ch-deleted):cm.state.overwrite&&!paste?to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length)):paste&&lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==textLines.join("\n")&&(from=to=Pos(from.line,0))),{from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming>recent?"cut":"+input")});makeChange(cm.doc,range),signalLater(cm,"inputRead",cm,range)}inserted&&!paste&&triggerElectric(cm,inserted),ensureCursorVisible(cm),cm.curOp.updateInput<2&&(cm.curOp.updateInput=updateInput),cm.curOp.typing=!0,cm.state.pasteIncoming=cm.state.cutIncoming=-1}function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text");return pasted&&(e.preventDefault(),cm.isReadOnly()||cm.options.disableInput||runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste")}),1)}function triggerElectric(cm,inserted){if(cm.options.electricChars&&cm.options.smartIndent)for(var sel=cm.doc.sel,i=sel.ranges.length-1;0<=i;i--){var range=sel.ranges[i];if(!(100<range.head.ch||i&&sel.ranges[i-1].head.line==range.head.line)){var mode=cm.getModeAt(range.head),indented=!1;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)if(-1<inserted.indexOf(mode.electricChars.charAt(j))){indented=indentLine(cm,range.head.line,"smart");break}}else mode.electricInput&&mode.electricInput.test(getLine(cm.doc,range.head.line).text.slice(0,range.head.ch))&&(indented=indentLine(cm,range.head.line,"smart"));indented&&signalLater(cm,"electricInput",cm,range.head.line)}}}function copyableRanges(cm){for(var text=[],ranges=[],i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line,line={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(line),text.push(cm.getRange(line.anchor,line.head))}return{text:text,ranges:ranges}}function disableBrowserMagic(field,spellcheck,autocorrect,autocapitalize){field.setAttribute("autocorrect",autocorrect?"":"off"),field.setAttribute("autocapitalize",autocapitalize?"":"off"),field.setAttribute("spellcheck",!!spellcheck)}function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");return webkit?te.style.width="1000px":te.setAttribute("wrap","off"),ios&&(te.style.border="1px solid black"),disableBrowserMagic(te),div}function findPosH(doc,pos,dir,unit,visually){var oldPos=pos,origDir=dir,lineObj=getLine(doc,pos.line),lineDir=visually&&"rtl"==doc.direction?-dir:dir;function moveOnce(boundToLine){var ch;if(null==(ch="codepoint"==unit?(ch=lineObj.text.charCodeAt(pos.ch+(0<unit?0:-1)),isNaN(ch)?null:new Pos(pos.line,Math.max(0,Math.min(lineObj.text.length,pos.ch+dir*(55296<=ch&&ch<56320?2:1))),-dir)):visually?moveVisually(doc.cm,lineObj,pos,dir):moveLogically(lineObj,pos,dir))){if(boundToLine||(boundToLine=pos.line+lineDir)<doc.first||boundToLine>=doc.first+doc.size||(pos=new Pos(boundToLine,pos.ch,pos.sticky),!(lineObj=getLine(doc,boundToLine))))return;pos=endOfLine(visually,doc.cm,lineObj,pos.line,lineDir)}else pos=ch;return 1}if("char"==unit||"codepoint"==unit)moveOnce();else if("column"==unit)moveOnce(!0);else if("word"==unit||"group"==unit)for(var sawType=null,group="group"==unit,helper=doc.cm&&doc.cm.getHelper(pos,"wordChars"),first=!0;!(dir<0)||moveOnce(!first);first=!1){var cur=lineObj.text.charAt(pos.ch)||"\n",cur=isWordChar(cur,helper)?"w":group&&"\n"==cur?"n":!group||/\s/.test(cur)?null:"p";if(group&&!first&&(cur=cur||"s"),sawType&&sawType!=cur){dir<0&&(dir=1,moveOnce(),pos.sticky="after");break}if(cur&&(sawType=cur),0<dir&&!moveOnce(!first))break}origDir=skipAtomic(doc,pos,oldPos,origDir,!0);return equalCursorPos(oldPos,origDir)&&(origDir.hitSide=!0),origDir}function findPosV(cm,pos,dir,unit){var pageSize,y,target,doc=cm.doc,x=pos.left;for("page"==unit?(pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),pageSize=Math.max(pageSize-.5*textHeight(cm.display),3),y=(0<dir?pos.bottom:pos.top)+dir*pageSize):"line"==unit&&(y=0<dir?pos.bottom+3:pos.top-3);(target=coordsChar(cm,x,y)).outside;){if(dir<0?y<=0:y>=doc.height){target.hitSide=!0;break}y+=5*dir}return target}function ContentEditableInput(cm){this.cm=cm,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new Delayed,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null}function posToDOM(cm,pos){var info,side,view=findViewForLine(cm,pos.line);return!view||view.hidden?null:(info=mapFromLineView(view,view=getLine(cm.doc,pos.line),pos.line),side="left",(view=getOrder(view,cm.doc.direction))&&(side=getBidiPartAt(view,pos.ch)%2?"right":"left"),(cm=nodeAndOffsetInLineMap(info.map,pos.ch,side)).offset="right"==cm.collapse?cm.end:cm.start,cm)}function badPos(pos,bad){return bad&&(pos.bad=!0),pos}function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){if(!(lineNode=cm.display.lineDiv.childNodes[offset]))return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),!0);node=null,offset=0}else for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv)return null;if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv)break}for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)return((lineView,node,offset)=>{var wrapper=lineView.text.firstChild,bad=!1;if(!node||!contains(wrapper,node))return badPos(Pos(lineNo(lineView.line),0),!0);if(node==wrapper)if(bad=!0,node=wrapper.childNodes[offset],offset=0,!node)return badPos(Pos(lineNo(line=lineView.rest?lst(lineView.rest):lineView.line),line.text.length),bad);var line=3==node.nodeType?node:null,topNode=node;for(line||1!=node.childNodes.length||3!=node.firstChild.nodeType||(line=node.firstChild,offset=offset&&line.nodeValue.length);topNode.parentNode!=wrapper;)topNode=topNode.parentNode;var measure=lineView.measure,maps=measure.maps;function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++)for(var map=i<0?measure.map:maps[i],j=0;j<map.length;j+=3){var line,ch,curNode=map[j+2];if(curNode==textNode||curNode==topNode)return line=lineNo(i<0?lineView.line:lineView.rest[i]),ch=map[j]+offset,Pos(line,ch=offset<0||curNode!=textNode?map[j+(offset?1:0)]:ch)}}var found=find(line,topNode,offset);if(found)return badPos(found,bad);for(var after=topNode.nextSibling,dist=line?line.nodeValue.length-offset:0;after;after=after.nextSibling){if(found=find(after,after.firstChild,0))return badPos(Pos(found.line,found.ch-dist),bad);dist+=after.textContent.length}for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){if(found=find(before,before.firstChild,-1))return badPos(Pos(found.line,found.ch+dist$1),bad);dist$1+=before.textContent.length}})(lineView,node,offset)}}ContentEditableInput.prototype.init=function(display){var this$1=this,input=this,cm=input.cm,div=input.div=display.lineDiv;function belongsToInput(e){for(var t=e.target;t;t=t.parentNode){if(t==div)return 1;if(/\bCodeMirror-(?:line)?widget\b/.test(t.className))break}}function onCopyCut(e){if(belongsToInput(e)&&!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()}),"cut"==e.type&&cm.replaceSelection("",null,"cut");else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type&&cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll),cm.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var content=lastCopied.text.join("\n");if(e.clipboardData.setData("Text",content),e.clipboardData.getData("Text")==content)return void e.preventDefault()}var kludge=hiddenTextarea(),content=kludge.firstChild,hadFocus=(cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild),content.value=lastCopied.text.join("\n"),document.activeElement);selectInput(content),setTimeout(function(){cm.display.lineSpace.removeChild(kludge),hadFocus.focus(),hadFocus==div&&input.showPrimarySelection()},50)}}disableBrowserMagic(div,cm.options.spellcheck,cm.options.autocorrect,cm.options.autocapitalize),on(div,"paste",function(e){!belongsToInput(e)||signalDOMEvent(cm,e)||handlePaste(e,cm)||ie_version<=11&&setTimeout(operation(cm,function(){return this$1.updateFromDOM()}),20)}),on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:!1}}),on(div,"compositionupdate",function(e){this$1.composing||(this$1.composing={data:e.data,done:!1})}),on(div,"compositionend",function(e){this$1.composing&&(e.data!=this$1.composing.data&&this$1.readFromDOMSoon(),this$1.composing.done=!0)}),on(div,"touchstart",function(){return input.forceCompositionEnd()}),on(div,"input",function(){this$1.composing||this$1.readFromDOMSoon()}),on(div,"copy",onCopyCut),on(div,"cut",onCopyCut)},ContentEditableInput.prototype.screenReaderLabelChanged=function(label){label?this.div.setAttribute("aria-label",label):this.div.removeAttribute("aria-label")},ContentEditableInput.prototype.prepareSelection=function(){var result=prepareSelection(this.cm,!1);return result.focus=document.activeElement==this.div,result},ContentEditableInput.prototype.showSelection=function(info,takeFocus){info&&this.cm.display.view.length&&((info.focus||takeFocus)&&this.showPrimarySelection(),this.showMultipleSelections(info))},ContentEditableInput.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()},ContentEditableInput.prototype.showPrimarySelection=function(){var sel=this.getSelection(),cm=this.cm,prim=cm.doc.sel.primary(),from=prim.from(),prim=prim.to();if(cm.display.viewTo==cm.display.viewFrom||from.line>=cm.display.viewTo||prim.line<cm.display.viewFrom)sel.removeAllRanges();else{var curAnchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),curFocus=domToPos(cm,sel.focusNode,sel.focusOffset);if(!curAnchor||curAnchor.bad||!curFocus||curFocus.bad||0!=cmp(minPos(curAnchor,curFocus),from)||0!=cmp(maxPos(curAnchor,curFocus),prim)){var curAnchor=cm.display.view,curFocus=from.line>=cm.display.viewFrom&&posToDOM(cm,from)||{node:curAnchor[0].measure.map[2],offset:0},from=prim.line<cm.display.viewTo&&posToDOM(cm,prim);if(from||(from={node:(curAnchor=(prim=curAnchor[curAnchor.length-1].measure).maps?prim.maps[prim.maps.length-1]:prim.map)[curAnchor.length-1],offset:curAnchor[curAnchor.length-2]-curAnchor[curAnchor.length-3]}),curFocus&&from){var rng,prim=sel.rangeCount&&sel.getRangeAt(0);try{rng=range(curFocus.node,curFocus.offset,from.offset,from.node)}catch(e){}rng&&(!gecko&&cm.state.focused&&(sel.collapse(curFocus.node,curFocus.offset),rng.collapsed)||(sel.removeAllRanges(),sel.addRange(rng)),prim&&null==sel.anchorNode?sel.addRange(prim):gecko&&this.startGracePeriod()),this.rememberSelection()}else sel.removeAllRanges()}}},ContentEditableInput.prototype.startGracePeriod=function(){var this$1=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){this$1.gracePeriod=!1,this$1.selectionChanged()&&this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=!0})},20)},ContentEditableInput.prototype.showMultipleSelections=function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors),removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)},ContentEditableInput.prototype.rememberSelection=function(){var sel=this.getSelection();this.lastAnchorNode=sel.anchorNode,this.lastAnchorOffset=sel.anchorOffset,this.lastFocusNode=sel.focusNode,this.lastFocusOffset=sel.focusOffset},ContentEditableInput.prototype.selectionInEditor=function(){var sel=this.getSelection();return!!sel.rangeCount&&(sel=sel.getRangeAt(0).commonAncestorContainer,contains(this.div,sel))},ContentEditableInput.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()&&document.activeElement==this.div||this.showSelection(this.prepareSelection(),!0),this.div.focus())},ContentEditableInput.prototype.blur=function(){this.div.blur()},ContentEditableInput.prototype.getField=function(){return this.div},ContentEditableInput.prototype.supportsTouch=function(){return!0},ContentEditableInput.prototype.receivedFocus=function(){var input=this;this.selectionInEditor()?this.pollSelection():runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,function poll(){input.cm.state.focused&&(input.pollSelection(),input.polling.set(input.cm.options.pollInterval,poll))})},ContentEditableInput.prototype.selectionChanged=function(){var sel=this.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset},ContentEditableInput.prototype.pollSelection=function(){var sel,cm,anchor,head;null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()&&(sel=this.getSelection(),cm=this.cm,android&&chrome&&this.cm.display.gutterSpecs.length&&(node=>{for(var scan=node;scan;scan=scan.parentNode)if(/CodeMirror-gutter-wrapper/.test(scan.className))return 1})(sel.anchorNode)?(this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),this.focus()):this.composing||(this.rememberSelection(),anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),head=domToPos(cm,sel.focusNode,sel.focusOffset),anchor&&head&&runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll),(anchor.bad||head.bad)&&(cm.curOp.selectionChanged=!0)})))},ContentEditableInput.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var fromLine,cm=this.cm,display=cm.display,sel=cm.doc.sel.primary(),from=sel.from(),sel=sel.to();if(0==from.ch&&from.line>cm.firstLine()&&(from=Pos(from.line-1,getLine(cm.doc,from.line-1).length)),sel.ch==getLine(cm.doc,sel.line).text.length&&sel.line<cm.lastLine()&&(sel=Pos(sel.line+1,0)),from.line<display.viewFrom||sel.line>display.viewTo-1)return!1;var toLine,fromIndex=from.line==display.viewFrom||0==(fromIndex=findViewIndex(cm,from.line))?(fromLine=lineNo(display.view[0].line),display.view[0].node):(fromLine=lineNo(display.view[fromIndex].line),display.view[fromIndex-1].node.nextSibling),sel=findViewIndex(cm,sel.line),display=sel==display.view.length-1?(toLine=display.viewTo-1,display.lineDiv.lastChild):(toLine=lineNo(display.view[sel+1].line)-1,display.view[sel+1].node.previousSibling);if(!fromIndex)return!1;for(var newText=cm.doc.splitLines(((cm,from,to,fromLine,toLine)=>{var text="",closing=!1,lineSep=cm.doc.lineSeparator(),extraLinebreak=!1;function close(){closing&&(text+=lineSep,extraLinebreak&&(text+=lineSep),closing=extraLinebreak=!1)}function addText(str){str&&(close(),text+=str)}for(;!function walk(node){if(1==node.nodeType){var cmText=node.getAttribute("cm-text");if(cmText)addText(cmText);else if(cmText=node.getAttribute("cm-marker"))(cmText=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),(id=+cmText,function(marker){return marker.id==id}))).length&&(cmText=cmText[0].find(0))&&addText(getBetween(cm.doc,cmText.from,cmText.to).join(lineSep));else if("false"!=node.getAttribute("contenteditable")&&(cmText=/^(pre|div|p|li|table|br)$/i.test(node.nodeName),/^br$/i.test(node.nodeName)||0!=node.textContent.length)){cmText&&close();for(var i=0;i<node.childNodes.length;i++)walk(node.childNodes[i]);/^(pre|p)$/i.test(node.nodeName)&&(extraLinebreak=!0),cmText&&(closing=!0)}}else 3==node.nodeType&&addText(node.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "));var id}(from),from!=to;)from=from.nextSibling,extraLinebreak=!1;return text})(cm,fromIndex,display,fromLine,toLine)),oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));1<newText.length&&1<oldText.length;)if(lst(newText)==lst(oldText))newText.pop(),oldText.pop(),toLine--;else{if(newText[0]!=oldText[0])break;newText.shift(),oldText.shift(),fromLine++}for(var cutFront=0,cutEnd=0,newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront);)++cutFront;for(var newBot=lst(newText),oldBot=lst(oldText),maxCutEnd=Math.min(newBot.length-(1==newText.length?cutFront:0),oldBot.length-(1==oldText.length?cutFront:0));cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)++cutEnd;if(1==newText.length&&1==oldText.length&&fromLine==from.line)for(;cutFront&&cutFront>from.ch&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)cutFront--,cutEnd++;newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,""),newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"");sel=Pos(fromLine,cutFront),fromIndex=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);return 1<newText.length||newText[0]||cmp(sel,fromIndex)?(replaceRange(cm.doc,newText,sel,fromIndex,"+input"),!0):void 0},ContentEditableInput.prototype.ensurePolled=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.reset=function(){this.forceCompositionEnd()},ContentEditableInput.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},ContentEditableInput.prototype.readFromDOMSoon=function(){var this$1=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(this$1.readDOMTimeout=null,this$1.composing){if(!this$1.composing.done)return;this$1.composing=null}this$1.updateFromDOM()},80))},ContentEditableInput.prototype.updateFromDOM=function(){var this$1=this;!this.cm.isReadOnly()&&this.pollContent()||runInOp(this.cm,function(){return regChange(this$1.cm)})},ContentEditableInput.prototype.setUneditable=function(node){node.contentEditable="false"},ContentEditableInput.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly())||operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0)},ContentEditableInput.prototype.readOnlyChanged=function(val){this.div.contentEditable=String("nocursor"!=val)},ContentEditableInput.prototype.onContextMenu=function(){},ContentEditableInput.prototype.resetPosition=function(){},ContentEditableInput.prototype.needsContentAttribute=!0;function TextareaInput(cm){this.cm=cm,this.prevInput="",this.pollingFast=!1,this.polling=new Delayed,this.hasSelection=!1,this.composing=null}TextareaInput.prototype.init=function(display){var this$1=this,input=this,cm=this.cm,te=(this.createField(display),this.textarea);function prepareCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected())setLastCopied({lineWise:!1,text:cm.getSelections()});else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text}),"cut"==e.type?cm.setSelections(ranges.ranges,null,sel_dontScroll):(input.prevInput="",te.value=ranges.text.join("\n"),selectInput(te))}"cut"==e.type&&(cm.state.cutIncoming=+new Date)}}display.wrapper.insertBefore(this.wrapper,display.wrapper.firstChild),ios&&(te.style.width="0px"),on(te,"input",function(){ie&&9<=ie_version&&this$1.hasSelection&&(this$1.hasSelection=null),input.poll()}),on(te,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)||(cm.state.pasteIncoming=+new Date,input.fastPoll())}),on(te,"cut",prepareCopyCut),on(te,"copy",prepareCopyCut),on(display.scroller,"paste",function(e){var event;eventInWidget(display,e)||signalDOMEvent(cm,e)||(te.dispatchEvent?((event=new Event("paste")).clipboardData=e.clipboardData,te.dispatchEvent(event)):(cm.state.pasteIncoming=+new Date,input.focus()))}),on(display.lineSpace,"selectstart",function(e){eventInWidget(display,e)||e_preventDefault(e)}),on(te,"compositionstart",function(){var start=cm.getCursor("from");input.composing&&input.composing.range.clear(),input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}}),on(te,"compositionend",function(){input.composing&&(input.poll(),input.composing.range.clear(),input.composing=null)})},TextareaInput.prototype.createField=function(_display){this.wrapper=hiddenTextarea(),this.textarea=this.wrapper.firstChild},TextareaInput.prototype.screenReaderLabelChanged=function(label){label?this.textarea.setAttribute("aria-label",label):this.textarea.removeAttribute("aria-label")},TextareaInput.prototype.prepareSelection=function(){var lineOff,cm=this.cm,display=cm.display,doc=cm.doc,result=prepareSelection(cm);return cm.options.moveInputWithCursor&&(cm=cursorCoords(cm,doc.sel.primary().head,"div"),doc=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect(),result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,cm.top+lineOff.top-doc.top)),result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,cm.left+lineOff.left-doc.left))),result},TextareaInput.prototype.showSelection=function(drawn){var display=this.cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors),removeChildrenAndAdd(display.selectionDiv,drawn.selection),null!=drawn.teTop&&(this.wrapper.style.top=drawn.teTop+"px",this.wrapper.style.left=drawn.teLeft+"px")},TextareaInput.prototype.reset=function(typing){var cm,content;this.contextMenuPending||this.composing||((cm=this.cm).somethingSelected()?(this.prevInput="",content=cm.getSelection(),this.textarea.value=content,cm.state.focused&&selectInput(this.textarea),ie&&9<=ie_version&&(this.hasSelection=content)):typing||(this.prevInput=this.textarea.value="",ie&&9<=ie_version&&(this.hasSelection=null)))},TextareaInput.prototype.getField=function(){return this.textarea},TextareaInput.prototype.supportsTouch=function(){return!1},TextareaInput.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!mobile||activeElt()!=this.textarea))try{this.textarea.focus()}catch(e){}},TextareaInput.prototype.blur=function(){this.textarea.blur()},TextareaInput.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},TextareaInput.prototype.receivedFocus=function(){this.slowPoll()},TextareaInput.prototype.slowPoll=function(){var this$1=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){this$1.poll(),this$1.cm.state.focused&&this$1.slowPoll()})},TextareaInput.prototype.fastPoll=function(){var missed=!1,input=this;input.pollingFast=!0,input.polling.set(20,function p(){input.poll()||missed?(input.pollingFast=!1,input.slowPoll()):(missed=!0,input.polling.set(60,p))})},TextareaInput.prototype.poll=function(){var this$1=this,cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||hasSelection(input)&&!prevInput&&!this.composing||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)return!1;var text=input.value;if(text==prevInput&&!cm.somethingSelected())return!1;if(ie&&9<=ie_version&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text))return cm.display.input.reset(),!1;if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);if(8203==first&&(prevInput=prevInput||""),8666==first)return this.reset(),this.cm.execCommand("undo")}for(var same=0,l=Math.min(prevInput.length,text.length);same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same);)++same;return runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null),1e3<text.length||-1<text.indexOf("\n")?input.value=this$1.prevInput="":this$1.prevInput=text,this$1.composing&&(this$1.composing.range.clear(),this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},TextareaInput.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},TextareaInput.prototype.onKeyPress=function(){ie&&9<=ie_version&&(this.hasSelection=null),this.fastPoll()},TextareaInput.prototype.onContextMenu=function(e){var oldCSS,oldWrapperCSS,oldScrollY,mouseup,input=this,cm=input.cm,display=cm.display,te=input.textarea,pos=(input.contextMenuPending&&input.contextMenuPending(),posFromMouse(cm,e)),scrollPos=display.scroller.scrollTop;function prepareSelectAllHack(){var selected,extval;null!=te.selectionStart&&(extval=""+((selected=cm.somethingSelected())?te.value:""),te.value="⇚",te.value=extval,input.prevInput=selected?"":"",te.selectionStart=1,te.selectionEnd=extval.length,display.selForContextMenu=cm.doc.sel)}function rehide(){var i,poll;input.contextMenuPending==rehide&&(input.contextMenuPending=!1,input.wrapper.style.cssText=oldWrapperCSS,te.style.cssText=oldCSS,ie&&ie_version<9&&display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos),null!=te.selectionStart)&&((!ie||ie_version<9)&&prepareSelectAllHack(),i=0,poll=function(){display.selForContextMenu==cm.doc.sel&&0==te.selectionStart&&0<te.selectionEnd&&""==input.prevInput?operation(cm,selectAll)(cm):i++<10?display.detectingSelectAll=setTimeout(poll,500):(display.selForContextMenu=null,display.input.reset())},display.detectingSelectAll=setTimeout(poll,200))}pos&&!presto&&(cm.options.resetSelectionOnContextMenu&&-1==cm.doc.sel.contains(pos)&&operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll),oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText,pos=input.wrapper.offsetParent.getBoundingClientRect(),input.wrapper.style.cssText="position: static",te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-pos.top-5)+"px; left: "+(e.clientX-pos.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",webkit&&(oldScrollY=window.scrollY),display.input.focus(),webkit&&window.scrollTo(null,oldScrollY),display.input.reset(),cm.somethingSelected()||(te.value=input.prevInput=" "),input.contextMenuPending=rehide,display.selForContextMenu=cm.doc.sel,clearTimeout(display.detectingSelectAll),ie&&9<=ie_version&&prepareSelectAllHack(),captureRightClick?(e_stop(e),mouseup=function(){off(window,"mouseup",mouseup),setTimeout(rehide,20)},on(window,"mouseup",mouseup)):setTimeout(rehide,50))},TextareaInput.prototype.readOnlyChanged=function(val){val||this.reset(),this.textarea.disabled="nocursor"==val,this.textarea.readOnly=!!val},TextareaInput.prototype.setUneditable=function(){},TextareaInput.prototype.needsContentAttribute=!1,(CodeMirror=>{var optionHandlers=CodeMirror.optionHandlers;function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt,handle&&(optionHandlers[name]=notOnInit?function(cm,val,old){old!=Init&&handle(cm,val,old)}:handle)}CodeMirror.defineOption=option,CodeMirror.Init=Init,option("value","",function(cm,val){return cm.setValue(val)},!0),option("mode",null,function(cm,val){cm.doc.modeOption=val,loadMode(cm)},!0),option("indentUnit",2,loadMode,!0),option("indentWithTabs",!1),option("smartIndent",!0),option("tabSize",4,function(cm){resetModeState(cm),clearCaches(cm),regChange(cm)},!0),option("lineSeparator",null,function(cm,val){if(cm.doc.lineSep=val){var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(-1==found)break;pos=found+val.length,newBreaks.push(Pos(lineNo,found))}lineNo++});for(var i=newBreaks.length-1;0<=i;i--)replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}}),option("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g"),old!=Init&&cm.refresh()}),option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh()},!0),option("electricChars",!0),option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),option("spellcheck",!1,function(cm,val){return cm.getInputField().spellcheck=val},!0),option("autocorrect",!1,function(cm,val){return cm.getInputField().autocorrect=val},!0),option("autocapitalize",!1,function(cm,val){return cm.getInputField().autocapitalize=val},!0),option("rtlMoveVisually",!windows),option("wholeLineUpdateBefore",!0),option("theme","default",function(cm){themeChanged(cm),updateGutters(cm)},!0),option("keyMap","default",function(cm,val,old){val=getKeyMap(val),old=old!=Init&&getKeyMap(old);old&&old.detach&&old.detach(cm,val),val.attach&&val.attach(cm,old||null)}),option("extraKeys",null),option("configureMouse",null),option("lineWrapping",!1,wrappingChanged,!0),option("gutters",[],function(cm,val){cm.display.gutterSpecs=getGutters(val,cm.options.lineNumbers),updateGutters(cm)},!0),option("fixedGutter",!0,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0",cm.refresh()},!0),option("coverGutterNextToScrollbar",!1,function(cm){return updateScrollbars(cm)},!0),option("scrollbarStyle","native",function(cm){initScrollbars(cm),updateScrollbars(cm),cm.display.scrollbars.setScrollTop(cm.doc.scrollTop),cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},!0),option("lineNumbers",!1,function(cm,val){cm.display.gutterSpecs=getGutters(cm.options.gutters,val),updateGutters(cm)},!0),option("firstLineNumber",1,updateGutters,!0),option("lineNumberFormatter",function(integer){return integer},updateGutters,!0),option("showCursorWhenSelecting",!1,updateSelection,!0),option("resetSelectionOnContextMenu",!0),option("lineWiseCopyCut",!0),option("pasteLinesPerSelection",!0),option("selectionsMayTouch",!1),option("readOnly",!1,function(cm,val){"nocursor"==val&&(onBlur(cm),cm.display.input.blur()),cm.display.input.readOnlyChanged(val)}),option("screenReaderLabel",null,function(cm,val){cm.display.input.screenReaderLabelChanged(val=""===val?null:val)}),option("disableInput",!1,function(cm,val){val||cm.display.input.reset()},!0),option("dragDrop",!0,dragDropChanged),option("allowDropFileTypes",null),option("cursorBlinkRate",530),option("cursorScrollMargin",0),option("cursorHeight",1,updateSelection,!0),option("singleCursorHeightPerLine",!0,updateSelection,!0),option("workTime",100),option("workDelay",100),option("flattenSpans",!0,resetModeState,!0),option("addModeClass",!1,resetModeState,!0),option("pollInterval",100),option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val}),option("historyEventDelay",1250),option("viewportMargin",10,function(cm){return cm.refresh()},!0),option("maxHighlightLength",1e4,resetModeState,!0),option("moveInputWithCursor",!0,function(cm,val){val||cm.display.input.resetPosition()}),option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||""}),option("autofocus",null),option("direction","ltr",function(cm,val){return cm.doc.setDirection(val)},!0),option("phrases",null)})(CodeMirror),(CodeMirror=>{var optionHandlers=CodeMirror.optionHandlers,helpers=CodeMirror.helpers={};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus(),this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option];options[option]==value&&"mode"!=option||(options[option]=value,optionHandlers.hasOwnProperty(option)&&operation(this,optionHandlers[option])(this,value,old),signal(this,"optionChange",this,option))},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map))},removeKeyMap:function(map){for(var maps=this.state.keyMaps,i=0;i<maps.length;++i)if(maps[i]==map||maps[i].name==map)return maps.splice(i,1),!0},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState)throw new Error("Overlays may not be stateful.");for(var array=this.state.overlays,mode={mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:options&&options.priority||0},score=function(overlay){return overlay.priority},pos=0,priority=score(mode);pos<array.length&&score(array[pos])<=priority;)pos++;array.splice(pos,0,mode),this.state.modeGen++,regChange(this)}),removeOverlay:methodOp(function(spec){for(var overlays=this.state.overlays,i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||"string"==typeof spec&&cur.name==spec)return overlays.splice(i,1),this.state.modeGen++,void regChange(this)}}),indentLine:methodOp(function(n,dir,aggressive){"string"!=typeof dir&&"number"!=typeof dir&&(dir=null==dir?this.options.smartIndent?"smart":"prev":dir?"add":"subtract"),isLine(this.doc,n)&&indentLine(this,n,dir,aggressive)}),indentSelection:methodOp(function(how){for(var ranges=this.doc.sel.ranges,end=-1,i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty())range.head.line>end&&(indentLine(this,range.head.line,how,!0),end=range.head.line,i==this.doc.sel.primIndex)&&ensureCursorVisible(this);else{for(var from=range.from(),range=range.to(),start=Math.max(end,from.line),end=Math.min(this.lastLine(),range.line-(range.ch?0:1))+1,j=start;j<end;++j)indentLine(this,j,how);range=this.doc.sel.ranges;0==from.ch&&ranges.length==range.length&&0<range[i].from().ch&&replaceOneSelection(this.doc,i,new Range(from,range[i].to()),sel_dontScroll)}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,!0)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var type,styles=getLineStyles(this,getLine(this.doc,pos.line)),before=0,after=(styles.length-1)/2,ch=pos.ch;if(0==ch)type=styles[2];else for(;;){var mid=before+after>>1;if((mid?styles[2*mid-1]:0)>=ch)after=mid;else{if(!(styles[2*mid+1]<ch)){type=styles[2*mid+2];break}before=1+mid}}pos=type?type.indexOf("overlay "):-1;return pos<0?type:0==pos?null:type.slice(0,pos-1)},getModeAt:function(pos){var mode=this.doc.mode;return mode.innerMode?CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode:mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var found=[];if(helpers.hasOwnProperty(type)){var help=helpers[type],mode=this.getModeAt(pos);if("string"==typeof mode[type])help[mode[type]]&&found.push(help[mode[type]]);else if(mode[type])for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];val&&found.push(val)}else mode.helperType&&help[mode.helperType]?found.push(help[mode.helperType]):help[mode.name]&&found.push(help[mode.name]);for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1];cur.pred(mode,this)&&-1==indexOf(found,cur.val)&&found.push(cur.val)}}return found},getStateAfter:function(line,precise){var doc=this.doc;return getContextBefore(this,(line=clipLine(doc,null==line?doc.first+doc.size-1:line))+1,precise).state},cursorCoords:function(start,mode){var range=this.doc.sel.primary(),start=null==start?range.head:"object"==typeof start?clipPos(this.doc,start):start?range.from():range.to();return cursorCoords(this,start,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){return coordsChar(this,(coords=fromCoordSystem(this,coords,mode||"page")).left,coords.top)},lineAtHeight:function(height,mode){return height=fromCoordSystem(this,{top:height,left:0},mode||"page").top,lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var end=!1,last="number"==typeof line?(last=this.doc.first+this.doc.size-1,line<this.doc.first?line=this.doc.first:last<line&&(line=last,end=!0),getLine(this.doc,line)):line;return intoCoordSystem(this,last,{top:0,left:0},mode||"page",includeWidgets||end).top+(end?this.doc.height-heightAtLine(last):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var hspace,vspace,display=this.display,top=(pos=cursorCoords(this,clipPos(this.doc,pos))).bottom,left=pos.left;node.style.position="absolute",node.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(node),display.sizer.appendChild(node),"over"==vert?top=pos.top:"above"!=vert&&"near"!=vert||(vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth),("above"==vert||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight?top=pos.top-node.offsetHeight:pos.bottom+node.offsetHeight<=vspace&&(top=pos.bottom),left+node.offsetWidth>hspace&&(left=hspace-node.offsetWidth)),node.style.top=top+"px",node.style.left=node.style.right="","right"==horiz?(left=display.sizer.clientWidth-node.offsetWidth,node.style.right="0px"):("left"==horiz?left=0:"middle"==horiz&&(left=(display.sizer.clientWidth-node.offsetWidth)/2),node.style.left=left+"px"),scroll&&(vert=this,vspace={left:left,top:top,right:left+node.offsetWidth,bottom:top+node.offsetHeight},null!=(vspace=calculateScrollPos(vert,vspace)).scrollTop&&updateScrollTop(vert,vspace.scrollTop),null!=vspace.scrollLeft)&&setScrollLeft(vert,vspace.scrollLeft)},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,triggerOnMouseDown:methodOp(onMouseDown),execCommand:function(cmd){if(commands.hasOwnProperty(cmd))return commands[cmd].call(null,this)},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){for(var dir=1,cur=(amount<0&&(dir=-1,amount=-amount),clipPos(this.doc,from)),i=0;i<amount&&!(cur=findPosH(this.doc,cur,dir,unit,visually)).hitSide;++i);return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range){return this$1.display.shift||this$1.doc.extend||range.empty()?findPosH(this$1.doc,range.head,dir,unit,this$1.options.rtlMoveVisually):dir<0?range.from():range.to()},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;sel.somethingSelected()?doc.replaceSelection("",null,"+delete"):deleteNearSelection(this,function(range){var other=findPosH(doc,range.head,dir,unit,!1);return dir<0?{from:other,to:range.head}:{from:range.head,to:other}})}),findPosV:function(from,amount,unit,goalColumn){for(var dir=1,x=goalColumn,cur=(amount<0&&(dir=-1,amount=-amount),clipPos(this.doc,from)),i=0;i<amount;++i){var coords=cursorCoords(this,cur,"div");if(null==x?x=coords.left:coords.left=x,(cur=findPosV(this,coords,dir,unit)).hitSide)break}return cur},moveV:methodOp(function(dir,unit){var this$1=this,doc=this.doc,goals=[],collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected();if(doc.extendSelectionsBy(function(range){var headPos,pos;return collapse?dir<0?range.from():range.to():(headPos=cursorCoords(this$1,range.head,"div"),null!=range.goalColumn&&(headPos.left=range.goalColumn),goals.push(headPos.left),pos=findPosV(this$1,headPos,dir,unit),"page"==unit&&range==doc.sel.primary()&&addToScrollTop(this$1,charCoords(this$1,pos,"div").top-headPos.top),pos)},sel_move),goals.length)for(var i=0;i<doc.sel.ranges.length;i++)doc.sel.ranges[i].goalColumn=goals[i]}),findWordAt:function(pos){var line=getLine(this.doc,pos.line).text,start=pos.ch,end=pos.ch;if(line){for(var helper=this.getHelper(pos,"wordChars"),startChar=("before"!=pos.sticky&&end!=line.length||!start?++end:--start,line.charAt(start)),check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper)}:/\s/.test(startChar)?function(ch){return/\s/.test(ch)}:function(ch){return!/\s/.test(ch)&&!isWordChar(ch)};0<start&&check(line.charAt(start-1));)--start;for(;end<line.length&&check(line.charAt(end));)++end}return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){null!=value&&value==this.state.overwrite||(((this.state.overwrite=!this.state.overwrite)?addClass:rmClass)(this.display.cursorDiv,"CodeMirror-overwrite"),signal(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:methodOp(function(x,y){scrollToCoords(this,x,y)}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range,margin){null==range?(range={from:this.doc.sel.primary().head,to:null},null==margin&&(margin=this.options.cursorScrollMargin)):"number"==typeof range?range={from:Pos(range,0),to:null}:null==range.from&&(range={from:range,to:null}),range.to||(range.to=range.from),range.margin=margin||0,null!=range.from.line?((cm,range)=>{resolveScrollToPos(cm),cm.curOp.scrollToPos=range})(this,range):scrollToCoordsRange(this,range.from,range.to,range.margin)}),setSize:methodOp(function(width,height){function interpret(val){return"number"==typeof val||/^\d+$/.test(String(val))?val+"px":val}var this$1=this,lineNo=(null!=width&&(this.display.wrapper.style.width=interpret(width)),null!=height&&(this.display.wrapper.style.height=interpret(height)),this.options.lineWrapping&&clearLineMeasurementCache(this),this.display.viewFrom);this.doc.iter(lineNo,this.display.viewTo,function(line){if(line.widgets)for(var i=0;i<line.widgets.length;i++)if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo,"widget");break}++lineNo}),this.curOp.forceUpdate=!0,signal(this,"refresh",this)}),operation:function(f){return runInOp(this,f)},startOperation:function(){return startOperation(this)},endOperation:function(){return endOperation(this)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this),this.curOp.forceUpdate=!0,clearCaches(this),scrollToCoords(this,this.doc.scrollLeft,this.doc.scrollTop),updateGutterSpace(this.display),(null==oldHeight||.5<Math.abs(oldHeight-textHeight(this.display))||this.options.lineWrapping)&&estimateLineHeights(this),signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc;return old.cm=null,this.state.selectingText&&this.state.selectingText(),attachDoc(this,doc),clearCaches(this),this.display.input.reset(),scrollToCoords(this,doc.scrollLeft,doc.scrollTop),this.curOp.forceScroll=!0,signalLater(this,"swapDoc",this,old),old}),phrase:function(phraseText){var phrases=this.options.phrases;return phrases&&Object.prototype.hasOwnProperty.call(phrases,phraseText)?phrases[phraseText]:phraseText},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},eventMixin(CodeMirror),CodeMirror.registerHelper=function(type,name,value){helpers.hasOwnProperty(type)||(helpers[type]=CodeMirror[type]={_global:[]}),helpers[type][name]=value},CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value),helpers[type]._global.push({pred:predicate,val:value})}})(CodeMirror);var prop,dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(prop in Doc.prototype)Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0&&(CodeMirror.prototype[prop]=(method=>function(){return method.apply(this.doc,arguments)})(Doc.prototype[prop]));return eventMixin(Doc),CodeMirror.inputStyles={textarea:TextareaInput,contenteditable:ContentEditableInput},CodeMirror.defineMode=function(name){CodeMirror.defaults.mode||"null"==name||(CodeMirror.defaults.mode=name),function(name,mode){2<arguments.length&&(mode.dependencies=Array.prototype.slice.call(arguments,2)),modes[name]=mode}.apply(this,arguments)},CodeMirror.defineMIME=function(mime,spec){mimeModes[mime]=spec},CodeMirror.defineMode("null",function(){return{token:function(stream){return stream.skipToEnd()}}}),CodeMirror.defineMIME("text/plain","null"),CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func},CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func},CodeMirror.fromTextArea=function(textarea,options){var hasFocus;function save(){textarea.value=cm.getValue()}if((options=options?copyObj(options):{}).value=textarea.value,!options.tabindex&&textarea.tabIndex&&(options.tabindex=textarea.tabIndex),!options.placeholder&&textarea.placeholder&&(options.placeholder=textarea.placeholder),null==options.autofocus&&(hasFocus=activeElt(),options.autofocus=hasFocus==textarea||null!=textarea.getAttribute("autofocus")&&hasFocus==document.body),textarea.form&&(on(textarea.form,"submit",save),!options.leaveSubmitMethodAlone)){var form=textarea.form,realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save(),form.submit=realSubmit,form.submit(),form.submit=wrappedSubmit}}catch(e){}}options.finishInit=function(cm){cm.save=save,cm.getTextArea=function(){return textarea},cm.toTextArea=function(){cm.toTextArea=isNaN,save(),textarea.parentNode.removeChild(cm.getWrapperElement()),textarea.style.display="",textarea.form&&(off(textarea.form,"submit",save),options.leaveSubmitMethodAlone||"function"!=typeof textarea.form.submit||(textarea.form.submit=realSubmit))}},textarea.style.display="none";var cm=CodeMirror(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling)},options);return cm},(CodeMirror=>{CodeMirror.off=off,CodeMirror.on=on,CodeMirror.wheelEventPixels=wheelEventPixels,CodeMirror.Doc=Doc,CodeMirror.splitLines=splitLinesAuto,CodeMirror.countColumn=countColumn,CodeMirror.findColumn=findColumn,CodeMirror.isWordChar=isWordCharBasic,CodeMirror.Pass=Pass,CodeMirror.signal=signal,CodeMirror.Line=Line,CodeMirror.changeEnd=changeEnd,CodeMirror.scrollbarModel=scrollbarModel,CodeMirror.Pos=Pos,CodeMirror.cmpPos=cmp,CodeMirror.modes=modes,CodeMirror.mimeModes=mimeModes,CodeMirror.resolveMode=resolveMode,CodeMirror.getMode=getMode,CodeMirror.modeExtensions=modeExtensions,CodeMirror.extendMode=extendMode,CodeMirror.copyState=copyState,CodeMirror.startState=startState,CodeMirror.innerMode=innerMode,CodeMirror.commands=commands,CodeMirror.keyMap=keyMap,CodeMirror.keyName=keyName,CodeMirror.isModifierKey=isModifierKey,CodeMirror.lookupKey=lookupKey,CodeMirror.normalizeKeyMap=normalizeKeyMap,CodeMirror.StringStream=StringStream,CodeMirror.SharedTextMarker=SharedTextMarker,CodeMirror.TextMarker=TextMarker,CodeMirror.LineWidget=LineWidget,CodeMirror.e_preventDefault=e_preventDefault,CodeMirror.e_stopPropagation=e_stopPropagation,CodeMirror.e_stop=e_stop,CodeMirror.addClass=addClass,CodeMirror.contains=contains,CodeMirror.rmClass=rmClass,CodeMirror.keyNames=keyNames})(CodeMirror),CodeMirror.version="5.58.3",CodeMirror}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function drawRulers(cm){cm.state.rulerDiv.textContent="";var val=cm.getOption("rulers"),cw=cm.defaultCharWidth(),left=cm.charCoords(CodeMirror.Pos(cm.firstLine(),0),"div").left;cm.state.rulerDiv.style.minHeight=cm.display.scroller.offsetHeight+30+"px";for(var i=0;i<val.length;i++){var elt=document.createElement("div");elt.className="CodeMirror-ruler";var col,conf=val[i];"number"==typeof conf?col=conf:(col=conf.column,conf.className&&(elt.className+=" "+conf.className),conf.color&&(elt.style.borderColor=conf.color),conf.lineStyle&&(elt.style.borderLeftStyle=conf.lineStyle),conf.width&&(elt.style.borderLeftWidth=conf.width)),elt.style.left=left+col*cw+"px",cm.state.rulerDiv.appendChild(elt)}}CodeMirror.defineOption("rulers",!1,function(cm,val){cm.state.rulerDiv&&(cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv),cm.state.rulerDiv=null,cm.off("refresh",drawRulers)),val&&val.length&&(cm.state.rulerDiv=cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"),cm.display.lineSpace),cm.state.rulerDiv.className="CodeMirror-rulers",drawRulers(cm),cm.on("refresh",drawRulers))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function onChange(cm,change){CodeMirror.changeEnd(change).line==cm.lastLine()&&updateBottomMargin(cm)}function updateBottomMargin(cm){var padding="";1<cm.lineCount()&&(padding=cm.display.scroller.clientHeight-30-cm.getLineHandle(cm.lastLine()).height+"px"),cm.state.scrollPastEndPadding!=padding&&(cm.state.scrollPastEndPadding=padding,cm.display.lineSpace.parentNode.style.paddingBottom=padding,cm.off("refresh",updateBottomMargin),cm.setSize(),cm.on("refresh",updateBottomMargin))}CodeMirror.defineOption("scrollPastEnd",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.off("change",onChange),cm.off("refresh",updateBottomMargin),cm.display.lineSpace.parentNode.style.paddingBottom="",cm.state.scrollPastEndPadding=null),val&&(cm.on("change",onChange),cm.on("refresh",updateBottomMargin),updateBottomMargin(cm))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function doFold(cm,pos,options,force){options&&options.call?(finder=options,options=null):finder=getOption(cm,options,"rangeFinder"),"number"==typeof pos&&(pos=CodeMirror.Pos(pos,0));var finder,minSize=getOption(cm,options,"minFoldSize");function getRange(allowFolded){var range=finder(cm,pos);if(!range||range.to.line-range.from.line<minSize)return null;for(var marks=cm.findMarksAt(range.from),i=0;i<marks.length;++i)if(marks[i].__isFold&&"fold"!==force){if(!allowFolded)return null;range.cleared=!0,marks[i].clear()}return range}var myWidget,myRange,range=getRange(!0);if(getOption(cm,options,"scanUp"))for(;!range&&pos.line>cm.firstLine();)pos=CodeMirror.Pos(pos.line-1,0),range=getRange(!1);range&&!range.cleared&&"unfold"!==force&&(myWidget=((cm,options,range)=>("string"==typeof(cm="function"==typeof(cm=getOption(cm,options,"widget"))?cm(range.from,range.to):cm)?(options=document.createTextNode(cm),(cm=document.createElement("span")).appendChild(options),cm.className="CodeMirror-foldmarker"):cm=cm&&cm.cloneNode(!0),cm))(cm,options,range),CodeMirror.on(myWidget,"mousedown",function(e){myRange.clear(),CodeMirror.e_preventDefault(e)}),(myRange=cm.markText(range.from,range.to,{replacedWith:myWidget,clearOnEnter:getOption(cm,options,"clearOnEnter"),__isFold:!0})).on("clear",function(from,to){CodeMirror.signal(cm,"unfold",cm,from,to)}),CodeMirror.signal(cm,"fold",cm,range.from,range.to))}CodeMirror.newFoldFunction=function(rangeFinder,widget){return function(cm,pos){doFold(cm,pos,{rangeFinder:rangeFinder,widget:widget})}},CodeMirror.defineExtension("foldCode",function(pos,options,force){doFold(this,pos,options,force)}),CodeMirror.defineExtension("isFolded",function(pos){for(var marks=this.findMarksAt(pos),i=0;i<marks.length;++i)if(marks[i].__isFold)return!0}),CodeMirror.commands.toggleFold=function(cm){cm.foldCode(cm.getCursor())},CodeMirror.commands.fold=function(cm){cm.foldCode(cm.getCursor(),null,"fold")},CodeMirror.commands.unfold=function(cm){cm.foldCode(cm.getCursor(),null,"unfold")},CodeMirror.commands.foldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"fold")})},CodeMirror.commands.unfoldAll=function(cm){cm.operation(function(){for(var i=cm.firstLine(),e=cm.lastLine();i<=e;i++)cm.foldCode(CodeMirror.Pos(i,0),null,"unfold")})},CodeMirror.registerHelper("fold","combine",function(){var funcs=Array.prototype.slice.call(arguments,0);return function(cm,start){for(var i=0;i<funcs.length;++i){var found=funcs[i](cm,start);if(found)return found}}}),CodeMirror.registerHelper("fold","auto",function(cm,start){for(var helpers=cm.getHelpers(start,"fold"),i=0;i<helpers.length;i++){var cur=helpers[i](cm,start);if(cur)return cur}});var defaultOptions={rangeFinder:CodeMirror.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};function getOption(cm,options,name){return(options&&void 0!==options[name]||(options=cm.options.foldOptions)&&void 0!==options[name]?options:defaultOptions)[name]}CodeMirror.defineOption("foldOptions",null),CodeMirror.defineExtension("foldOption",function(options,name){return getOption(this,options,name)})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./foldcode")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./foldcode"],mod):mod(CodeMirror)})(function(CodeMirror){CodeMirror.defineOption("foldGutter",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.clearGutter(cm.state.foldGutter.options.gutter),cm.state.foldGutter=null,cm.off("gutterClick",onGutterClick),cm.off("changes",onChange),cm.off("viewportChange",onViewportChange),cm.off("fold",onFold),cm.off("unfold",onFold),cm.off("swapDoc",onChange)),val&&(cm.state.foldGutter=new State((opts=>(null==(opts=!0===opts?{}:opts).gutter&&(opts.gutter="CodeMirror-foldgutter"),null==opts.indicatorOpen&&(opts.indicatorOpen="CodeMirror-foldgutter-open"),null==opts.indicatorFolded&&(opts.indicatorFolded="CodeMirror-foldgutter-folded"),opts))(val)),updateInViewport(cm),cm.on("gutterClick",onGutterClick),cm.on("changes",onChange),cm.on("viewportChange",onViewportChange),cm.on("fold",onFold),cm.on("unfold",onFold),cm.on("swapDoc",onChange))});var Pos=CodeMirror.Pos;function State(options){this.options=options,this.from=this.to=0}function isFolded(cm,line){for(var marks=cm.findMarks(Pos(line,0),Pos(line+1,0)),i=0;i<marks.length;++i)if(marks[i].__isFold){var fromPos=marks[i].find(-1);if(fromPos&&fromPos.line===line)return marks[i]}}function marker(spec){var elt;return"string"==typeof spec?((elt=document.createElement("div")).className=spec+" CodeMirror-guttermarker-subtle",elt):spec.cloneNode(!0)}function updateFoldInfo(cm,from,to){var opts=cm.state.foldGutter.options,cur=from-1,minSize=cm.foldOption(opts,"minFoldSize"),func=cm.foldOption(opts,"rangeFinder"),clsFolded="string"==typeof opts.indicatorFolded&&classTest(opts.indicatorFolded),clsOpen="string"==typeof opts.indicatorOpen&&classTest(opts.indicatorOpen);cm.eachLine(from,to,function(line){++cur;var mark=null,old=(old=line.gutterMarkers)&&old[opts.gutter];if(isFolded(cm,cur)){if(clsFolded&&old&&clsFolded.test(old.className))return;mark=marker(opts.indicatorFolded)}else{var pos=Pos(cur,0),pos=func&&func(cm,pos);if(pos&&pos.to.line-pos.from.line>=minSize){if(clsOpen&&old&&clsOpen.test(old.className))return;mark=marker(opts.indicatorOpen)}}(mark||old)&&cm.setGutterMarker(line,opts.gutter,mark)})}function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}function updateInViewport(cm){var vp=cm.getViewport(),state=cm.state.foldGutter;state&&(cm.operation(function(){updateFoldInfo(cm,vp.from,vp.to)}),state.from=vp.from,state.to=vp.to)}function onGutterClick(cm,line,gutter){var state=cm.state.foldGutter;state&&gutter==(gutter=state.options).gutter&&((state=isFolded(cm,line))?state.clear():cm.foldCode(Pos(line,0),gutter))}function onChange(cm){var opts,state=cm.state.foldGutter;state&&(opts=state.options,state.from=state.to=0,clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){updateInViewport(cm)},opts.foldOnChangeTimeSpan||600))}function onViewportChange(cm){var opts,state=cm.state.foldGutter;state&&(opts=state.options,clearTimeout(state.changeUpdate),state.changeUpdate=setTimeout(function(){var vp=cm.getViewport();state.from==state.to||20<vp.from-state.to||20<state.from-vp.to?updateInViewport(cm):cm.operation(function(){vp.from<state.from&&(updateFoldInfo(cm,vp.from,state.from),state.from=vp.from),vp.to>state.to&&(updateFoldInfo(cm,state.to,vp.to),state.to=vp.to)})},opts.updateViewportTimeSpan||400))}function onFold(cm,from){var state=cm.state.foldGutter;state&&(from=from.line)>=state.from&&from<state.to&&updateFoldInfo(cm,from,from+1)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var noOptions={},nonWS=/[^\s\u00a0]/,Pos=CodeMirror.Pos,cmp=CodeMirror.cmpPos;function firstNonWS(str){str=str.search(nonWS);return-1==str?0:str}function getMode(cm,pos){var mode=cm.getMode();return!1!==mode.useInnerComments&&mode.innerMode?cm.getModeAt(pos):mode}CodeMirror.commands.toggleComment=function(cm){cm.toggleComment()},CodeMirror.defineExtension("toggleComment",function(options){options=options||noOptions;for(var minLine=1/0,ranges=this.listSelections(),mode=null,i=ranges.length-1;0<=i;i--){var from=ranges[i].from(),to=ranges[i].to();from.line>=minLine||(to.line>=minLine&&(to=Pos(minLine,0)),minLine=from.line,null==mode?mode=this.uncomment(from,to,options)?"un":(this.lineComment(from,to,options),"line"):"un"==mode?this.uncomment(from,to,options):this.lineComment(from,to,options))}}),CodeMirror.defineExtension("lineComment",function(from,to,options){options=options||noOptions;var commentString,end,pad,blankLines,self=this,mode=getMode(self,from),firstLine=self.getLine(from.line);null!=firstLine&&(firstLine=firstLine,!/\bstring\b/.test(self.getTokenTypeAt(Pos(from.line,0)))||/^[\'\"\`]/.test(firstLine))&&((commentString=options.lineComment||mode.lineComment)?(end=Math.min(0!=to.ch||to.line==from.line?to.line+1:to.line,self.lastLine()+1),pad=null==options.padding?" ":options.padding,blankLines=options.commentBlankLines||from.line==to.line,self.operation(function(){if(options.indent){for(var baseString=null,i=from.line;i<end;++i){var whitespace=(line=self.getLine(i)).slice(0,firstNonWS(line));(null==baseString||baseString.length>whitespace.length)&&(baseString=whitespace)}for(i=from.line;i<end;++i){var line=self.getLine(i),cut=baseString.length;(blankLines||nonWS.test(line))&&(line.slice(0,cut)!=baseString&&(cut=firstNonWS(line)),self.replaceRange(baseString+commentString+pad,Pos(i,0),Pos(i,cut)))}}else for(i=from.line;i<end;++i)(blankLines||nonWS.test(self.getLine(i)))&&self.replaceRange(commentString+pad,Pos(i,0))})):(options.blockCommentStart||mode.blockCommentStart)&&(options.fullLines=!0,self.blockComment(from,to,options)))}),CodeMirror.defineExtension("blockComment",function(from,to,options){options=options||noOptions;var end,pad,self=this,mode=getMode(self,from),startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;startString&&endString?/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line,0)))||((end=Math.min(to.line,self.lastLine()))!=from.line&&0==to.ch&&nonWS.test(self.getLine(end))&&--end,pad=null==options.padding?" ":options.padding,end<from.line)||self.operation(function(){if(0!=options.fullLines){var lastLineHasText=nonWS.test(self.getLine(end)),lead=(self.replaceRange(pad+endString,Pos(end)),self.replaceRange(startString+pad,Pos(from.line,0)),options.blockCommentLead||mode.blockCommentLead);if(null!=lead)for(var i=from.line+1;i<=end;++i)i==end&&!lastLineHasText||self.replaceRange(lead+pad,Pos(i,0))}else{var atCursor=0==cmp(self.getCursor("to"),to),empty=!self.somethingSelected();self.replaceRange(endString,to),atCursor&&self.setSelection(empty?to:self.getCursor("from"),to),self.replaceRange(startString,from)}}):(options.lineComment||mode.lineComment)&&0!=options.fullLines&&self.lineComment(from,to,options)}),CodeMirror.defineExtension("uncomment",function(from,to,options){options=options||noOptions;var didSomething,self=this,mode=getMode(self,from),end=Math.min(0!=to.ch||to.line==from.line?to.line:to.line-1,self.lastLine()),start=Math.min(from.line,end),lineString=options.lineComment||mode.lineComment,lines=[],pad=null==options.padding?" ":options.padding;lineComment:if(lineString){for(var i=start;i<=end;++i){var line=self.getLine(i),found=line.indexOf(lineString);if(-1==(found=-1<found&&!/comment/.test(self.getTokenTypeAt(Pos(i,found+1)))?-1:found)&&nonWS.test(line))break lineComment;if(-1<found&&nonWS.test(line.slice(0,found)))break lineComment;lines.push(line)}if(self.operation(function(){for(var i=start;i<=end;++i){var line=lines[i-start],pos=line.indexOf(lineString),endPos=pos+lineString.length;pos<0||(line.slice(endPos,endPos+pad.length)==pad&&(endPos+=pad.length),didSomething=!0,self.replaceRange("",Pos(i,pos),Pos(i,endPos)))}}),didSomething)return!0}var lead,startLine,open,endLine,close,startString=options.blockCommentStart||mode.blockCommentStart,endString=options.blockCommentEnd||mode.blockCommentEnd;return!(!startString||!endString||(lead=options.blockCommentLead||mode.blockCommentLead,startLine=self.getLine(start),-1==(open=startLine.indexOf(startString)))||(endLine=end==start?startLine:self.getLine(end),close=endLine.indexOf(endString,end==start?open+startString.length:0),options=Pos(start,open+1),mode=Pos(end,close+1),-1==close)||!/comment/.test(self.getTokenTypeAt(options))||!/comment/.test(self.getTokenTypeAt(mode))||-1<self.getRange(options,mode,"\n").indexOf(endString)||(mode=-1==(options=startLine.lastIndexOf(startString,from.ch))?-1:startLine.slice(0,from.ch).indexOf(endString,options+startString.length),-1!=options&&-1!=mode&&mode+endString.length!=from.ch)||(mode=endLine.indexOf(endString,to.ch),from=endLine.slice(to.ch).lastIndexOf(startString,mode-to.ch),options=-1==mode||-1==from?-1:to.ch+from,-1!=mode&&-1!=options&&options!=to.ch)||(self.operation(function(){self.replaceRange("",Pos(end,close-(pad&&endLine.slice(close-pad.length,close)==pad?pad.length:0)),Pos(end,close+endString.length));var openEnd=open+startString.length;if(pad&&startLine.slice(openEnd,openEnd+pad.length)==pad&&(openEnd+=pad.length),self.replaceRange("",Pos(start,open),Pos(start,openEnd)),lead)for(var i=start+1;i<=end;++i){var foundEnd,line=self.getLine(i),found=line.indexOf(lead);-1==found||nonWS.test(line.slice(0,found))||(foundEnd=found+lead.length,pad&&line.slice(foundEnd,foundEnd+pad.length)==pad&&(foundEnd+=pad.length),self.replaceRange("",Pos(i,found),Pos(i,foundEnd)))}}),0))})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function dialogDiv(cm,template,bottom){var cm=cm.getWrapperElement(),dialog=cm.appendChild(document.createElement("div"));return dialog.className=bottom?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof template?dialog.innerHTML=template:dialog.appendChild(template),CodeMirror.addClass(cm,"dialog-opened"),dialog}function closeNotification(cm,newVal){cm.state.currentNotificationClose&&cm.state.currentNotificationClose(),cm.state.currentNotificationClose=newVal}CodeMirror.defineExtension("openDialog",function(template,callback,options){options=options||{},closeNotification(this,null);var dialog=dialogDiv(this,template,options.bottom),closed=!1,me=this;function close(newVal){"string"==typeof newVal?inp.value=newVal:closed||(closed=!0,CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog),me.focus(),options.onClose&&options.onClose(dialog))}var inp=dialog.getElementsByTagName("input")[0];return inp?(inp.focus(),options.value&&(inp.value=options.value,!1!==options.selectValueOnOpen)&&inp.select(),options.onInput&&CodeMirror.on(inp,"input",function(e){options.onInput(e,inp.value,close)}),options.onKeyUp&&CodeMirror.on(inp,"keyup",function(e){options.onKeyUp(e,inp.value,close)}),CodeMirror.on(inp,"keydown",function(e){options&&options.onKeyDown&&options.onKeyDown(e,inp.value,close)||((27==e.keyCode||!1!==options.closeOnEnter&&13==e.keyCode)&&(inp.blur(),CodeMirror.e_stop(e),close()),13==e.keyCode&&callback(inp.value,e))}),!1!==options.closeOnBlur&&CodeMirror.on(dialog,"focusout",function(evt){null!==evt.relatedTarget&&close()})):(template=dialog.getElementsByTagName("button")[0])&&(CodeMirror.on(template,"click",function(){close(),me.focus()}),!1!==options.closeOnBlur&&CodeMirror.on(template,"blur",close),template.focus()),close}),CodeMirror.defineExtension("openConfirm",function(template,callbacks,options){closeNotification(this,null);var dialog=dialogDiv(this,template,options&&options.bottom),buttons=dialog.getElementsByTagName("button"),closed=!1,me=this,blurring=1;function close(){closed||(closed=!0,CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog),me.focus())}buttons[0].focus();for(var i=0;i<buttons.length;++i){var b=buttons[i];(callback=>{CodeMirror.on(b,"click",function(e){CodeMirror.e_preventDefault(e),close(),callback&&callback(me)})})(callbacks[i]),CodeMirror.on(b,"blur",function(){--blurring,setTimeout(function(){blurring<=0&&close()},200)}),CodeMirror.on(b,"focus",function(){++blurring})}}),CodeMirror.defineExtension("openNotification",function(template,options){closeNotification(this,close);var doneTimer,dialog=dialogDiv(this,template,options&&options.bottom),closed=!1,template=options&&void 0!==options.duration?options.duration:5e3;function close(){closed||(closed=!0,clearTimeout(doneTimer),CodeMirror.rmClass(dialog.parentNode,"dialog-opened"),dialog.parentNode.removeChild(dialog))}return CodeMirror.on(dialog,"click",function(e){CodeMirror.e_preventDefault(e),close()}),template&&(doneTimer=setTimeout(close,template)),close})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./searchcursor"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../dialog/dialog"],mod):mod(CodeMirror)})(function(CodeMirror){function SearchState(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function getSearchState(cm){return cm.state.search||(cm.state.search=new SearchState)}function queryCaseInsensitive(query){return"string"==typeof query&&query==query.toLowerCase()}function getSearchCursor(cm,query,pos){return cm.getSearchCursor(query,pos,{caseFold:queryCaseInsensitive(query),multiline:!0})}function dialog(cm,text,shortText,deflt,f){cm.openDialog?cm.openDialog(text,f,{value:deflt,selectValueOnOpen:!0}):f(prompt(shortText,deflt))}function parseString(string){return string.replace(/\\([nrt\\])/g,function(match,ch){return"n"==ch?"\n":"r"==ch?"\r":"t"==ch?"\t":"\\"==ch?"\\":match})}function parseQuery(query){var isRE=query.match(/^\/(.*)\/([a-z]*)$/);if(isRE)try{query=new RegExp(isRE[1],-1==isRE[2].indexOf("i")?"":"i")}catch(e){}else query=parseString(query);return query=("string"==typeof query?""==query:query.test(""))?/x^/:query}function startSearch(cm,state,query){state.queryText=query,state.query=parseQuery(query),cm.removeOverlay(state.overlay,queryCaseInsensitive(state.query)),state.overlay=((query,caseInsensitive)=>("string"==typeof query?query=new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),caseInsensitive?"gi":"g"):query.global||(query=new RegExp(query.source,query.ignoreCase?"gi":"g")),{token:function(stream){query.lastIndex=stream.pos;var match=query.exec(stream.string);if(match&&match.index==stream.pos)return stream.pos+=match[0].length||1,"searching";match?stream.pos=match.index:stream.skipToEnd()}}))(state.query,queryCaseInsensitive(state.query)),cm.addOverlay(state.overlay),cm.showMatchesOnScrollbar&&(state.annotate&&(state.annotate.clear(),state.annotate=null),state.annotate=cm.showMatchesOnScrollbar(state.query,queryCaseInsensitive(state.query)))}function doSearch(cm,rev,persistent,immediate){var state=getSearchState(cm);if(state.query)return findNext(cm,rev);var hiding,searchNext,q=cm.getSelection()||state.lastQuery;q instanceof RegExp&&"x^"==q.source&&(q=null),persistent&&cm.openDialog?(hiding=null,searchNext=function(query,event){CodeMirror.e_stop(event),query&&(query!=state.queryText&&(startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor()),hiding&&(hiding.style.opacity=1),findNext(cm,event.shiftKey,function(_,to){var dialog;to.line<3&&document.querySelector&&(dialog=cm.display.wrapper.querySelector(".CodeMirror-dialog"))&&dialog.getBoundingClientRect().bottom-4>cm.cursorCoords(to,"window").top&&((hiding=dialog).style.opacity=.4)}))},((cm,text,deflt,onEnter,onKeyDown)=>{cm.openDialog(text,onEnter,{value:deflt,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){clearSearch(cm)},onKeyDown:onKeyDown})})(cm,getQueryDialog(cm),q,searchNext,function(event,query){var keyName=CodeMirror.keyName(event),extra=cm.getOption("extraKeys"),extra=extra&&extra[keyName]||CodeMirror.keyMap[cm.getOption("keyMap")][keyName];"findNext"==extra||"findPrev"==extra||"findPersistentNext"==extra||"findPersistentPrev"==extra?(CodeMirror.e_stop(event),startSearch(cm,getSearchState(cm),query),cm.execCommand(extra)):"find"!=extra&&"findPersistent"!=extra||(CodeMirror.e_stop(event),searchNext(query,event))}),immediate&&q&&(startSearch(cm,state,q),findNext(cm,rev))):dialog(cm,getQueryDialog(cm),"Search for:",q,function(query){query&&!state.query&&cm.operation(function(){startSearch(cm,state,query),state.posFrom=state.posTo=cm.getCursor(),findNext(cm,rev)})})}function findNext(cm,rev,callback){cm.operation(function(){var state=getSearchState(cm),cursor=getSearchCursor(cm,state.query,rev?state.posFrom:state.posTo);(cursor.find(rev)||(cursor=getSearchCursor(cm,state.query,rev?CodeMirror.Pos(cm.lastLine()):CodeMirror.Pos(cm.firstLine(),0))).find(rev))&&(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()},20),state.posFrom=cursor.from(),state.posTo=cursor.to(),callback)&&callback(cursor.from(),cursor.to())})}function clearSearch(cm){cm.operation(function(){var state=getSearchState(cm);state.lastQuery=state.query,state.query&&(state.query=state.queryText=null,cm.removeOverlay(state.overlay),state.annotate)&&(state.annotate.clear(),state.annotate=null)})}function getQueryDialog(cm){return'<span class="CodeMirror-search-label">'+cm.phrase("Search:")+'</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use /re/ syntax for regexp search)")+"</span>"}function replaceAll(cm,query,text){cm.operation(function(){for(var match,cursor=getSearchCursor(cm,query);cursor.findNext();)"string"!=typeof query?(match=cm.getRange(cursor.from(),cursor.to()).match(query),cursor.replace(text.replace(/\$(\d)/g,function(_,i){return match[i]}))):cursor.replace(text)})}function replace(cm,all){var query,dialogText;cm.getOption("readOnly")||(query=cm.getSelection()||getSearchState(cm).lastQuery,dialogText='<span class="CodeMirror-search-label">'+(all?cm.phrase("Replace all:"):cm.phrase("Replace:"))+"</span>",dialog(cm,dialogText+' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use /re/ syntax for regexp search)")+"</span>",dialogText,query,function(query){query&&(query=parseQuery(query),dialog(cm,'<span class="CodeMirror-search-label">'+cm.phrase("With:")+'</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>',cm.phrase("Replace with:"),"",function(text){var cursor,advance,doReplace;text=parseString(text),all?replaceAll(cm,query,text):(clearSearch(cm),cursor=getSearchCursor(cm,query,cm.getCursor("from")),doReplace=function(match){cursor.replace("string"==typeof query?text:text.replace(/\$(\d)/g,function(_,i){return match[i]})),advance()},(advance=function(){var match,start=cursor.from();!(match=cursor.findNext())&&(cursor=getSearchCursor(cm,query),!(match=cursor.findNext())||start&&cursor.from().line==start.line&&cursor.from().ch==start.ch)||(cm.setSelection(cursor.from(),cursor.to()),cm.scrollIntoView({from:cursor.from(),to:cursor.to()}),((cm,text,shortText,fs)=>{cm.openConfirm?cm.openConfirm(text,fs):confirm(shortText)&&fs[0]()})(cm,(cm=>'<span class="CodeMirror-search-label">'+cm.phrase("Replace?")+"</span> <button>"+cm.phrase("Yes")+"</button> <button>"+cm.phrase("No")+"</button> <button>"+cm.phrase("All")+"</button> <button>"+cm.phrase("Stop")+"</button> ")(cm),cm.phrase("Replace?"),[function(){doReplace(match)},advance,function(){replaceAll(cm,query,text)}]))})())}))}))}CodeMirror.commands.find=function(cm){clearSearch(cm),doSearch(cm)},CodeMirror.commands.findPersistent=function(cm){clearSearch(cm),doSearch(cm,!1,!0)},CodeMirror.commands.findPersistentNext=function(cm){doSearch(cm,!1,!0,!0)},CodeMirror.commands.findPersistentPrev=function(cm){doSearch(cm,!0,!0,!0)},CodeMirror.commands.findNext=doSearch,CodeMirror.commands.findPrev=function(cm){doSearch(cm,!0)},CodeMirror.commands.clearSearch=clearSearch,CodeMirror.commands.replace=replace,CodeMirror.commands.replaceAll=function(cm){replace(cm,!0)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var doFold,noFold,Pos=CodeMirror.Pos;function ensureFlags(regexp,flags){for(var current=(regexp=>{var flags=regexp.flags;return null!=flags?flags:(regexp.ignoreCase?"i":"")+(regexp.global?"g":"")+(regexp.multiline?"m":"")})(regexp),target=current,i=0;i<flags.length;i++)-1==target.indexOf(flags.charAt(i))&&(target+=flags.charAt(i));return current==target?regexp:new RegExp(regexp.source,target)}function maybeMultiline(regexp){return/\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)}function searchRegexpForward(doc,regexp,start){regexp=ensureFlags(regexp,"g");for(var line=start.line,ch=start.ch,last=doc.lastLine();line<=last;line++,ch=0){regexp.lastIndex=ch;var string=doc.getLine(line),string=regexp.exec(string);if(string)return{from:Pos(line,string.index),to:Pos(line,string.index+string[0].length),match:string}}}function searchRegexpForwardMultiline(doc,regexp,start){if(!maybeMultiline(regexp))return searchRegexpForward(doc,regexp,start);regexp=ensureFlags(regexp,"gm");for(var chunk=1,line=start.line,last=doc.lastLine();line<=last;){for(var i=0;i<chunk&&!(last<line);i++)var curLine=doc.getLine(line++),string=null==string?curLine:string+"\n"+curLine;chunk*=2,regexp.lastIndex=start.ch;var inside,startLine,before,match=regexp.exec(string);if(match)return before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=start.line+before.length-1,before=before[before.length-1].length,{from:Pos(startLine,before),to:Pos(startLine+inside.length-1,1==inside.length?before+inside[0].length:inside[inside.length-1].length),match:match}}}function lastMatchIn(string,regexp,endMargin){for(var match,from=0;from<=string.length;){regexp.lastIndex=from;var newMatch=regexp.exec(string);if(!newMatch)break;var end=newMatch.index+newMatch[0].length;if(end>string.length-endMargin)break;(!match||end>match.index+match[0].length)&&(match=newMatch),from=newMatch.index+1}return match}function searchRegexpBackward(doc,regexp,start){regexp=ensureFlags(regexp,"g");for(var line=start.line,ch=start.ch,first=doc.firstLine();first<=line;line--,ch=-1){var string=doc.getLine(line),string=lastMatchIn(string,regexp,ch<0?0:string.length-ch);if(string)return{from:Pos(line,string.index),to:Pos(line,string.index+string[0].length),match:string}}}function searchRegexpBackwardMultiline(doc,regexp,start){if(!maybeMultiline(regexp))return searchRegexpBackward(doc,regexp,start);regexp=ensureFlags(regexp,"gm");for(var chunkSize=1,endMargin=doc.getLine(start.line).length-start.ch,line=start.line,first=doc.firstLine();first<=line;){for(var i=0;i<chunkSize&&first<=line;i++)var curLine=doc.getLine(line--),string=null==string?curLine:curLine+"\n"+string;chunkSize*=2;var inside,startLine,before,match=lastMatchIn(string,regexp,endMargin);if(match)return before=string.slice(0,match.index).split("\n"),inside=match[0].split("\n"),startLine=line+before.length,before=before[before.length-1].length,{from:Pos(startLine,before),to:Pos(startLine+inside.length-1,1==inside.length?before+inside[0].length:inside[inside.length-1].length),match:match}}}function adjustPos(orig,folded,pos,foldFunc){if(orig.length==folded.length)return pos;for(var min=0,max=pos+Math.max(0,orig.length-folded.length);;){if(min==max)return min;var mid=min+max>>1,len=foldFunc(orig.slice(0,mid)).length;if(len==pos)return mid;pos<len?max=mid:min=1+mid}}function searchStringForward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,last=doc.lastLine()+1-lines.length;line<=last;line++,ch=0){var orig=doc.getLine(line).slice(ch),string=fold(orig);if(1==lines.length){var found=string.indexOf(lines[0]);if(-1!=found)return start=adjustPos(orig,string,found,fold)+ch,{from:Pos(line,adjustPos(orig,string,found,fold)+ch),to:Pos(line,adjustPos(orig,string,found+lines[0].length,fold)+ch)}}else{found=string.length-lines[0].length;if(string.slice(found)==lines[0]){for(var i=1;i<lines.length-1;i++)if(fold(doc.getLine(line+i))!=lines[i])continue search;var end=doc.getLine(line+lines.length-1),endString=fold(end),lastLine=lines[lines.length-1];if(endString.slice(0,lastLine.length)==lastLine)return{from:Pos(line,adjustPos(orig,string,found,fold)+ch),to:Pos(line+lines.length-1,adjustPos(end,endString,lastLine.length,fold))}}}}}function searchStringBackward(doc,query,start,caseFold){if(!query.length)return null;var fold=caseFold?doFold:noFold,lines=fold(query).split(/\r|\n\r?/);search:for(var line=start.line,ch=start.ch,first=doc.firstLine()-1+lines.length;first<=line;line--,ch=-1){var orig=doc.getLine(line),string=fold(orig=-1<ch?orig.slice(0,ch):orig);if(1==lines.length){var found=string.lastIndexOf(lines[0]);if(-1!=found)return{from:Pos(line,adjustPos(orig,string,found,fold)),to:Pos(line,adjustPos(orig,string,found+lines[0].length,fold))}}else{found=lines[lines.length-1];if(string.slice(0,found.length)==found){for(var i=1,start=line-lines.length+1;i<lines.length-1;i++)if(fold(doc.getLine(start+i))!=lines[i])continue search;var top=doc.getLine(line+1-lines.length),topString=fold(top);if(topString.slice(topString.length-lines[0].length)==lines[0])return{from:Pos(line+1-lines.length,adjustPos(top,topString,top.length-lines[0].length,fold)),to:Pos(line,adjustPos(orig,string,found.length,fold))}}}}}function SearchCursor(doc,query,pos,options){var caseFold;this.atOccurrence=!1,this.doc=doc,pos=pos?doc.clipPos(pos):Pos(0,0),this.pos={from:pos,to:pos},"object"==typeof options?caseFold=options.caseFold:(caseFold=options,options=null),"string"==typeof query?(null==caseFold&&(caseFold=!1),this.matches=function(reverse,pos){return(reverse?searchStringBackward:searchStringForward)(doc,query,pos,caseFold)}):(query=ensureFlags(query,"gm"),options&&!1===options.multiline?this.matches=function(reverse,pos){return(reverse?searchRegexpBackward:searchRegexpForward)(doc,query,pos)}:this.matches=function(reverse,pos){return(reverse?searchRegexpBackwardMultiline:searchRegexpForwardMultiline)(doc,query,pos)})}noFold=String.prototype.normalize?(doFold=function(str){return str.normalize("NFD").toLowerCase()},function(str){return str.normalize("NFD")}):(doFold=function(str){return str.toLowerCase()},function(str){return str}),SearchCursor.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(reverse){for(var end,result=this.matches(reverse,this.doc.clipPos(reverse?this.pos.from:this.pos.to));result&&0==CodeMirror.cmpPos(result.from,result.to);)reverse?result.from.ch?result.from=Pos(result.from.line,result.from.ch-1):result=result.from.line==this.doc.firstLine()?null:this.matches(reverse,this.doc.clipPos(Pos(result.from.line-1))):result.to.ch<this.doc.getLine(result.to.line).length?result.to=Pos(result.to.line,result.to.ch+1):result=result.to.line==this.doc.lastLine()?null:this.matches(reverse,Pos(result.to.line+1,0));return result?(this.pos=result,this.atOccurrence=!0,this.pos.match||!0):(end=Pos(reverse?this.doc.firstLine():this.doc.lastLine()+1,0),this.pos={from:end,to:end},this.atOccurrence=!1)},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(newText,origin){this.atOccurrence&&(newText=CodeMirror.splitLines(newText),this.doc.replaceRange(newText,this.pos.from,this.pos.to,origin),this.pos.to=Pos(this.pos.from.line+newText.length-1,newText[newText.length-1].length+(1==newText.length?this.pos.from.ch:0)))}},CodeMirror.defineExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this.doc,query,pos,caseFold)}),CodeMirror.defineDocExtension("getSearchCursor",function(query,pos,caseFold){return new SearchCursor(this,query,pos,caseFold)}),CodeMirror.defineExtension("selectMatches",function(query,caseFold){for(var ranges=[],cur=this.getSearchCursor(query,this.getCursor("from"),caseFold);cur.findNext()&&!(0<CodeMirror.cmpPos(cur.to(),this.getCursor("to")));)ranges.push({anchor:cur.from(),head:cur.to()});ranges.length&&this.setSelections(ranges,0)})}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function Annotation(cm,options){function scheduleRedraw(delay){clearTimeout(self.doRedraw),self.doRedraw=setTimeout(function(){self.redraw()},delay)}this.cm=cm,this.options=options,this.buttonHeight=options.scrollButtonHeight||cm.getOption("scrollButtonHeight"),this.annotations=[],this.doRedraw=this.doUpdate=null,this.div=cm.getWrapperElement().appendChild(document.createElement("div")),this.div.style.cssText="position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none",this.computeScale();var self=this;cm.on("refresh",this.resizeHandler=function(){clearTimeout(self.doUpdate),self.doUpdate=setTimeout(function(){self.computeScale()&&scheduleRedraw(20)},100)}),cm.on("markerAdded",this.resizeHandler),cm.on("markerCleared",this.resizeHandler),!1!==options.listenForChanges&&cm.on("changes",this.changeHandler=function(){scheduleRedraw(250)})}CodeMirror.defineExtension("annotateScrollbar",function(options){return new Annotation(this,options="string"==typeof options?{className:options}:options)}),CodeMirror.defineOption("scrollButtonHeight",0),Annotation.prototype.computeScale=function(){var cm=this.cm,cm=(cm.getWrapperElement().clientHeight-cm.display.barHeight-2*this.buttonHeight)/cm.getScrollerElement().scrollHeight;if(cm!=this.hScale)return this.hScale=cm,!0},Annotation.prototype.update=function(annotations){this.annotations=annotations,this.redraw()},Annotation.prototype.redraw=function(compute){!1!==compute&&this.computeScale();var cm=this.cm,hScale=this.hScale,frag=document.createDocumentFragment(),anns=this.annotations,wrapping=cm.getOption("lineWrapping"),singleLineH=wrapping&&1.5*cm.defaultTextHeight(),curLine=null,curLineObj=null;function getY(pos,top){var visual;return curLine!=pos.line&&(curLine=pos.line,curLineObj=cm.getLineHandle(pos.line),(visual=cm.getLineHandleVisualStart(curLineObj))!=curLineObj)&&(curLine=cm.getLineNumber(visual),curLineObj=visual),curLineObj.widgets&&curLineObj.widgets.length||wrapping&&curLineObj.height>singleLineH?cm.charCoords(pos,"local")[top?"top":"bottom"]:cm.heightAtLine(curLineObj,"local")+(top?0:curLineObj.height)}var lastLine=cm.lastLine();if(cm.display.barWidth)for(var nextTop,i=0;i<anns.length;i++){var ann=anns[i];if(!(ann.to.line>lastLine)){for(var height,elt,top=nextTop||getY(ann.from,!0)*hScale,bottom=getY(ann.to,!1)*hScale;i<anns.length-1&&!(anns[i+1].to.line>lastLine)&&!(bottom+.9<(nextTop=getY(anns[i+1].from,!0)*hScale));)bottom=getY((ann=anns[++i]).to,!1)*hScale;bottom!=top&&(height=Math.max(bottom-top,3),(elt=frag.appendChild(document.createElement("div"))).style.cssText="position: absolute; right: 0px; width: "+Math.max(cm.display.barWidth-1,2)+"px; top: "+(top+this.buttonHeight)+"px; height: "+height+"px",elt.className=this.options.className,ann.id)&&elt.setAttribute("annotation-id",ann.id)}}this.div.textContent="",this.div.appendChild(frag)},Annotation.prototype.clear=function(){this.cm.off("refresh",this.resizeHandler),this.cm.off("markerAdded",this.resizeHandler),this.cm.off("markerCleared",this.resizeHandler),this.changeHandler&&this.cm.off("changes",this.changeHandler),this.div.parentNode.removeChild(this.div)}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("./searchcursor"),require("../scroll/annotatescrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../scroll/annotatescrollbar"],mod):mod(CodeMirror)})(function(CodeMirror){function SearchAnnotation(cm,query,caseFold,options){this.cm=cm;var prop,annotateOptions={listenForChanges:!1};for(prop in this.options=options)annotateOptions[prop]=options[prop];annotateOptions.className||(annotateOptions.className="CodeMirror-search-match"),this.annotation=cm.annotateScrollbar(annotateOptions),this.query=query,this.caseFold=caseFold,this.gap={from:cm.firstLine(),to:cm.lastLine()+1},this.matches=[],this.update=null,this.findMatches(),this.annotation.update(this.matches);var self=this;cm.on("change",this.changeHandler=function(_cm,change){self.onChange(change)})}CodeMirror.defineExtension("showMatchesOnScrollbar",function(query,caseFold,options){return new SearchAnnotation(this,query,caseFold,options=(options="string"==typeof options?{className:options}:options)||{})});function offsetLine(line,changeStart,sizeChange){return line<=changeStart?line:Math.max(changeStart,line+sizeChange)}SearchAnnotation.prototype.findMatches=function(){if(this.gap){for(var i=0;i<this.matches.length;i++){if((match=this.matches[i]).from.line>=this.gap.to)break;match.to.line>=this.gap.from&&this.matches.splice(i--,1)}for(var match,cursor=this.cm.getSearchCursor(this.query,CodeMirror.Pos(this.gap.from,0),{caseFold:this.caseFold,multiline:this.options.multiline}),maxMatches=this.options&&this.options.maxMatches||1e3;cursor.findNext();){if((match={from:cursor.from(),to:cursor.to()}).from.line>=this.gap.to)break;if(this.matches.splice(i++,0,match),this.matches.length>maxMatches)break}this.gap=null}},SearchAnnotation.prototype.onChange=function(change){var startLine=change.from.line,endLine=CodeMirror.changeEnd(change).line,sizeChange=endLine-change.to.line;if(this.gap?(this.gap.from=Math.min(offsetLine(this.gap.from,startLine,sizeChange),change.from.line),this.gap.to=Math.max(offsetLine(this.gap.to,startLine,sizeChange),change.from.line)):this.gap={from:change.from.line,to:endLine+1},sizeChange)for(var i=0;i<this.matches.length;i++){var match=this.matches[i],newFrom=offsetLine(match.from.line,startLine,sizeChange),newFrom=(newFrom!=match.from.line&&(match.from=CodeMirror.Pos(newFrom,match.from.ch)),offsetLine(match.to.line,startLine,sizeChange));newFrom!=match.to.line&&(match.to=CodeMirror.Pos(newFrom,match.to.ch))}clearTimeout(this.update);var self=this;this.update=setTimeout(function(){self.updateAfterChange()},250)},SearchAnnotation.prototype.updateAfterChange=function(){this.findMatches(),this.annotation.update(this.matches)},SearchAnnotation.prototype.clear=function(){this.cm.off("change",this.changeHandler),this.annotation.clear()}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../dialog/dialog")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../dialog/dialog"],mod):mod(CodeMirror)})(function(CodeMirror){function interpretLine(cm,string){var num=Number(string);return/^[-+]/.test(string)?cm.getCursor().line+num:num-1}CodeMirror.commands.jumpToLine=function(cm){var cur=cm.getCursor();((cm,text,shortText,deflt,f)=>{cm.openDialog?cm.openDialog(text,f,{value:deflt,selectValueOnOpen:!0}):f(prompt(shortText,deflt))})(cm,(cm=>cm.phrase("Jump to line:")+' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">'+cm.phrase("(Use line:column or scroll% syntax)")+"</span>")(cm),cm.phrase("Jump to line:"),cur.line+1+":"+cur.ch,function(posStr){var match,line;posStr&&((match=/^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr))?cm.setCursor(interpretLine(cm,match[1]),Number(match[2])):(match=/^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr))?(line=Math.round(cm.lineCount()*Number(match[1])/100),/^[-+]/.test(match[1])&&(line=cur.line+line+1),cm.setCursor(line-1,cur.ch)):(match=/^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr))&&cm.setCursor(interpretLine(cm,match[1]),cur.ch))})},CodeMirror.keyMap.default["Alt-G"]="jumpToLine"}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){function onCursorActivity(cm){cm.state.markedSelection&&cm.operation(function(){(cm=>{if(!cm.somethingSelected())return clear(cm);if(1<cm.listSelections().length)return reset(cm);var from=cm.getCursor("start"),to=cm.getCursor("end"),array=cm.state.markedSelection;if(!array.length)return coverRange(cm,from,to);var coverStart=array[0].find(),coverEnd=array[array.length-1].find();if(!coverStart||!coverEnd||to.line-from.line<=CHUNK_SIZE||0<=cmp(from,coverEnd.to)||cmp(to,coverStart.from)<=0)return reset(cm);for(;0<cmp(from,coverStart.from);)array.shift().clear(),coverStart=array[0].find();for(cmp(from,coverStart.from)<0&&(coverStart.to.line-from.line<CHUNK_SIZE?(array.shift().clear(),coverRange(cm,from,coverStart.to,0)):coverRange(cm,from,coverStart.from,0));cmp(to,coverEnd.to)<0;)array.pop().clear(),coverEnd=array[array.length-1].find();0<cmp(to,coverEnd.to)&&(to.line-coverEnd.from.line<CHUNK_SIZE?(array.pop().clear(),coverRange(cm,coverEnd.from,to)):coverRange(cm,coverEnd.to,to))})(cm)})}function onChange(cm){cm.state.markedSelection&&cm.state.markedSelection.length&&cm.operation(function(){clear(cm)})}CodeMirror.defineOption("styleSelectedText",!1,function(cm,val,old){old=old&&old!=CodeMirror.Init;val&&!old?(cm.state.markedSelection=[],cm.state.markedSelectionStyle="string"==typeof val?val:"CodeMirror-selectedtext",reset(cm),cm.on("cursorActivity",onCursorActivity),cm.on("change",onChange)):!val&&old&&(cm.off("cursorActivity",onCursorActivity),cm.off("change",onChange),clear(cm),cm.state.markedSelection=cm.state.markedSelectionStyle=null)});var CHUNK_SIZE=8,Pos=CodeMirror.Pos,cmp=CodeMirror.cmpPos;function coverRange(cm,from,to,addAt){if(0!=cmp(from,to))for(var array=cm.state.markedSelection,cls=cm.state.markedSelectionStyle,line=from.line;;){var start=line==from.line?from:Pos(line,0),endLine=line+CHUNK_SIZE,atEnd=endLine>=to.line,end=atEnd?to:Pos(endLine,0),start=cm.markText(start,end,{className:cls});if(null==addAt?array.push(start):array.splice(addAt++,0,start),atEnd)break;line=endLine}}function clear(cm){for(var array=cm.state.markedSelection,i=0;i<array.length;++i)array[i].clear();array.length=0}function reset(cm){clear(cm);for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++)coverRange(cm,ranges[i].from(),ranges[i].to())}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){CodeMirror.runMode=function(string,modespec,callback,options){for(var ie_lt9,node,col,mode=CodeMirror.getMode(CodeMirror.defaults,modespec),tabSize=options&&options.tabSize||CodeMirror.defaults.tabSize,lines=(callback.appendChild&&(ie_lt9=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<9),col=0,(node=callback).innerHTML="",callback=function(text,style){if("\n"==text)node.appendChild(document.createTextNode(ie_lt9?"\r":text)),col=0;else{for(var sp,content="",pos=0;;){var idx=text.indexOf("\t",pos);if(-1==idx){content+=text.slice(pos),col+=text.length-pos;break}col+=idx-pos,content+=text.slice(pos,idx);var size=tabSize-col%tabSize;col+=size;for(var i=0;i<size;++i)content+=" ";pos=idx+1}(style?((sp=node.appendChild(document.createElement("span"))).className="cm-"+style.replace(/ +/g," cm-"),sp):node).appendChild(document.createTextNode(content))}}),CodeMirror.splitLines(string)),state=options&&options.state||CodeMirror.startState(mode),i=0,e=lines.length;i<e;++i){i&&callback("\n");var stream=new CodeMirror.StringStream(lines[i],null,{lookAhead:function(n){return lines[i+n]},baseToken:function(){}});for(!stream.string&&mode.blankLine&&mode.blankLine(state);!stream.eol();){var style=mode.token(stream,state);callback(stream.current(),style,i,stream.start,state),stream.start=stream.pos}}}}),CodeMirror.defineMode("pyret",function(config,parserConfig){function wordRegexp(words){return new RegExp("^(("+words.join(")|(")+"))(?![a-zA-Z0-9-_])")}function toToken(type){return function(tstr){return{type:type,string:tstr}}}let pyret_ident_regex=new RegExp("^[a-zA-Z_][a-zA-Z0-9_-]*");var pyret_closing_keywords=["end"],pyret_closing_tokens=pyret_closing_keywords.map(toToken("keyword")).concat([].map(toToken("builtin"))),pyret_opening_keywords_colon=["reactor","try","ref-graph","block","table","load-table"],pyret_opening_keywords_nocolon=["include from","provide from","fun","when","for","if","let","type-let","ask","spy","cases","data","shared","check","except","letrec","lam","method","examples","do","select","extend","transform","extract","sieve","order","provide","provide-types"],pyret_opening_tokens=pyret_opening_keywords_colon.concat(pyret_opening_keywords_nocolon).map(toToken("keyword"));let pyret_openers_closed_by_end={FUN:!0,WHEN:!0,DO:!0,FOR:!0,IF:!0,BLOCK:!0,LET:!0,TABLE:!0,LOADTABLE:!0,SELECT:!0,EXTEND:!0,SIEVE:!0,TRANSFORM:!0,EXTRACT:!0,ORDER:!0,REACTOR:!0,SPY:!0,INCLUDEFROM:!0,PROVIDECOLON:!0},pyret_keywords=wordRegexp(["else if"].concat(pyret_opening_keywords_nocolon,pyret_closing_keywords,["spy","var","rec","import","include","type","newtype","hiding","from","lazy","shadow","ref","of","module","and","or","as","else","cases","is==","is=~","is<=>","is","satisfies","raises","violates","by","ascending","descending","sanitize","using","because","module","hiding"])),pyret_booleans=wordRegexp(["true","false"]),pyret_keywords_hyphen=wordRegexp(["type-let","does-not-raise","raises-violates","raises-satisfies","raises-other-than","is-roughly","is-not-roughly","is-not==","is-not=~","is-not<=>","is-not"]),pyret_keywords_colon=wordRegexp(pyret_opening_keywords_colon.concat(["doc","otherwise","then","with","sharing","where","do","row","source"])),pyret_single_punctuation=new RegExp("^(["+[":",".","<",">",",","^","!",";","|","=","+","*","/","\\\\","(",")","{","}","\\[","\\]"].join("")+"])"),pyret_double_punctuation=new RegExp("^(("+["<=>","::","=~","==",">=","<=","=>","->",":=","<>"].join(")|(")+"))"),initial_operators={"-":!0,"+":!0,"*":!0,"/":!0,"<":!0,"<=":!0,">":!0,">=":!0,"==":!0,"<>":!0,".":!0,"^":!0,"<=>":!0,"=~":!0,is:!0,"is==":!0,"is=~":!0,"is<=>":!0,because:!0,"is-roughly":!0,"is-not":!0,"is-not-roughly":!0,"is-not==":!0,"is-not=~":!0,"is-not<=>":!0,satisfies:!0,violates:!0,raises:!0,"raises-other-than":!0,"does-not-raise":!0,"raises-satisfies":!0,"raises-violates":!0},pyret_delimiter_type={NONE:0,OPENING:1,CLOSING:2,SUBKEYWORD:3,OPEN_CONTD:4,CLOSE_CONTD:5,SUB_CONTD:6,FOLD_OPEN_CONTD:7};function ret(state,tokType,content,style){return state.lastToken=tokType,state.lastContent=content,style}let number=new RegExp("^[-+]?[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?"),badNumber=new RegExp("^~?[+-]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?"),roughnum=new RegExp("^~[-+]?(?:[0-9]+/[0-9]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)"),restOfRoughnum=new RegExp("^[-+]?(?:[0-9]+/[0-9]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)"),rational=new RegExp("^[-+]?[0-9]+/[0-9]+");function tokenBase(stream,state){var squot_str,unterminated_string,dquot_str;return stream.eatSpace()?"IGNORED-SPACE":"#"===stream.peek()?stream.match("#|",!0)?(state.tokenizer=tokenizeBlockComment,state.commentNestingDepth=1,ret(state,"COMMENT-START",state.lastContent,"comment")):(stream.skipToEnd(),ret(state,"COMMENT",state.lastContent,"comment")):stream.match(roughnum,!1)?(stream.match("~"),state.tokenizer=tokenizeRoughnum,ret(state,"ROUGHNUM-START",stream.current(),"roughnum-start")):stream.match(rational)||stream.match(number)?ret(state,"number",stream.current(),"number"):stream.match(badNumber)?ret(state,"number",stream.current(),"bad-number"):(dquot_str=new RegExp('^"(?:\\\\[01234567]{1,3}|\\\\x[0-9a-fA-F]{1,2}|\\\\u[0-9a-fA-f]{1,4}|\\\\[\\\\nrt"\']|[^\\\\"\n\r])*"'),squot_str=new RegExp("^'(?:\\\\[01234567]{1,3}|\\\\x[0-9a-fA-F]{1,2}|\\\\u[0-9a-fA-f]{1,4}|\\\\[\\\\nrt\"']|[^\\\\'\n\r])*'"),unterminated_string=new RegExp("^[\"'].*"),state.maybeShorthandLambda=!1,(dquot_str=(dquot_str=stream.match(dquot_str,!0))||stream.match(squot_str,!0))?ret(state,"string",dquot_str[0],"string"):stream.match(/^```/,!0)?(state.tokenizer=tokenStringTriple,state.inString=stream.column(),state.lastToken="```",state.tokenizer(stream,state)):(dquot_str=stream.match(unterminated_string,!0))?ret(state,"string",dquot_str[0],"unterminated-string"):(dquot_str=stream.match(/^\.\.\./,!0))?ret(state,dquot_str[0],dquot_str[0],"builtin"):(dquot_str=stream.match(/^({(?=\())/,!0))?(state.maybeShorthandLambda=!0,ret(state,"{","{","builtin")):(dquot_str=(dquot_str=stream.match(pyret_double_punctuation,!0))||stream.match(pyret_single_punctuation,!0))?(!state.dataNoPipeColon||":"!=dquot_str[0]&&"|"!=dquot_str[0]||(state.dataNoPipeColon=!1),ret(state,dquot_str[0],dquot_str[0],"builtin")):(dquot_str=stream.match(pyret_keywords_hyphen,!0))?ret(state,dquot_str[0],dquot_str[0],"keyword"):(dquot_str=stream.match(pyret_keywords,!0))?("data"==dquot_str[0]&&(state.dataNoPipeColon=!0),ret(state,dquot_str[0],dquot_str[0],"keyword")):(dquot_str=stream.match(pyret_booleans,!0))?ret(state,dquot_str[0],dquot_str[0],"boolean"):(dquot_str=stream.match(pyret_keywords_colon,!0))?":"===stream.peek()?ret(state,dquot_str[0],dquot_str[0],"keyword"):ret(state,"name",dquot_str[0],"variable"):(dquot_str=stream.match(pyret_ident_regex))?"|"===state.lastToken||"::"===state.lastToken||"data"===state.lastToken||state.dataNoPipeColon?(state.dataNoPipeColon=!1,ret(state,"name",dquot_str[0],"type")):stream.match(/\s*\(/,!1)?ret(state,"name",dquot_str[0],"function-name"):ret(state,"name",dquot_str[0],"variable"):stream.eat("-")?ret(state,"-","-","builtin"):(stream.next(),null))}function tokenizeRoughnum(stream,state){return stream.match(restOfRoughnum),state.tokenizer=tokenBase,ret(state,"number",stream.current(),"roughnum")}function tokenizeBlockComment(stream,state){return stream.match("#|",!0)?(state.commentNestingDepth++,ret(state,"COMMENT-START",state.lastContent,"comment")):stream.match("|#",!0)?(state.commentNestingDepth--,0===state.commentNestingDepth&&(state.tokenizer=tokenBase),ret(state,"COMMENT-END",state.lastContent,"comment")):(stream.next(),stream.eatWhile(/[^#|]/),ret(state,"COMMENT",state.lastContent,"comment"))}function tokenStringTriple(stream,state){for(;!stream.eol();)if(stream.match(/[^`\\]*/,!0),stream.eat("\\")){if(stream.next(),stream.eol())return ret(state,"string",stream.current(),"string")}else{if(stream.match("```",!0))return state.tokenizer=tokenBase,state.inString=!1,ret(state,"string",stream.current(),"string");stream.next()}return ret(state,"string",stream.current(),"string")}function Indent(funs,cases,data,shared,trys,except,graph,parens,objects,vars,fields,initial,comments){this.fn=funs||0,this.c=cases||0,this.d=data||0,this.s=shared||0,this.t=trys||0,this.e=except||0,this.g=graph||0,this.p=parens||0,this.o=objects||0,this.v=vars||0,this.f=fields||0,this.i=initial||0,this.comments=comments||0}function LineState(tokens,nestingsAtLineStart,nestingsAtLineEnd,deferedOpened,curOpened,deferedClosed,curClosed,delimType){this.tokens=tokens,this.nestingsAtLineStart=nestingsAtLineStart,this.nestingsAtLineEnd=nestingsAtLineEnd,this.deferedOpened=deferedOpened,this.curOpened=curOpened,this.deferedClosed=deferedClosed,this.curClosed=curClosed,this.delimType=delimType}function peek(arr){return arr[arr.length-1]}function hasTop(arr,wanted){if(wanted instanceof Array){for(var i=0;i<wanted.length;i++)if(arr[arr.length-1-i]!==wanted[i])return;return 1}return arr[arr.length-1]===wanted}function parse(firstTokenInLine,state,stream,style){var inOpening=(ls=state.lineState).delimType===pyret_delimiter_type.OPENING||ls.delimType===pyret_delimiter_type.OPEN_CONTD,inSubkw=ls.delimType===pyret_delimiter_type.SUBKEYWORD||ls.delimType===pyret_delimiter_type.SUB_CONTD;if(ls.delimType=pyret_delimiter_type.NONE,firstTokenInLine&&(ls.nestingsAtLineStart=ls.nestingsAtLineEnd.copy()),"name"===state.lastToken&&"function-name"===style&&hasTop(ls.tokens,["WANTOPENPAREN","WANTCLOSEPAREN","WANTCOLONORBLOCK","FUN"])&&inOpening&&(ls.delimType=pyret_delimiter_type.FOLD_OPEN_CONTD),ls.lastToken=state.lastToken,0<ls.nestingsAtLineStart.comments||0<ls.curOpened.comments||0<ls.deferedOpened.comments)"COMMENT-END"===state.lastToken?0<ls.curOpened.comments?ls.curOpened.comments--:0<ls.deferedOpened.comments?ls.deferedOpened.comments--:firstTokenInLine?ls.curClosed.comments++:ls.deferedClosed.comments++:"COMMENT-START"===state.lastToken&&ls.deferedOpened.comments++;else if("COMMENT-START"===state.lastToken)ls.deferedOpened.comments++;else if("COMMENT"!==state.lastToken)if(hasTop(ls.tokens,"NEEDSOMETHING"))ls.tokens.pop(),hasTop(ls.tokens,"VAR")&&0<ls.deferedOpened.v&&(ls.deferedOpened.v--,ls.tokens.pop()),parse(firstTokenInLine,state,stream,style);else if(firstTokenInLine&&(initial_operators[state.lastToken]&&("."==state.lastToken||stream.match(/^\s+/))||"is"===state.lastToken&&stream.match(/^%/)||"is-not"===state.lastToken&&stream.match(/^%/)))ls.curOpened.i++,ls.deferedClosed.i++;else if(":"===state.lastToken)inOpening?ls.delimType=pyret_delimiter_type.OPEN_CONTD:inSubkw&&(ls.delimType=pyret_delimiter_type.SUB_CONTD),hasTop(ls.tokens,"WANTCOLON")||hasTop(ls.tokens,"WANTCOLONOREQUAL")||hasTop(ls.tokens,"WANTCOLONORBLOCK")||hasTop(ls.tokens,"WANTCOLONORSTAR")?ls.tokens.pop():(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"REACTOR")||hasTop(ls.tokens,"SHARED")||hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&((hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("OBJECT")),ls.deferedOpened.f++,ls.tokens.push("FIELD","NEEDSOMETHING"));else if(";"===state.lastToken)(hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("TUPLE"));else if("::"===state.lastToken)(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"SHARED"))&&(ls.deferedOpened.f++,ls.tokens.push("FIELD","NEEDSOMETHING"));else if(","===state.lastToken)hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.deferedClosed.f++);else if("="===state.lastToken)if(hasTop(ls.tokens,"WANTCOLONOREQUAL"))ls.tokens.pop();else{for(;hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.curClosed.v++;ls.deferedOpened.v++,ls.tokens.push("VAR","NEEDSOMETHING")}else if("var"===state.lastToken||"rec"===state.lastToken)ls.deferedOpened.v++,ls.tokens.push("VAR","NEEDSOMETHING","WANTCOLONOREQUAL");else if("fun"===state.lastToken||"method"===state.lastToken||"lam"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FUN","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("method"===state.lastToken)(hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA"))&&(ls.tokens.pop(),ls.tokens.push("OBJECT")),ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FUN","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("let"===state.lastToken||"letrec"===state.lastToken||"type-let"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("LET","WANTCOLONORBLOCK");else if("when"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("WHEN","WANTCOLONORBLOCK");else if("do"===state.lastToken)hasTop(ls.tokens,"DO")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WHEN","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("for"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("FOR","WANTCOLONORBLOCK");else if("cases"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.c++,ls.tokens.push("CASES","WANTCOLONORBLOCK","WANTCLOSEPAREN","WANTOPENPAREN");else if("data"!==state.lastToken||(hasTop(ls.tokens,"INCLUDEFROMBODY")||hasTop(ls.tokens,"PROVIDE")||hasTop(ls.tokens,"PROVIDEFROMBODY")))if("ask"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.c++,ls.tokens.push("IFCOND","WANTCOLONORBLOCK");else if("spy"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SPY","WANTCOLON");else if("if"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("IF","WANTCOLONORBLOCK","NEEDSOMETHING");else if("else if"===state.lastToken)hasTop(ls.tokens,"IF")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON","NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("else"===state.lastToken)hasTop(ls.tokens,"IF")&&(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("row"===state.lastToken)hasTop(ls.tokens,"TABLEROW")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"TABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("TABLEROW","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("source"===state.lastToken)hasTop(ls.tokens,"LOADTABLESPEC")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("NEEDSOMETHING","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"LOADTABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("LOADTABLESPEC","NEEDSOMETHING","WANTCOLON"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("sanitize"===state.lastToken)hasTop(ls.tokens,"LOADTABLESPEC")?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,ls.deferedOpened.fn++,ls.tokens.push("NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD):hasTop(ls.tokens,"LOADTABLE")&&(ls.deferedOpened.fn++,ls.tokens.push("LOADTABLESPEC","NEEDSOMETHING"),ls.delimType=pyret_delimiter_type.SUBKEYWORD);else if("|"===state.lastToken)hasTop(ls.tokens,["OBJECT","DATA"])||hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++),hasTop(ls.tokens,"OBJECT")&&ls.tokens.pop()):hasTop(ls.tokens,"DATA")&&ls.tokens.push("NEEDSOMETHING");else if("with"===state.lastToken)hasTop(ls.tokens,["WANTOPENPAREN","WANTCLOSEPAREN","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.push("OBJECT","WANTCOLON")):hasTop(ls.tokens,["DATA"])&&ls.tokens.push("OBJECT","WANTCOLON");else if("provide"===state.lastToken)ls.tokens.push("PROVIDE","WANTCOLONORSTAR"),ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.s++;else if("sharing"===state.lastToken)ls.curClosed.d++,ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.SUBKEYWORD,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.pop(),ls.curClosed.o++,ls.tokens.push("SHARED","WANTCOLON")):hasTop(ls.tokens,["OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.tokens.push("SHARED","WANTCOLON")):hasTop(ls.tokens,"DATA")&&(ls.tokens.pop(),ls.tokens.push("SHARED","WANTCOLON"));else if("where"===state.lastToken||"examples"===state.lastToken&&0<ls.tokens.length)ls.delimType="where"===state.lastToken?pyret_delimiter_type.SUBKEYWORD:pyret_delimiter_type.OPENING,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.tokens.pop(),ls.tokens.pop(),ls.curClosed.o++,ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,["OBJECT","DATA"])?(ls.tokens.pop(),ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,"DATA")?(ls.curClosed.d++,ls.deferedOpened.s++):hasTop(ls.tokens,"FUN")?(ls.curClosed.f++,ls.deferedOpened.s++):hasTop(ls.tokens,"SHARED")&&(ls.curClosed.s++,ls.deferedOpened.s++),ls.tokens.pop(),ls.tokens.push("CHECK","WANTCOLON");else if("check"===state.lastToken||"examples"===state.lastToken&&0===ls.tokens.length)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.s++,ls.tokens.push("CHECK","WANTCOLON");else if("try"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.t++,ls.tokens.push("TRY","WANTCOLON");else if("except"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,0<ls.curOpened.t?ls.curOpened.t--:0<ls.deferedOpened.t?ls.deferedOpened.t--:ls.curClosed.t++,hasTop(ls.tokens,"TRY")&&(ls.tokens.pop(),ls.tokens.push("WANTCOLON","WANTCLOSEPAREN","WANTOPENPAREN"));else if("then"===state.lastToken||"otherwise"===state.lastToken)ls.delimType=pyret_delimiter_type.SUBKEYWORD;else if("block"===state.lastToken)hasTop(ls.tokens,"WANTCOLONORBLOCK")?ls.delimType=pyret_delimiter_type.SUBKEYWORD:(ls.deferedOpened.fn++,ls.tokens.push("BLOCK","WANTCOLON"),ls.delimType=pyret_delimiter_type.OPENING);else if("reactor"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("REACTOR","WANTCOLON");else if("table"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("TABLE","WANTCOLON");else if("load-table"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("LOADTABLE","WANTCOLON");else if("select"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SELECT","WANTCOLON");else if("extend"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("EXTEND","WANTCOLON");else if("transform"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("TRANSFORM","WANTCOLON");else if("extract"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("EXTRACT","WANTCOLON");else if("sieve"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("SIEVE","WANTCOLON");else if("order"===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.fn++,ls.tokens.push("ORDER","WANTCOLON");else if("ref-graph"===state.lastToken)ls.deferedOpened.g++,ls.tokens.push("GRAPH","WANTCOLON");else if("["===state.lastToken)ls.deferedOpened.o++,ls.tokens.push("ARRAY"),ls.delimType=pyret_delimiter_type.OPENING;else if("]"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,firstTokenInLine?ls.curClosed.o++:ls.deferedClosed.o++,hasTop(ls.tokens,"ARRAY")&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("{"===state.lastToken&&hasTop(ls.tokens,["WANTRECORDORSTAR"]))ls.delimType=pyret_delimiter_type.OPEN_CONTD;else if("{"===state.lastToken)ls.deferedOpened.o++,state.maybeShorthandLambda?ls.tokens.push("BRACEDEXPR"):ls.tokens.push("BRACEDEXPR_NOLAMBDA"),ls.delimType=pyret_delimiter_type.OPENING;else if("}"===state.lastToken&&hasTop(ls.tokens,["WANTRECORDORSTAR"]))firstTokenInLine?ls.curClosed.s++:ls.deferedClosed.s++,ls.tokens.pop(),ls.tokens.pop(),ls.delimType=pyret_delimiter_type.CLOSING;else if("}"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,firstTokenInLine?ls.curClosed.o++:ls.deferedClosed.o++,hasTop(ls.tokens,"FIELD")&&(ls.tokens.pop(),0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++),(hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"BRACEDEXPR")||hasTop(ls.tokens,"BRACEDEXPR_NOLAMBDA")||hasTop(ls.tokens,"TUPLE")||hasTop(ls.tokens,"SHORTHANDLAMBDA"))&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("("===state.lastToken)ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.p++,hasTop(ls.tokens,"WANTOPENPAREN")?ls.tokens.pop():hasTop(ls.tokens,"BRACEDEXPR")?(ls.tokens.pop(),ls.tokens.push("SHORTHANDLAMBDA","WANTCOLONORBLOCK")):hasTop(ls.tokens,"OBJECT")||hasTop(ls.tokens,"SHARED")?(ls.tokens.push("FUN","WANTCOLONORBLOCK"),ls.deferedOpened.fn++):ls.tokens.push("WANTCLOSEPAREN");else if(")"===state.lastToken)for(ls.delimType=pyret_delimiter_type.CLOSING,0<ls.curOpened.p?ls.curOpened.p--:0<ls.deferedOpened.p?ls.deferedOpened.p--:ls.deferedClosed.p++,hasTop(ls.tokens,"WANTCLOSEPAREN")&&ls.tokens.pop();hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.deferedClosed.v++;else if("end"===state.lastToken){ls.delimType=pyret_delimiter_type.CLOSING,hasTop(ls.tokens,["FIELD","OBJECT","DATA"])?(ls.curClosed.f++,ls.tokens.pop(),ls.tokens.pop()):hasTop(ls.tokens,["OBJECT","DATA"])?ls.tokens.pop():(hasTop(ls.tokens,["TABLEROW","TABLE"])||hasTop(ls.tokens,["LOADTABLESPEC","LOADTABLE"]))&&(ls.tokens.pop(),ls.curClosed.o++);for(var top=peek(ls.tokens),stillUnclosed=!0;stillUnclosed&&ls.tokens.length;)"OBJECT"===top||"ARRAY"===top?0<ls.curOpened.o?ls.curOpened.o--:0<ls.deferedOpened.o?ls.deferedOpened.o--:ls.curClosed.o++:"WANTCLOSEPAREN"===top?0<ls.curOpened.p?ls.curOpened.p--:0<ls.deferedOpened.p?ls.deferedOpened.p--:ls.curClosed.p++:"FIELD"===top?0<ls.curOpened.f?ls.curOpened.f--:0<ls.deferedOpened.f?ls.deferedOpened.f--:ls.curClosed.f++:"VAR"===top?0<ls.curOpened.v?ls.curOpened.v--:0<ls.deferedOpened.v?ls.deferedOpened.v--:ls.curClosed.v++:"PROVIDE"===top||"INCLUDEFROM"==top?0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++:"INCLUDEFROMBODY"==top||"PROVIDEFROMBODY"==top?(0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++,ls.tokens.pop()):!0===pyret_openers_closed_by_end[top]?(0<ls.curOpened.fn?ls.curOpened.fn--:0<ls.deferedOpened.fn?ls.deferedOpened.fn--:ls.curClosed.fn++,stillUnclosed=!1):"CASES"===top||"IFCOND"===top?(0<ls.curOpened.c?ls.curOpened.c--:0<ls.deferedOpened.c?ls.deferedOpened.c--:ls.curClosed.c++,stillUnclosed=!1):"DATA"===top?(0<ls.curOpened.d?ls.curOpened.d--:0<ls.deferedOpened.d?ls.deferedOpened.d--:ls.curClosed.d++,stillUnclosed=!1):"SHARED"===top||"CHECK"===top?(0<ls.curOpened.s?ls.curOpened.s--:0<ls.deferedOpened.s?ls.deferedOpened.s--:ls.curClosed.s++,stillUnclosed=!1):"TRY"===top?(0<ls.curOpened.t?ls.curOpened.t--:0<ls.deferedOpened.t?ls.deferedOpened.t--:ls.curClosed.t++,stillUnclosed=!1):"EXCEPT"===top?(0<ls.curOpened.e?ls.curOpened.e--:0<ls.deferedOpened.e?ls.deferedOpened.e--:ls.curClosed.e++,stillUnclosed=!1):"GRAPH"===top&&(0<ls.curOpened.g?ls.curOpened.g--:0<ls.deferedOpened.g?ls.deferedOpened.g--:ls.curClosed.g++,stillUnclosed=!1),ls.tokens.pop(),top=peek(ls.tokens)}else"*"===state.lastToken&&(hasTop(ls.tokens,["WANTCOLONORSTAR","PROVIDE"])||hasTop(ls.tokens,["WANTRECORDORSTAR","PROVIDETYPES"]))?(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop(),ls.tokens.pop()):"include from"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("INCLUDEFROM")):"provide from"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("PROVIDEFROM")):"provide-types"==state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("PROVIDETYPES","WANTRECORDORSTAR")):"include"==state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("INCLUDE")):"import"===state.lastToken?(ls.deferedOpened.s++,ls.delimType=pyret_delimiter_type.OPENING,ls.tokens.push("IMPORT","WANTFROMORAS")):"from"!==state.lastToken&&"as"!==state.lastToken||!hasTop(ls.tokens,["WANTFROMORAS"])?"name"===state.lastToken&&hasTop(ls.tokens,["INCLUDE"])?(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop()):"name"===state.lastToken&&(hasTop(ls.tokens,["INCLUDEFROM"])||hasTop(ls.tokens,["PROVIDEFROM"]))?(ls.delimType=pyret_delimiter_type.OPEN_CONTD,style=ls.tokens[ls.tokens.length-1]+"BODY",ls.tokens.push(style,"WANTCOLON")):"name"===state.lastToken&&hasTop(ls.tokens,["IMPORT"])&&(ls.deferedClosed.s++,ls.delimType=pyret_delimiter_type.CLOSING,ls.tokens.pop()):ls.tokens.pop();else ls.delimType=pyret_delimiter_type.OPENING,ls.deferedOpened.d++,ls.tokens.push("DATA","WANTCOLON","NEEDSOMETHING");if(stream.match(/\s*$/,!1)){for(ls.nestingsAtLineStart.addSelf(ls.curOpened).subSelf(ls.curClosed);hasTop(ls.tokens,"VAR");)ls.tokens.pop(),ls.curClosed.v++;ls.nestingsAtLineEnd.addSelf(ls.curOpened).addSelf(ls.deferedOpened).subSelf(ls.curClosed).subSelf(ls.deferedClosed),ls.tokens=ls.tokens.concat([]),ls.curOpened.zeroOut(),ls.deferedOpened.zeroOut(),ls.curClosed.zeroOut(),ls.deferedClosed.zeroOut()}}Indent.prototype.toString=function(){return"Fun "+this.fn+", Cases "+this.c+", Data "+this.d+", Shared "+this.s+", Try "+this.t+", Except "+this.e+", Graph "+this.g+", Parens "+this.p+", Object "+this.o+", Vars "+this.v+", Fields "+this.f+", Initial "+this.i+", Comment depth "+this.comments},Indent.prototype.copy=function(){return new Indent(this.fn,this.c,this.d,this.s,this.t,this.e,this.g,this.p,this.o,this.v,this.f,this.i,this.comments)},Indent.prototype.zeroOut=function(){this.fn=this.c=this.d=this.s=this.t=this.e=this.g=this.p=this.o=this.v=this.f=this.i=this.comments=0},Indent.prototype.addSelf=function(that){return this.fn+=that.fn,this.c+=that.c,this.d+=that.d,this.s+=that.s,this.t+=that.t,this.e+=that.e,this.g+=that.g,this.p+=that.p,this.o+=that.o,this.v+=that.v,this.f+=that.f,this.i+=that.i,this.comments+=that.comments,this},Indent.prototype.add=function(that){return this.copy().addSelf(that)},Indent.prototype.subSelf=function(that){return this.fn-=that.fn,this.c-=that.c,this.d-=that.d,this.s-=that.s,this.t-=that.t,that.e-=that.e,this.g-=that.g,this.p-=that.p,this.o-=that.o,this.v-=that.v,this.f-=that.f,this.i-=that.i,this.comments-=that.comments,this},Indent.prototype.sub=function(that){return this.copy().subSelf(that)},LineState.prototype.copy=function(){return new LineState(this.tokens.concat([]),this.nestingsAtLineStart.copy(),this.nestingsAtLineEnd.copy(),this.deferedOpened.copy(),this.curOpened.copy(),this.deferedClosed.copy(),this.curClosed.copy(),this.delimType)},LineState.prototype.print=function(){console.log("LineState is:"),console.log(" NestingsAtLineStart = "+this.nestingsAtLineStart),console.log(" NestingsAtLineEnd = "+this.nestingsAtLineEnd),console.log(" DeferedOpened = "+this.deferedOpened),console.log(" DeferedClosed = "+this.deferedClosed),console.log(" CurOpened = "+this.curOpened),console.log(" CurClosed = "+this.curClosed),console.log(" Tokens = "+this.tokens),console.log(" LastToken = "+this.lastToken)};let INDENTATION=new Indent(1,2,2,1,1,1,1,1,1,1,1,1,1.5);function copyState(oldState){return{tokenizer:oldState.tokenizer,lineState:oldState.lineState.copy(),lastToken:oldState.lastToken,lastContent:oldState.lastContent,commentNestingDepth:oldState.commentNestingDepth,inString:oldState.inString,dataNoPipeColon:oldState.dataNoPipeColon,sol:oldState.sol,maybeShorthandLambda:oldState.maybeShorthandLambda}}return{startState:function(basecolumn){return{tokenizer:tokenBase,inString:!1,commentNestingDepth:0,lineState:new LineState([],new Indent,new Indent,new Indent,new Indent,new Indent,new Indent,pyret_delimiter_type.NONE),sol:!0}},blankLine:function(state){state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy()},lineComment:"#",blockCommentStart:"#|",blockCommentEnd:"|#",blockCommentLead:" ",copyState:copyState,token:function(stream,state){!state.sol&&stream.sol()&&(state.sol=!0,state.indentation=stream.indentation());var style=state.tokenizer(stream,state);return"IGNORED-SPACE"===style?null:(parse(state.sol,state,stream,style),state.sol=!1,style)},indent:function(state,textAfter,fullLine){var indentUnit=config.indentUnit,taSS=new CodeMirror.StringStream(textAfter,config.tabSize),sol=!0,inString=state.inString;if(0<(state=copyState(state)).commentNestingDepth&&(state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy()),/^\s*$/.test(textAfter))state.lineState.nestingsAtLineStart=state.lineState.nestingsAtLineEnd.copy();else for(;!taSS.eol();){var style=state.tokenizer(taSS,state);"IGNORED-SPACE"!==style&&(parse(sol,state,taSS,style),sol=!1)}var key,indentSpec=state.lineState.nestingsAtLineStart,indent=0;for(key in INDENTATION)INDENTATION.hasOwnProperty(key)&&(indent+=(indentSpec[key]||0)*INDENTATION[key]);return 0<indentSpec.comments||!1!==inString?0<(textAfter=fullLine.match(/\s*/)[0].length)?textAfter:!1!==inString?inString:indent*indentUnit:/^\s*\|([^#]|$)/.test(fullLine)?(indent-1)*indentUnit:indent*indentUnit},electricInput:new RegExp("(?:[de.\\]}|:]||#|[-enst\\*\\+/=<>^~]\\s|is%|is-not%)$"),fold:"pyret",delimiters:{opening:pyret_opening_tokens,closing:pyret_closing_tokens,subkeywords:{if:["block","else if","else"],when:["block"],fun:["block","where"],method:["block","where"],lam:["block"],for:["block","do"],let:["block"],letrec:["block"],"type-let":["block"],cases:["block"],ask:["block","then","otherwise"],data:["sharing","where"],table:["row"],"load-table":["sanitize","source"],import:["from","as"],provide:["from"],include:["from"]},lastSubkeywords:{if:"else"},special:[{start:"(",ends:[")"]},{start:"[",ends:["]"]},{start:"{",ends:["}"]},{start:"provide",ends:["*","name","type"]},{start:"include",ends:["name","type"]},{start:"import",ends:["name","type"]},{start:"provide-types",ends:["*","}"]}],types:pyret_delimiter_type},unprefixedContexts:["SHARED","OBJECT"],blockCommentStart:"#|",blockCommentEnd:"|#",blockCommentContinue:"",lineComment:"#"}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)})(function(CodeMirror){var Pos=CodeMirror.Pos;function cmpClosest(a,b,c){var ret=a.line-c.line;return ret||(a.ch<=c.ch&&c.ch<=b.ch?0:Math.abs(a.ch-c.ch)<Math.abs(b.ch-c.ch)?a.ch-c.ch:b.ch-c.ch)}function keyMatches(open,close,isFunctionName){"string"!=typeof open?open=isFunctionName||"function-name"===open.type?"fun":open.string:isFunctionName&&(open="fun");isFunctionName="string"==typeof close?close:close.string;if(-1!=DELIMS.indexOf(open)&&-1!=ENDDELIM.indexOf(isFunctionName))return!0;for(var closeType="string"==typeof close?close:close.state.lastToken,i=0;i<SPECIALDELIM.length;i++)if(open===SPECIALDELIM[i].start)return SPECIALDELIM[i].ends.includes(closeType);return!1}function fieldOneOf(fname){var oneOf=Array.prototype.slice.call(arguments,1);return function(obj){for(var fval=obj[fname],i=0;i<oneOf.length;i++)if(fval===oneOf[i])return!0;return!1}}function negate(func){return function(){return!func.apply(this,arguments)}}function getField(fname){return function(o){return o[fname]}}function hasDuplicates(array){for(var valuesSoFar=Object.create(null),i=0;i<array.length;++i){var value=array[i];if(value in valuesSoFar)return 1;valuesSoFar[value]=!0}}var pyretMode=CodeMirror.getMode({},"pyret");if("null"===pyretMode.name)throw Error("Pyret Mode not Defined");if(!(pyretMode.delimiters&&pyretMode.delimiters.opening&&pyretMode.delimiters.closing&&pyretMode.delimiters.subkeywords&&pyretMode.delimiters.lastSubkeywords&&pyretMode.delimiters.special&&pyretMode.delimiters.types))throw Error("No correct delimiters defined in Pyret Mode");if(pyretMode.delimiters.opening.some(negate(fieldOneOf("type","keyword","builtin")))||pyretMode.delimiters.closing.some(negate(fieldOneOf("type","keyword","builtin"))))throw Error("Pyret Mode contains delimiters of unknown type");var DELIMS=pyretMode.delimiters.opening.map(getField("string")),ENDDELIM=pyretMode.delimiters.closing.map(getField("string")),UPFXCONTEXTS=pyretMode.unprefixedContexts;if(!DELIMS||!ENDDELIM||!UPFXCONTEXTS)throw Error("Pyret Mode missing required exports.");if(hasDuplicates(DELIMS)||hasDuplicates(ENDDELIM))throw Error("Pyret Mode contains duplicate delimiter string values");var SPECIALDELIM=pyretMode.delimiters.special,SUBKEYWORDS=pyretMode.delimiters.subkeywords,DELIMTYPES=pyretMode.delimiters.types,LASTSUBKEYWORDS=(new RegExp("("+DELIMS.join("|")+"|"+ENDDELIM.join("|")+"|\\(|\\)|\\[|\\]|{|})","g"),pyretMode.delimiters.lastSubkeywords),INV_SUBKEYWORDS={},INV_LASTSUBKEYWORDS=(Object.keys(SUBKEYWORDS).forEach(function(key){SUBKEYWORDS[key].forEach(function(skw){INV_SUBKEYWORDS[skw]=INV_SUBKEYWORDS[skw]||[],INV_SUBKEYWORDS[skw].push(key)})}),{}),INV_DELIMTYPES=(Object.keys(LASTSUBKEYWORDS).forEach(function(key){var kw=LASTSUBKEYWORDS[key];INV_LASTSUBKEYWORDS[kw]=INV_LASTSUBKEYWORDS[kw]||[],INV_LASTSUBKEYWORDS[kw].push(key)}),{});function TokenTape(cm,line,ch,range){if(this.line=line,this.startCh=ch,this.cm=cm,this.min=range?range.from:cm.firstLine(),this.max=range?range.to-1:cm.lastLine(),this.lineToks=cm.getLineTokens(line),this.dbg=CodeMirror.debugInternal,ch<=1){for(this.current=0;this.current<this.lineToks.length&&!this.lineToks[this.current].type;)++this.current;this.current>=this.lineToks.length&&(this.current=null)}else{for(var i=0;i<this.lineToks.length;i++)if(this.lineToks[i].start<ch&&this.lineToks[i].end>=ch){this.current=i;break}void 0===this.current&&(console.warn("TokenTape: Given invalid start ch of "+ch+". Defaulting to last."),this.current=this.lineToks.length-1)}(this.cachedLine=null)===this.current?this.curRegion=null:0<this.lineToks.length?this.curRegion={start:Pos(this.line,this.lineToks[this.current].start),end:Pos(this.line,this.lineToks[this.current].end)}:this.curRegion={start:Pos(this.line,0),end:Pos(this.line,0)}}function posToString(p){return p?"{line: "+p.line+", ch: "+p.ch+"}":"null"}function tokenToString(t){return"{start: "+t.start+", end: "+t.end+", string: '"+t.string+"', type: "+t.type+", delimType: "+INV_DELIMTYPES[t.state.lineState.delimType]+"}"}function TokenTapeClone(tt){tt instanceof TokenTapeClone&&(tt=tt.__wrapped),this.__wrapped=tt,this.line=tt.line,this.cm=tt.cm,this.min=tt.min,this.max=tt.max,this.lineToks=tt.lineToks.slice(0),this.current=tt.current,this.cachedLine=tt.cachedLine,this.curRegion={start:tt.curRegion.start,end:tt.curRegion.end}}function IterResult(token,fail,subs,badSubs){this.token=token,this.fail=fail,this.subs=subs||[],this.badSubs=badSubs||[]}function initializeTape(cm,pos,foldOpen,range){var ttape=new TokenTape(cm,pos.line,pos.ch,range),start=ttape.findInit(foldOpen);if(ttape.dbg&&ttape.dbg.writeLn("Start token: "+(start&&tokenToString(start))),!start||(cm=Pos(start.line,start.start),range=pos,0<(cm.line-range.line||cm.ch-range.ch)))return{ttape:ttape,didNotMatch:!0};var startType=start.state.lineState.delimType;switch(startType){case DELIMTYPES.NONE:return ttape.dbg&&ttape.dbg.writeLn("Invalid delimiter type."),{ttape:ttape,didNotMatch:!0};case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.CLOSE_CONTD:case DELIMTYPES.SUB_CONTD:if(!foldOpen){if(!ttape.snapBack())return{ttape:ttape,didNotMatch:!0};startType=(start=ttape.cur()).state.lineState.delimType;break}case DELIMTYPES.FOLD_OPEN_CONTD:if(!ttape.snapBack())return{ttape:ttape,didNotMatch:!0};startType=(start=ttape.cur()).state.lineState.delimType}return{ttape:ttape,start:start,startType:startType,here:{from:Pos(start.line,start.start),to:Pos(start.line,start.end),token:start},didNotMatch:!1}}Object.keys(DELIMTYPES).forEach(function(key){INV_DELIMTYPES[DELIMTYPES[key]]=key}),TokenTape.prototype.toString=function(){for(var r,ret="TokenTape:\n\tline: "+this.line+"\n\tmin: "+this.min+"\n\tmax: "+this.max+"\n\tlineToks: [",i=0;i<this.lineToks.length;++i)0<i&&(ret+=",\n\t "),ret+="["+i+"] "+tokenToString(this.lineToks[i]);return ret+="]\n\tcurrent: "+this.current+"\n\tcurRegion: "+((r=this.curRegion)?"{start: "+posToString(r.start)+", end: "+posToString(r.end)+"}":"null")},TokenTapeClone.prototype=Object.create(TokenTape.prototype),TokenTape.prototype.clone=function(){return new TokenTapeClone(this)},TokenTape.prototype.setIndex=function(idx){this.current=idx,this.curRegion={start:Pos(this.line,this.lineToks[idx].start),end:Pos(this.line,this.lineToks[idx].end)}},TokenTape.prototype.nextLine=function(){var newCached;return this.line>=this.max?(this.current=null,this.curRegion=null,!1):(newCached={dir:-1,toks:this.lineToks},this.cachedLine&&1===this.cachedLine.dir?(this.lineToks=this.cachedLine.toks,++this.line):this.lineToks=this.cm.getLineTokens(++this.line),this.cachedLine=newCached,0===this.lineToks.length?this.nextLine():(this.setIndex(0),!0))},TokenTape.prototype.prevLine=function(){var newCached;return this.line<=this.min?(this.current=null,this.curRegion=null,!1):(newCached={dir:1,toks:this.lineToks},this.cachedLine&&-1===this.cachedLine.dir?(this.lineToks=this.cachedLine.toks,--this.line):this.lineToks=this.cm.getLineTokens(--this.line),this.cachedLine=newCached,0===this.lineToks.length?this.prevLine():(this.setIndex(this.lineToks.length-1),!0))},TokenTape.prototype.getContinued=function(){var contdType,idx=this.current,tok=this.lineToks[idx];if(this.current!==this.lineToks.length-1){switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:contdType=DELIMTYPES.OPEN_CONTD;break;case DELIMTYPES.CLOSING:contdType=DELIMTYPES.CLOSE_CONTD;break;case DELIMTYPES.SUBKEYWORD:contdType=DELIMTYPES.SUB_CONTD;break;default:return console.warn("getContinued called with bad current token"),void console.warn(tok)}for(;++idx<this.lineToks.length;)if(this.lineToks[idx].type){if(this.lineToks[idx].state.lineState.delimType!==contdType)break;tok=this.lineToks[idx]}this.curRegion.end=Pos(this.line,tok.end)}},TokenTape.prototype.getFoldingContinued=function(){var idx=this.current,tok=this.lineToks[idx];if(this.current!==this.lineToks.length-1){var contdType,foldContdType=null;switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:contdType=DELIMTYPES.OPEN_CONTD,foldContdType=DELIMTYPES.FOLD_OPEN_CONTD;break;case DELIMTYPES.CLOSING:contdType=DELIMTYPES.CLOSE_CONTD;break;case DELIMTYPES.SUBKEYWORD:contdType=DELIMTYPES.SUB_CONTD;break;default:return console.warn("getFoldingContinued called with bad current token"),void console.warn(tok)}for(;++idx<this.lineToks.length;)if(this.lineToks[idx].type){if(this.lineToks[idx].state.lineState.delimType!==contdType&&this.lineToks[idx].state.lineState.delimType!==foldContdType)break;tok=this.lineToks[idx]}this.curRegion.end=Pos(this.line,tok.end)}},TokenTape.prototype.snapBack=function(){var idx=this.current,tok=this.lineToks[idx];if(0===this.current)return!1;var initType,contdType=tok.state.lineState.delimType;switch(contdType){case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.FOLD_OPEN_CONTD:initType=DELIMTYPES.OPENING;break;case DELIMTYPES.CLOSE_CONTD:initType=DELIMTYPES.CLOSING;break;case DELIMTYPES.SUB_CONTD:initType=DELIMTYPES.SUBKEYWORD;break;default:console.warn("snapBack called with bad current token"),console.warn(tok)}for(;0<=--idx;)if(this.lineToks[idx].type){var curType=this.lineToks[idx].state.lineState.delimType;if(curType===initType)return this.setIndex(idx),!0;if(curType!==contdType)return!1}},TokenTape.prototype.move=function(dir,opts){if(null===this.current&&this.line<=this.min&&-1===dir)return!1;if(null===this.current&&this.line>=this.max&&1===dir)return!1;if(1!==dir&&-1!==dir)return console.warn("Expected direction of 1 or -1. Given: "+dir),!1;opts=opts||{};var moveLine=(1===dir?this.nextLine:this.prevLine).bind(this),isEOL=1===dir?function(i){return i>=this.lineToks.length-1}.bind(this):function(i){return i<=0},idx=this.current;for(this.lineToks[this.current];;){if(isEOL(idx)){if(!moveLine())return!1;idx=this.current}else idx+=dir;if((tok=>{if(tok.type){if(opts.includeContd)switch(tok.state.lineState.delimType){case DELIMTYPES.OPEN_CONTD:case DELIMTYPES.CLOSE_CONTD:case DELIMTYPES.SUB_CONTD:return 1;case DELIMTYPES.FOLD_OPEN_CONTD:if(opts.includeFoldContd)return 1}switch(tok.state.lineState.delimType){case DELIMTYPES.OPENING:case DELIMTYPES.CLOSING:case DELIMTYPES.SUBKEYWORD:return 1;default:return}}})(this.lineToks[idx]))return this.setIndex(idx),!0}},TokenTape.prototype.next=function(opts){return this.move(1,opts),this.cur()},TokenTape.prototype.prev=function(){return this.move(-1),this.cur()},TokenTape.prototype.cur=function(){var ret;return null===this.current||0===this.lineToks.length?null:((ret=this.lineToks[this.current]).line=this.line,ret)},TokenTape.prototype.findInit=function(folding){var cur=this.cur(),dbg=this.dbg;if(dbg&&this.dbg.writeLn("cur: "+(cur&&tokenToString(cur))),!cur)return null;function matchesFwd(tok){var diff,sameLine,allowed;return!(!tok||!tok.type)&&(diff=cmpClosest(Pos(tok.line,tok.start),Pos(tok.line,tok.end),startPos),sameLine=tok.line===startPos.line,allowed=tok.start<=truePos.ch,dbg&&dbg.writeLn("matchFwd: "+(tok&&tokenToString(tok))+"; diff = "+diff+"; sameLine = "+sameLine+"; allowed = "+allowed),sameLine)&&0===diff&&allowed}function matchesBwd(tok){var diff,sameLine;return!(!tok||!tok.type)&&(diff=cmpClosest(Pos(tok.line,tok.start),Pos(tok.line,tok.end),truePos),sameLine=tok.line===startPos.line,dbg&&dbg.writeLn("matchBwd: "+(tok&&tokenToString(tok))+"; diff = "+diff+"; sameLine = "+sameLine),sameLine)&&0===diff}var startPos=Pos(this.line,this.startCh+1),truePos=Pos(this.line,this.startCh),curIdx=(dbg&&(dbg.writeLn("startPos: "+posToString(startPos)),dbg.writeLn("truePos: "+posToString(truePos))),this.current);if(dbg&&this.dbg.writeLn("Checking if left at current position is closing"),matchesBwd(cur)&&cur.state.lineState.delimType===DELIMTYPES.CLOSING)return cur;if(dbg&&this.dbg.writeLn("Checking forward at current position"),(()=>{for(;this.line<startPos.line;)this.nextLine();this.setIndex(curIdx)})(),matchesFwd(cur))return cur;dbg&&this.dbg.writeLn("Checking right adjacent token");folding=this.next({includeContd:!0,includeFoldContd:folding});return matchesFwd(folding)?folding:((()=>{for(;this.line>startPos.line;)this.prevLine();this.setIndex(curIdx)})(),dbg&&this.dbg.writeLn("Checking for any on left"),matchesBwd(cur)?cur:null)},TokenTape.prototype.findMatchingToken=function(kw,dir){if(1!==Math.abs(dir))throw new Error("Invalid Direction Given to findMatchingToken: "+dir.toString());var curType=this.lineToks[this.current].state.lineState.delimType;if(curType!==DELIMTYPES.OPENING&&curType!==DELIMTYPES.CLOSING)throw new Error("Invalid starting token: "+this.lineToks[this.current]);function stackEmpty(){return 0===stack.length}var isFunctionName="function-name"===kw.type,kwOrig=kw,forward=(kw=kw.string,1===dir),stack=[],subs={},lastFound=[],badSubs={},getNext=(forward?this.next:this.prev).bind(this),deeperType=forward?DELIMTYPES.OPENING:DELIMTYPES.CLOSING,shallowerType=forward?DELIMTYPES.CLOSING:DELIMTYPES.OPENING,toksMatch=forward?function(tok){return keyMatches(kw,tok,isFunctionName)}:function(tok){return keyMatches(tok,kwOrig)},failIfNoMatch=!forward;for(var dealWithAfterLast=function(tok,parent){this.getContinued();var toAdd={from:this.curRegion.start,to:this.curRegion.end};forward?(badSubs[parent]=badSubs[parent]||[],badSubs[parent].push(toAdd)):-1===(INV_LASTSUBKEYWORDS[tok.string]||[]).indexOf(parent)?(subs[parent]=subs[parent]||[],subs[parent].push(toAdd)):(subs[parent]&&(badSubs[parent]=badSubs[parent]||[],subs[parent].forEach(function(child){badSubs[parent].push(child)})),subs[parent]=[toAdd])}.bind(this);;){var next=getNext();if(!next)return new IterResult(null,failIfNoMatch,kw?subs[kw]:[]);if(stackEmpty()&&next.state.lineState.delimType===DELIMTYPES.SUBKEYWORD)if(forward){var matchingSubs=SUBKEYWORDS[kw],lastSubs=LASTSUBKEYWORDS[kw];if(matchingSubs&&-1!==matchingSubs.indexOf(next.string)){-1!==lastFound.indexOf(kw)?dealWithAfterLast(next,kw):(lastSubs&&lastSubs===next.string&&lastFound.push(kw),subs[kw]=subs[kw]||[],this.getContinued(),subs[kw].push({from:this.curRegion.start,to:this.curRegion.end}));continue}}else{matchingSubs=INV_SUBKEYWORDS[next.string];if(matchingSubs){matchingSubs.forEach(function(key){var nextReg;lastFound.indexOf(key)?dealWithAfterLast(next,key):(this.getContinued(),nextReg={from:this.curRegion.start,to:this.curRegion.end},LASTSUBKEYWORDS[key]===next.string&&lastFound.push(key),subs[key]=subs[key]||[],subs[key].push(nextReg))});continue}}if(next.state.lineState.delimType===shallowerType){if(stackEmpty())return new IterResult({token:next,from:this.curRegion.start,to:this.curRegion.end},lastSubs=!(!kw||toksMatch(next)),lastSubs?[]:forward?subs[kw]:subs[next.string],forward?badSubs[kw]:badSubs[next.string]);stack.pop()}else(t=>t.state.lineState.delimType===deeperType)(next)&&stack.push(next)}},TokenTape.prototype.findMatchingOpen=function(kw){return this.findMatchingToken(kw,-1)},TokenTape.prototype.findMatchingClose=function(kw){return this.findMatchingToken(kw,1)},TokenTape.prototype.findMatchingParent=function(kw){kw=kw.string;var stack=[],skip=0,parents=INV_SUBKEYWORDS[kw];if(!parents)throw new Error("Non-Subkeyword given to findMatchingParent");for(;;){var prev=this.prev();if(!prev)return new IterResult(null,!0);if(0<skip)skip--;else{var prevIsLast=-1!==Object.keys(INV_LASTSUBKEYWORDS).indexOf(prev.string);if(0===stack.length&&prevIsLast)return new IterResult(null,!0);prevIsLast=prev.state.lineState.delimType;if(prevIsLast===DELIMTYPES.CLOSING)stack.push(prev);else{if(parents.indexOf(-1!==prev.string)&&0===stack.length)return new IterResult(prev,!1,[]);prevIsLast===DELIMTYPES.OPENING&&stack.pop()}}}},CodeMirror.registerHelper("fold","pyret",function(cm,start){var dbg=CodeMirror.debugInternal;dbg&&(dbg.clear(),dbg.writeLn("Folding Debug Info:"));var close,kw,ttape=initializeTape(cm,Pos(start.line,0),!0).ttape,openKw=ttape.cur();for(;openKw&&openKw.line===start.line;){if((kw=openKw)&&kw.state.lineState.delimType===DELIMTYPES.OPENING&&("("!==openKw.string||"builtin"!==openKw.type))return ttape.getFoldingContinued(),kw=ttape.curRegion.end,(close=ttape.findMatchingClose(openKw))&&close.token&&{from:kw,to:close.token.from};openKw=ttape.next()}}),CodeMirror.findMatchingKeyword=function(cm,pos,range){var dbg=CodeMirror.debugInternal,pos=(dbg&&(dbg.clear(),dbg.writeLn("Keyword Matching Debug Info:")),initializeTape(cm,pos,!0,range));if(pos.didNotMatch)return dbg&&dbg.writeLn("<no match>"),null;dbg&&(dbg.writeLn("Initial tape:"),dbg.writeLn(pos.ttape.toString()));var other,dbg=pos.ttape,start=pos.start,startType=pos.startType,pos=pos.here;return startType===DELIMTYPES.CLOSING?{open:(other=dbg.findMatchingOpen(start)).token,close:pos,at:"close",matches:!other.fail,extra:other.subs,extraBad:other.badSubs}:-1!=Object.keys(INV_SUBKEYWORDS).indexOf(start.string)&&startType!==DELIMTYPES.OPENING?(startType=dbg.findMatchingParent(start)).fail?{open:startType.token,close:pos,at:"close",matches:!1,extra:[],extraBad:startType.badSubs}:CodeMirror.findMatchingKeyword(cm,Pos(startType.token.line,startType.token.start+1),range):{open:pos,close:(other=dbg.findMatchingClose(start)).token,at:"open",matches:!other.fail,extra:other.subs,extraBad:other.badSubs}}}),(mod=>{"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../fold/pyret-fold")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../fold/pyret-fold"],mod):mod(CodeMirror)})(function(CodeMirror){function clear(cm){if(cm.state.keywordMarks)for(var i=0;i<cm.state.keywordMarks.length;i++)cm.state.keywordMarks[i].clear();cm.state.keywordMarks=[]}function doMatchKeywords(cm){cm.state.failedKeywordMatch=!1,cm.operation(function(){var cur,range,other,wordStyle,regionStyle;clear(cm),cm.somethingSelected()||(cur=cm.getCursor(),(range=cm.getViewport()).from=Math.min(range.from,cur.line),range.to=Math.max(cur.line+1,range.to),(cur=CodeMirror.findMatchingKeyword(cm,cur,range))&&(range="open"==cur.at?cur.open:cur.close,other="close"==cur.at?cur.open:cur.close,regionStyle=(wordStyle=cur.matches?other?"CodeMirror-matchingbracket":"CodeMirror-pyret-no-match-start":other?"CodeMirror-nonmatchingbracket":"CodeMirror-pyret-no-match-end")+"-region",cm.state.failedKeywordMatch=!cur.matches,cm.state.keywordMarks.push(cm.markText(range.from,range.to,{className:wordStyle+" "+("open"==cur.at?"open":"close")})),cur.extra.forEach(function(tok){cm.state.keywordMarks.push(cm.markText(tok.from,tok.to,{className:wordStyle}))}),cur.extraBad.forEach(function(tok){cm.state.keywordMarks.push(cm.markText(tok.from,tok.to,{className:"CodeMirror-nonmatchingbracket"}))}),other)&&(cm.state.keywordMarks.push(cm.markText(other.from,other.to,{className:wordStyle+" "+("close"==cur.at?"open":"close")})),cm.state.keywordMarks.push(cm.markText(cur.open.from,cur.close.to,{className:regionStyle}))))})}function maybeUpdateMatch(cm){cm.state.failedKeywordMatch&&doMatchKeywords(cm)}function nonBlankToken(tok){return null!==tok.type&&!/^\s*$/.test(tok.string)}function nextNonblankTokenAfter(cm,pos,allowAtCurrent){var line=pos.line,toks=cm.getLineTokens(line);if(allowAtCurrent)for(var i=0;i<toks.length;i++)if(toks[i].start==pos.ch&&nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(i=0;i<toks.length;i++)if(toks[i].start<=pos.ch&&toks[i].end>pos.ch)for(nonBlankToken(toks[i])&&i++;i<toks.length;i++)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(line+=1;line<=cm.lastLine();line++)for(toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i]}function prevNonblankTokenBefore(cm,pos){for(var line=pos.line,toks=cm.getLineTokens(line),i=toks.length-1;0<=i;i--)if(toks[i].start<pos.ch&&toks[i].end>=pos.ch)for(nonBlankToken(toks[i])&&i--;0<=i;i--)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i];for(line-=1;line>=cm.firstLine();line--)for(i=(toks=cm.getLineTokens(line)).length-1;0<=i;i--)if(nonBlankToken(toks[i]))return toks[i].line=line,toks[i]}CodeMirror.defineOption("matchKeywords",!1,function(cm,val,old){old&&old!=CodeMirror.Init&&(cm.off("cursorActivity",doMatchKeywords),cm.off("viewportChange",maybeUpdateMatch),clear(cm)),val&&(cm.state.matchBothKeywords="object"==typeof val&&val.bothKeywords,cm.on("cursorActivity",doMatchKeywords),cm.on("viewportChange",maybeUpdateMatch),doMatchKeywords(cm))}),CodeMirror.commands.toMatchingKeyword=function(cm){var found=CodeMirror.findMatchingKeyword(cm,cm.getCursor());found&&(found="close"==found.at?found.open:found.close)&&cm.extendSelection(found.to,found.from)},CodeMirror.commands.goBackwardSexp=function(cm){var cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),prev=(cursor.ch,prevNonblankTokenBefore(cm,cursor));!prev||cursor.ch!==cur.start&&nonBlankToken(cur)&&"COMMENT-END"!==prev.state.lastToken||(cursor={line:(cur=prev).line,ch:prev.start}),cur&&"comment"===cur.type&&"COMMENT-END"===cur.state.lastToken?((cm,pos,nestingDepth)=>{for(var line=pos.line,toks=cm.getLineTokens(line),i=toks.length-1;0<=i;i--)if(toks[i].start<pos.ch&&"COMMENT-START"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth)return pos={line:line,ch:toks[i].start},cm.extendSelection(pos,pos);for(line-=1;line>=cm.firstLine();line--)for(i=(toks=cm.getLineTokens(line)).length-1;0<=i;i--)if("COMMENT-START"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth)return pos={line:line,ch:toks[i].start},cm.extendSelection(pos,pos);pos={line:cm.firstLine(),ch:0},cm.extendSelection(pos,pos)})(cm,cursor,cur.state.commentNestingDepth+1):(prev=(prev=CodeMirror.findMatchingKeyword(cm,cursor))&&prev.open.from.line==cursor.line&&prev.open.from.ch==cursor.ch?null:prev)?cm.extendSelection(prev.open.from,prev.open.from):CodeMirror.commands.goBackwardToken(cm)},CodeMirror.commands.goForwardSexp=function(cm){var cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),next=nextNonblankTokenAfter(cm,cursor,!0);next&&(cursor.ch===cur.end||next.start===cursor.ch&&next.line===cur.line||!nonBlankToken(cur)||"COMMENT-START"===next.state.lastToken)&&(cursor={line:(cur=next).line,ch:next.start}),cur&&"comment"===cur.type&&"COMMENT-START"===cur.state.lastToken?((cm,pos,nestingDepth)=>{for(var line=pos.line,toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if(toks[i].start>pos.ch&&"COMMENT-END"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth-1)return pos={line:line,ch:toks[i].end},cm.extendSelection(pos,pos);for(line+=1;line<=cm.lastLine();line++)for(toks=cm.getLineTokens(line),i=0;i<toks.length;i++)if("COMMENT-END"===toks[i].state.lastToken&&toks[i].state.commentNestingDepth==nestingDepth-1)return pos={line:line,ch:toks[i].end},cm.extendSelection(pos,pos);pos={line:cm.lastLine(),ch:null},cm.extendSelection(pos,pos)})(cm,cursor,cur.state.commentNestingDepth):((cur=CodeMirror.findMatchingKeyword(cm,cursor))&&cur.close.to.line==cursor.line&&cur.close.to.ch==cursor.ch&&next&&(next.ch=next.end,cur=CodeMirror.findMatchingKeyword(cm,next)),cur?cm.extendSelection(cur.close.to,cur.close.to):CodeMirror.commands.goForwardToken(cm))},CodeMirror.commands.goBackwardToken=function(cm){var pos,cursor=cm.getCursor(),cur=cm.getTokenAt(cursor);if(cur)if("comment"===cur.type)CodeMirror.commands.goWordLeft(cm);else{if(cur.type&&cur.start<cursor.ch)pos={line:cursor.line,ch:cur.start};else{cur=prevNonblankTokenBefore(cm,cursor);if(!cur)return;pos={line:cur.line,ch:cur.start}}cm.extendSelection(pos,pos)}},CodeMirror.commands.goForwardToken=function(cm){var pos,cursor=cm.getCursor(),cur=cm.getTokenAt(cursor),next=nextNonblankTokenAfter(cm,cursor,!0);if(next&&(cursor.ch===cur.end||next.start===cursor.ch&&next.line===cur.line)&&(cursor={line:(cur=next).line,ch:next.start}),cur)if(nonBlankToken(cur)){if("comment"===cur.type){for(var index=cursor.ch-cur.start;index<cur.string.length;index++)if(" "!==cur.string[index]&&"\t"!==cur.string[index]&&(" "===cur.string[index+1]||"\t"==cur.string[index+1])){index++;break}return pos={line:cursor.line,ch:cur.start+index},void cm.extendSelection(pos,pos)}}else cur=nextNonblankTokenAfter(cm,cursor,!0);if(cur){if(cur.type&&cur.end>cursor.ch)pos={line:cursor.line,ch:cur.end};else{if(!(next=nextNonblankTokenAfter(cm,cursor)))return;pos={line:next.line,ch:next.end}}cm.extendSelection(pos,pos)}}}),((q,u,c)=>{function v(a,b,g){a.addEventListener?a.addEventListener(b,g,!1):a.attachEvent("on"+b,g)}function z(a){var b;return"keypress"==a.type?(b=String.fromCharCode(a.which),a.shiftKey?b:b.toLowerCase()):n[a.which]||r[a.which]||String.fromCharCode(a.which).toLowerCase()}function w(a){return"shift"==a||"ctrl"==a||"alt"==a||"meta"==a}function A(a,b){for(var d=[],e="+"===(e=a)?["+"]:(e=e.replace(/\+{2}/g,"+plus")).split("+"),g=0;g<e.length;++g){var m=e[g];B[m]&&(m=B[m]),b&&"keypress"!=b&&C[m]&&(m=C[m],d.push("shift")),w(m)&&d.push(m)}if(e=m,!(g=b)){if(!p)for(var c in p={},n)95<c&&c<112||n.hasOwnProperty(c)&&(p[n[c]]=c);g=p[e]?"keydown":"keypress"}return{key:m,modifiers:d,action:g="keypress"==g&&d.length?"keydown":g}}function d(a){function b(a){a=a||{};var l,b=!1;for(l in p)a[l]?b=!0:p[l]=0;b||(x=!1)}function g(a,b,t,f,g,d){var l,E=[],h=t.type;if(!k._callbacks[a])return[];for("keyup"==h&&w(a)&&(b=[a]),l=0;l<k._callbacks[a].length;++l){var e,c=k._callbacks[a][l];!f&&c.seq&&p[c.seq]!=c.level||h!=c.action||((e="keypress"==h&&!t.metaKey&&!t.ctrlKey)||(e=c.modifiers,e=b.sort().join(",")===e.sort().join(",")),e&&(e=f&&c.seq==f&&c.level==d,(!f&&c.combo==g||e)&&k._callbacks[a].splice(l,1),E.push(c)))}return E}function c(a,b,c,f){k.stopCallback(b,b.target||b.srcElement,c,f)||!1!==a(b,c)||(b.preventDefault?b.preventDefault():b.returnValue=!1,b.stopPropagation?b.stopPropagation():b.cancelBubble=!0)}function e(a){"number"!=typeof a.which&&(a.which=a.keyCode);var b=z(a);b&&("keyup"==a.type&&y===b?y=!1:k.handleKey(b,(a=>{var b=[];return a.shiftKey&&b.push("shift"),a.altKey&&b.push("alt"),a.ctrlKey&&b.push("ctrl"),a.metaKey&&b.push("meta"),b})(a),a))}function m(a,g,t,f){function l(g){c(t,g,a),"keyup"!==f&&(y=z(g)),setTimeout(b,10)}for(var d=p[a]=0;d<g.length;++d){var e=d+1===g.length?l:(c=>function(){x=c,++p[a],clearTimeout(q),q=setTimeout(b,1e3)})(f||A(g[d+1]).action);n(g[d],e,f,a,d)}}function n(a,b,c,f,d){k._directMap[a+":"+c]=b;var e=(a=a.replace(/\s+/g," ")).split(" ");1<e.length?m(a,e,b,c):(c=A(a,c),k._callbacks[c.key]=k._callbacks[c.key]||[],g(c.key,c.modifiers,{type:c.action},f,a,d),k._callbacks[c.key][f?"unshift":"push"]({callback:b,modifiers:c.modifiers,action:c.action,seq:f,level:d,combo:a}))}var k=this;if(a=a||u,!(k instanceof d))return new d(a);k.target=a,k._callbacks={};var q,p={},y=!(k._directMap={}),r=!1,x=!1;k._handleKey=function(a,d,e){for(var f=g(a,d,e),k=0,l=!(d={}),h=0;h<f.length;++h)f[h].seq&&(k=Math.max(k,f[h].level));for(h=0;h<f.length;++h)f[h].seq?f[h].level==k&&(l=!0,d[f[h].seq]=1,c(f[h].callback,e,f[h].combo,f[h].seq)):l||c(f[h].callback,e,f[h].combo);f="keypress"==e.type&&r,e.type!=x||w(a)||f||b(d),r=l&&"keydown"==e.type},k._bindMultiple=function(a,b,c){for(var d=0;d<a.length;++d)n(a[d],b,c)},v(a,"keypress",e),v(a,"keydown",e),v(a,"keyup",e)}if(q){var p,n={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},r={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},C={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},B={option:"alt",command:"meta",return:"enter",escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"};for(c=1;c<20;++c)n[111+c]="f"+c;for(c=0;c<=9;++c)n[c+96]=c.toString();d.prototype.bind=function(a,b,c){return a=a instanceof Array?a:[a],this._bindMultiple.call(this,a,b,c),this},d.prototype.unbind=function(a,b){return this.bind.call(this,a,function(){},b)},d.prototype.trigger=function(a,b){return this._directMap[a+":"+b]&&this._directMap[a+":"+b]({},a),this},d.prototype.reset=function(){return this._callbacks={},this._directMap={},this},d.prototype.stopCallback=function(a,b){var c;return!(-1<(" "+b.className+" ").indexOf(" mousetrap ")||function D(a,b){return null!==a&&a!==u&&(a===b||D(a.parentNode,b))}(b,this.target))&&("INPUT"==(b="composedPath"in a&&"function"==typeof a.composedPath&&(c=a.composedPath()[0])!==a.target?c:b).tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable)},d.prototype.handleKey=function(){return this._handleKey.apply(this,arguments)},d.addKeycodes=function(a){for(var b in a)a.hasOwnProperty(b)&&(n[b]=a[b]);p=null},(d.init=function(){var b,a=d(u);for(b in a)"_"!==b.charAt(0)&&(d[b]=(b=>function(){return a[b].apply(a,arguments)})(b))})(),q.Mousetrap=d,"undefined"!=typeof module&&module.exports&&(module.exports=d),"function"==typeof define&&define.amd&&define(function(){return d})}})("undefined"!=typeof window?window:null,"undefined"!=typeof window?document:null),(a=>{var c={},d=a.prototype.stopCallback;a.prototype.stopCallback=function(e,b,a,f){return!!this.paused||!c[a]&&!c[f]&&d.call(this,e,b,a)},a.prototype.bindGlobal=function(a,b,d){if(this.bind(a,b,d),a instanceof Array)for(b=0;b<a.length;b++)c[a[b]]=!0;else c[a]=!0},a.init()})(Mousetrap),window.logger={},function(){this.log=function(){console.log.apply(console,arguments)}}),DummyBackend=function(){this.log=function(_,__){}},AJAXBackend=function(url){this.log=function(name,obj){var request=new XMLHttpRequest;request.open("POST",url,!0),request.send(JSON.stringify(obj))}},logger=(backend=>{var sessionStorage,localStorage;try{sessionStorage=window.localStorage,localStorage=window.sessionStorage}catch(e){sessionStorage={getItem:function(){},setItem:function(){}},localStorage={getItem:function(){},setItem:function(){}}}function guid(){for(var array=new Uint32Array(6),str=(window.crypto.getRandomValues(array),""),i=0;i<array.length;i++)str=str.concat(array[i].toString(36));return str}_identifiers={};var _identifiers,identifiers={get localID(){return _identifiers.lid||storedID(localStorage,"lid")},get sessionID(){return _identifiers.sid||storedID(sessionStorage,"sid")},get windowID(){return _identifiers.tid=_identifiers.tid||guid(),_identifiers.tid}};function storedID(storage,type){var id=storage.getItem(type);return null!==id&&""!==id||(id=_identifiers[type]||guid(),_identifiers[type]=id,storage.setItem(type,id)),id}function log(name,obj){(obj=obj instanceof Object?obj:{}).meta=[Date.now(),name,identifiers.windowID,identifiers.sessionID,identifiers.localID,GIT_REV,GIT_BRANCH],backend.log(name,obj)}var isDetailed="true"==localSettings.getItem("log-detailed");return{guid:guid,log:log,get isDetailed(){var nowIsDetailed="true"==localSettings.getItem("log-detailed");return isDetailed!=nowIsDetailed&&(log("LOG_DETAIL_CHANGED",{detailed:nowIsDetailed}),isDetailed=nowIsDetailed),nowIsDetailed}}})(LOG_URL?new AJAXBackend(LOG_URL):new DummyBackend),gwrap=(window.CodeMirror&&CodeMirror.defineOption("logging",!1,function(cm,new_value){1==new_value&&(cm.CPO_editorID||(cm.CPO_editorID=logger.guid()),logger.log("cm_init",{CPO_editorID:cm.CPO_editorID}),cm.on("change",function(cm,change){logger.isDetailed&&(change.CPO_editorID=cm.CPO_editorID,logger.log("cm_change",change))}),cm.on("focus",function(cm){logger.isDetailed&&logger.log("cm_focus",{CPO_editorID:cm.CPO_editorID})}),cm.on("blur",function(cm){logger.isDetailed&&logger.log("cm_blur",{CPO_editorID:cm.CPO_editorID})}))}),logger.log("load"),window.addEventListener("unload",function(event){logger.log("unload")}),document.addEventListener("visibilitychange",function(){logger.log("pagevis",{visibility:document.visibilityState})}),window.makeShareAPI=function(pyretVersion){var showingNeedingHidden=[];function makeShareUrl(id){id="/editor#share="+id;return""!==pyretVersion&&(id+="&v="+pyretVersion),window.location.origin+id}function getImportLetter(letter){letter=letter.toUpperCase();return!!/[A-Z]/.exec(letter)?letter:"M"}return $(".menuButton a").click(function(){showingNeedingHidden.forEach(function(hideIt){hideIt()})}),{makeShareLink:function(originalFile){var link=$('<button aria-label="Publish, F9" aria-describedby="mhelp-menus mhelp-activate mhelp-escape" class="focusable blueButton" role="menuitem" tabindex="-1">').text("Publish"),shareDiv=$("<div>").addClass("share");return link.click(function(){!function showShares(container,originalFile){function showNewSharePrompt(){var newShare=new modalPrompt({title:"Publish this file",style:"confirm",submitText:"Publish",narrow:!0,options:[{message:"This program has not been shared before. Publishing it by clicking below will make a new copy of the file that you can share with anyone you like. They will be able to see your code and run your program."}]});newShare.show().then(function(confirmed){!0===confirmed&&window.CPO.save().then(function(p){window.stickMessage("Copying...");p=p.makeShareCopy();p.fail(function(err){window.flashError("Couldn't copy the file for sharing.")}),p.then(function(f){return window.flashMessage("File published successfully"),showShares(container,originalFile)})})}).fail(function(err){console.error("Error showing the share dialog",err)})}function showExistingSharePrompt(instances){var f=instances[0],shareUrl=makeShareUrl(f.getUniqueId()),importLetter=getImportLetter(f.getName()[0]),f='import shared-gdrive("'+f.getName()+'", "'+f.getUniqueId()+'") as '+importLetter,importLetter=new modalPrompt({title:"Share or update the published copy",style:"copyText",submitText:"Update",options:[{message:"You can copy the link below to share the most recently published version with others.",text:shareUrl},{message:"You can copy the code below to use the published version as a library.",text:f},{message:"You can also click Update below to copy the current version to the published version, or click Cancel to exit this window."}]});importLetter.show(function(republish){republish&&window.CPO.save().then(function(p){window.stickMessage("Republishing file..."),p.getContents().then(function(contents){contents=instances[0].save(contents,!1);contents.fail(function(err){window.flashError("Couldn't publish the file.")}),contents.then(function(f){window.flashMessage("Published program updated.")})}).fail(function(){window.flashError("Couldn't get the file contents for publishing")})})})}var shares=originalFile.getShares();shares.then(function(sharedInstances){0===sharedInstances.length?showNewSharePrompt():showExistingSharePrompt(sharedInstances)})}(shareDiv,originalFile)}),link},makeShareUrl:makeShareUrl}},window.gwrap={load:function(params){var ret;if(params&¶ms.reauth&&void 0!==params.reauth.immediate)return ret=Q.defer(),loadAPIWrapper(params.reauth.immediate).then(function(gw){var copy=$.extend({},params);delete copy.reauth,gw.load(copy).then(function(loaded){loaded.auth=gw.auth,loaded.hasAuth=function(){return null!==gw.auth},ret.resolve(loaded)})}).fail(function(err){ret.reject(err)}),ret.promise;throw new Error("Google API Wrapper not yet initialized")},request:function(){throw new Error("Google API Wrapper not yet initialized")}});function reauth(immediate,useFullScopes){var d=Q.defer();return immediate?((immediate=$.ajax("/getAccessToken",{method:"get",datatype:"json"})).then(function(t){gapi.auth.setToken({access_token:t.access_token}),logger.log("login",{user_id:t.user_id}),d.resolve({user_id:t.user_id,access_token:t.access_token})}),immediate.fail(function(t){d.resolve(null)})):(immediate="/login?redirect="+encodeURIComponent("/close.html"),useFullScopes&&(immediate+="&scopes=full"),window.addEventListener("message",function(e){(e.domain||e.origin)===document.location.origin?d.resolve(reauth(!0,useFullScopes)):d.resolve(null)}),window.open(immediate)),d.promise}window.reauth=reauth;var _GWRAP_APIS={};function loadAPIWrapper(immediate){function assertDefined(v){if(void 0===window[v])throw new Error("Cannot initialize wrapper! Missing required definition: "+v)}function GoogleAPIError(message){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=message||""}assertDefined("gapi"),assertDefined("apiKey"),assertDefined("Q"),(GoogleAPIError.prototype=Object.create(Error.prototype)).name="GoogleAPIError";var GAPIError=GoogleAPIError.prototype.constructor=GoogleAPIError;function AuthenticationError(message){this.message=message||""}function APIResponseError(response){this.message=(response=response||{}).message||"",this.code=response.code||null,this.response=response}function authCheck(f){function isAuthFailure(result){return result&&(result.error&&result.error.code&&401===result.error.code||result.code&&401===result.code)}return f().then(function(result){return isAuthFailure(result)?function(){return 0<arguments.length&&console.warn("The `immediate` argument to `refresh()` is deprecated."),reauth(!0)}().then(function(authResult){return!authResult||authResult.error?{error:{code:401,message:"Couldn't re-authorize"}}:f()}):result}).then(function(result){if(isAuthFailure(result))throw new AuthenticationError("Authentication failure");return result})}function failCheck(p){return p.then(function(result){if(result&&"number"==typeof result.code&&400<=result.code)throw console.error("40X Error getting Google API response: ",result),new APIResponseError(result);if(result&&result.error)throw console.error("Error getting Google API response: ",result),new APIResponseError(result);return result})}function gQ(makeRequest,skipAuth){var oldAccess=gapi.auth.getToken(),ret=(skipAuth&&gapi.auth.setToken({access_token:null}),failCheck(authCheck(function(){var d=Q.defer();return makeRequest().execute(function(result){d.resolve(result)}),d.promise})));return skipAuth&&setTimeout(function(){gapi.auth.setToken(oldAccess)}),ret}(AuthenticationError.prototype=Object.create(GoogleAPIError.prototype)).name="AuthenticationError",AuthenticationError.prototype.constructor=AuthenticationError,(APIResponseError.prototype=Object.create(GoogleAPIError.prototype)).name="APIResponseError",APIResponseError.prototype.constructor=APIResponseError;var cachedAPIS=[];function loadAPI(params){if(!params)throw new GoogleAPIError("Missing API loading parameters");if(params.reauth){if(void 0===params.reauth.immediate)throw new GoogleAPIError("Missing required field to load(): params.reauth.immediate");var reloaded=Q.defer();return loadAPIWrapper(params.reauth.immediate).then(function(gw){var copy=$.extend({},params);delete copy.reauth,gw.load(copy).then(function(loaded){reloaded.resolve(loaded)})}),reloaded.promise}for(var i=0;i<cachedAPIS.length;++i){var cached=cachedAPIS[i];if(params.name&&cached.query.name===params.name)return cached.api;if(params.url&&cached.query.url===params.url)return cached.api}var preKeys=Object.keys(gapi.client);function processKey(key){var api;return key in _GWRAP_APIS||(api=gapi.client[key],_GWRAP_APIS[key]={},void 0!==api&&function processObject(obj,dest){Object.keys(obj).forEach(function(key){var original;"object"==typeof obj[key]?(dest[key]={},processObject(obj[key],dest[key])):"function"==typeof obj[key]?(original=obj[key],dest[key]=function(args,skipAuth){return gQ(function(){return original(args)},skipAuth)}):dest[key]=obj[key]})}(api,_GWRAP_APIS[key])),_GWRAP_APIS[key]}function processDelta(){var ret,newKeys=Object.keys(gapi.client).filter(function(k){return-1===preKeys.indexOf(k)});return 1<newKeys.length?ret=newKeys.map(processKey):params.name&&0===newKeys.length?gapi.client[params.name]&&(ret=processKey(params.name)):ret=processKey(newKeys[0]),ret?cachedAPIS.push({query:params,api:ret}):console.warn("loadAPI: Nothing to return!"),ret}var ret,name=params.name||params.url,version=params.version;return params.callback?(gapi.client.load(name,version,function(){params.callback(processDelta())}),null):(ret=Q.defer(),gapi.client.load(name,version,function(){ret.resolve(processDelta())}),ret.promise)}return reauth(immediate).then(function(auth){function makeWrapped(){this.GoogleAPIError=GoogleAPIError,this.GAPIError=GAPIError,this.AuthenticationError=AuthenticationError,this.APIResponseError=APIResponseError,this.load=loadAPI,this.withAuth=function(f){return failCheck(authCheck(f))},this.request=function(params,skipAuth){return gQ(function(){return gapi.client.request(params)},skipAuth)},this.auth=auth,this.hasAuth=function(){return null!==auth}}return makeWrapped.prototype=_GWRAP_APIS,gwrap=new makeWrapped})}function makeUrlFile(url){var p=Q.defer();return p.resolve({shared:!0,getOriginal:function(){throw new Error("Cannot getOriginal for a file created from a URL")},getContents:function(){let ans=Q.defer();return fetch(url).then(async function(contents){ans.resolve(await contents.text())}).catch(function(err){ans.reject(err)}),ans.promise},getName:function(){var lastSlash=String(url).lastIndexOf("/");return-1===lastSlash?url:url.slice(lastSlash+1)},getModifiedTime:function(){return new Date},getUniqueId:function(){return url}}),p.promise}function FilePicker(options){this.options=options=options||{},this.dataHandler=options.onSelect,this.onLoaded=options.onLoaded||function(){},this.onError=options.onError||function(m){throw console.error(m),new gwrap.GAPIError(m)},this.onInternalError=options.onInternalError||this.onError,this.raisedError=!1,storageAPI.then(function(){gapi.load("picker",{callback:function(){this.init(google.picker),this.onLoaded()}.bind(this)})}.bind(this))}function createSheetsAPI(immediate){function createAPI(spreadsheets){var _COLUMNS_ONE_INDEXED=!0;let SHEET_REQ_FIELDS=["properties(defaultFormat,title)","sheets("+["data("+"rowData(values(effectiveFormat/numberFormat,effectiveValue,formattedValue))"+",startColumn,startRow)","properties("+"gridProperties(columnCount,frozenColumnCount,frozenRowCount,rowCount)"+",index,sheetId,title)"].join(",")+")","spreadsheetId"].join(",");function SheetsError(message,extra){"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=message||"",this.extra=extra||{}}function colAsString(col){if(isNaN(col)){if("string"!=typeof col)throw new SheetsError("Invalid column: "+(col&&col.toString()));return col}for(var out="";0<col;){var modulo=(col-(_COLUMNS_ONE_INDEXED?1:0))%26,out=String.fromCharCode(65+modulo)+out;col=Math.floor((col-modulo)/26)}return out}function colAsNumber(col){if("string"==typeof col){for(var colNum=0,power=1,i=col.length-1;0<=i;--i)colNum+=(col.charCodeAt(i)-65+1)*power,power*=26;return colNum-(_COLUMNS_ONE_INDEXED?1:0)}if(isNaN(col))throw new SheetsError("Invalid column: "+(col&&col.toString()));return col}(SheetsError.prototype=Object.create(Error.prototype)).name="SheetsError",SheetsError.prototype.constructor=SheetsError;let VALUE_TYPES={STRING:1,NUMBER:2,BOOL:3,NONE:4};function unifyRows(rowData,skipHeaders,onlyInfer){var errors=[],rowSchemas=[],schema=[],startCol=1/0,endCol=0,startRow=0;function processValue(v,idx){if(!v)throw new SheetsError("Internal Error: unifyRows called with no value");if(!v.effectiveValue)return{value:null,type:VALUE_TYPES.NONE};if(startCol=Math.min(startCol,idx),endCol=Math.max(endCol,idx),void 0===v.effectiveValue.numberValue)return void 0!==v.effectiveValue.boolValue?{value:v.effectiveValue.boolValue,type:VALUE_TYPES.BOOL}:v.effectiveValue.errorValue?("N_A"===v.effectiveValue.errorValue.type?errors.push("Google Sheets Error: there are #N/A values in the sheet, so it cannot be loaded correctly. The #N/A values must first be fixed before importing."):errors.push("Google Sheets Error: "+v.effectiveValue.errorValue),{value:null,type:VALUE_TYPES.NONE}):{value:v.formattedValue,type:VALUE_TYPES.STRING};var idx=v.effectiveFormat&&v.effectiveFormat.numberFormat&&v.effectiveFormat.numberFormat.type,asStr=v.formattedValue||v.effectiveValue.numberValue.toString();switch(idx){case"TEXT":case"DATE":case"TIME":case"DATE_TIME":return{value:asStr,type:VALUE_TYPES.STRING};default:return{value:v.effectiveValue.numberValue,type:VALUE_TYPES.NUMBER}}}function typeName(t){switch(t){case VALUE_TYPES.STRING:return"String";case VALUE_TYPES.NUMBER:return"Number";case VALUE_TYPES.BOOL:return"Bool";default:VALUE_TYPES.NONE;return"Option"}}var foundFirstRow=!1,foundHeaders=!1,emptyRows=[];rowData=rowData.map(function(row,rowNum){if(row.values&&0<row.values.length&&row.values.some(function(v){return void 0!==v.effectiveValue})){if(!foundHeaders&&skipHeaders)return foundHeaders=!0,startRow+=1,rowSchemas.push([]),[];foundFirstRow=!0;var extracted=((row,rowNum)=>row.reduce(function(acc,cur,idx){return acc.values.push(cur.value),acc.schema.push({type:cur.type,isOption:cur.type===VALUE_TYPES.NONE,trueRow:rowNum,trueCol:idx}),acc},{values:[],schema:[]}))(row.values.map(processValue),rowNum);return row.values=extracted.values,rowSchemas.push(extracted.schema),row.values}return foundFirstRow?emptyRows.push(rowNum):startRow+=1,rowSchemas.push([]),[]});for(var i=emptyRows.length-1;0<=i;--i)rowData.splice(emptyRows[i],1),rowSchemas.splice(emptyRows[i],1);rowData.splice(0,startRow),rowSchemas.splice(0,startRow);for(var tableWidth=endCol-startCol+1,i=0;i<rowData.length;++i){rowData[i]=rowData[i].slice(startCol,endCol+1),rowSchemas[i]=rowSchemas[i].slice(startCol,endCol+1);for(var j=rowData[i].length;j<tableWidth;++j)rowData[i][j]=null,rowSchemas[i].push({type:VALUE_TYPES.NONE,isOption:!1})}for(i=0;i<rowSchemas.length;++i)for(j=0;j<Math.max(schema.length,rowSchemas[i].length);++j)schema[j]=((schema1,schema2,row,index)=>{function logFail(){var trueRow,data,trueCol;onlyInfer&&!onlyInfer.includes(schema2.trueCol)||(trueRow=schema2.trueRow,trueCol=schema2.trueCol,"string"==typeof(data=rowData[row][index])&&(data='"'+data+'"'),trueCol="All items in every column must have the same type. We expected to find a "+typeName(schema1.type)+" at cell "+colAsString(trueCol+1)+(trueRow+1)+", but we instead found this "+typeName(schema2.type)+": "+data+".",(schema1.type===VALUE_TYPES.STRING&&schema2.type===VALUE_TYPES.NUMBER||schema1.type===VALUE_TYPES.NUMBER&&schema2.type===VALUE_TYPES.STRING)&&(trueCol+=' If you want some Numbers to be read as Strings, you need to format those cells in Google Sheets as "Plain Text" (Select the cells, click "Format", then click "Number", and then click "Plain Text").'),errors.push(trueCol))}return schema1?schema1.type===VALUE_TYPES.NONE?schema2.type===VALUE_TYPES.NONE?schema1:(schema2.isOption=!0,schema2):(schema1.isOption?schema2.type!==VALUE_TYPES.NONE&&schema2.type!==schema1.type&&logFail():schema2.type===VALUE_TYPES.NONE?schema1.isOption=!0:schema1.type!==schema2.type&&logFail(),schema1):schema2})(schema[j],rowSchemas[i][j],i,j);var ret={values:rowData,schema:schema,startCol:startCol};return 0<errors.length&&(ret.errors=errors),ret}function Spreadsheet(data){this.id=data.spreadsheetId,this.title=data.properties.title,this.defaultFormat=data.properties.defaultFormat||{},data.sheets=data.sheets||[],this.worksheetsInfo=[],this.worksheets=data.sheets.map(function(wsdata){return new Worksheet(this,wsdata)},this)}function Worksheet(spreadsheet,data){if(!data)throw new SheetsError("Worksheet: Internal Error: No data. Please report this error to the developers.");if(!data.properties)throw new SheetsError("Worksheet: Internal Error: No properties. Please report this error to the developers.");this.id=data.properties.sheetId,this.title=data.properties.title,this.rows=data.properties.gridProperties.rowCount,this.cols=data.properties.gridProperties.columnCount,this.index=data.properties.index,spreadsheet.worksheetsInfo[this.index]={properties:data.properties},this.cache=[],this.spreadsheet=spreadsheet,this.rawData=data,this.listener={handleEvent:function(){return this.flushCache(!0)}.bind(this)},void 0===window?(console.warn("No window detected. Sheets may fall out of sync."),this.useTimer=!1):(window.addEventListener("pyret-save",this.flushCache.bind(this),!1),this.useTimer=!0)}return Spreadsheet.prototype.lookupInfoByName=function(name){for(var worksheetIdx=-1,i=0;i<this.worksheetsInfo.length;++i)if(this.worksheetsInfo[i].properties.title===name){worksheetIdx=i;break}if(-1===worksheetIdx)throw new SheetsError('No worksheet with name "'+name+'"');return this.worksheetsInfo[worksheetIdx]},Spreadsheet.prototype.lookupInfoByIndex=function(worksheetIdx){if(worksheetIdx>=this.worksheetsInfo.length)throw new SheetsError("No worksheet with index "+worksheetIdx);return this.worksheetsInfo[worksheetIdx]},Spreadsheet.prototype.getByIndex=function(worksheetIdx,skipHeaders,onlyInfer){this.lookupInfoByIndex(worksheetIdx);worksheetIdx=this.worksheets[worksheetIdx];return worksheetIdx.init(skipHeaders,onlyInfer),worksheetIdx},Spreadsheet.prototype.getByName=function(name,skipHeaders,onlyInfer){name=this.lookupInfoByName(name),name=this.worksheets[name.properties.index];return name.init(skipHeaders,onlyInfer),name},Spreadsheet.prototype.addWorksheet=function(name,index){var request={addSheet:{properties:{title:name}}};return void 0!==index&&(request.addSheet.properties.index=index),spreadsheets.batchUpdate({spreadsheetId:this.id,resource:{requests:[request]}}).then(function(data){return spreadsheets.get({spreadsheetId:this.id,ranges:name,fields:SHEET_REQ_FIELDS})}.bind(this)).then(function(data){if(data.sheets&&0!==data.sheets.length)return(data=new Worksheet(this,data.sheets[0])).init(!1),data;throw new SheetsError('Failed to add worksheet: "'+name+'"')}.bind(this)).fail(function(err){throw err.message&&/already exists/.test(err.message)?new SheetsError('A sheet with name "'+name+'" already exists in this spreadsheet.'):err})},Spreadsheet.prototype.deleteSheetById=function(id){return spreadsheets.batchUpdate({spreadsheetId:this.id,resource:{requests:[{deleteSheet:{sheetId:id}}]}}).then(function(_){return!0}).fail(function(err){throw err.message&&/sheet with ID.*does not exist/.test(err.message)?new SheetsError('A sheet with ID "'+id+'" does not exist in this spreadsheet.'):err})},Spreadsheet.prototype.deleteSheetByName=function(name){return this.deleteSheetById(this.lookupInfoByName(name).properties.sheetId).fail(function(err){throw err.message&&/does not exist in this spreadsheet/.test(err.message)?new SheetsError(err.message.replace(/ID "[^"]*"/,'name "'+name+'"')):err})},Spreadsheet.prototype.deleteSheetByIndex=function(idx){return this.deleteSheetById(this.lookupInfoByIndex(idx).properties.sheetId)},Worksheet.prototype.init=function(skipHeaders,onlyInfer){if(void 0!==this.hasHeaders&&this.hasHeaders!==!skipHeaders)throw new SheetsError("Attempted to load worksheet with"+(skipHeaders?"out":"")+" headers, but worksheet was already previously loaded with"+(skipHeaders?"":"out")+" headers.");if(void 0===this.data){var data=this.rawData;if(this.hasHeaders=!skipHeaders,data.data&&data.data[0]&&data.data[0].rowData){data=unifyRows(data.data[0].rowData,skipHeaders,onlyInfer);if(this.startCol=data.startCol,this.data=data.values,this.schema=data.schema,this.typeErrors=data.errors,!this.data)throw new SheetsError("Worksheet: Internal Error: Type-check yielded no values. Please report this error to the developers.");if(!this.schema)throw new SheetsError("Worksheet: Internal Error: Type-check yielded no schema. Please report this error to the developers.")}else this.data=[],this.startCol=0,this.schema=[]}},Worksheet.prototype.clearTimer=function(){this.useTimer&&void 0!==this.timeoutId&&(window.removeEventListener("beforeunload",this.listener),window.clearTimeout(this.timeoutId),this.timeoutId=void 0)},Worksheet.prototype.resetTimer=function(){this.useTimer&&(this.clearTimer(),window.addEventListener("beforeunload",this.listener),this.timeoutId=window.setTimeout(this.flushCache.bind(this),1e4))},Worksheet.prototype.getCellAt=function(col,row){return this.getCellRange(col,row,col,row).then(function(arr){return arr[0][0]})},Worksheet.prototype.setCellAt=function(col,row,val){return this.setCellRange(col,row,col,row,[[val]])},Worksheet.prototype.setCellRange=function(fromCol,fromRow,toCol,toRow,values){fromCol=((title,fromCol,fromRow,toCol,toRow)=>(toCol=fromCol===toCol?fromCol=colAsString(fromCol):(fromCol=colAsString(fromCol),colAsString(toCol)),title+"!"+fromCol+fromRow+":"+toCol+toRow))(this.title,fromCol,fromRow,toCol,toRow);return this.cache.push({range:fromCol,majorDimension:"ROWS",values:values}),this.resetTimer(),!0},Worksheet.prototype.flushCache=function(noRefresh){var promise;return this.clearTimer(),0===this.cache.length?Q(this):(promise=spreadsheets.values.batchUpdate({spreadsheetId:this.spreadsheet.id,resource:{data:this.cache}}),this.cache=[],promise.then((noRefresh?function(){return this}:this.refresh).bind(this)))},Worksheet.prototype.getAllCells=function(){return this.flushCache().then(function(){return this.data}.bind(this))},Worksheet.prototype.getCellRange=function(fromCol,fromRow,toCol,toRow){return fromCol=colAsNumber(fromCol),toCol=colAsNumber(toCol),this.flushCache().then(function(){return this.data.map(function(row){return row.slice(fromCol-this.startCol,toCol-this.startCol+1)}.bind(this)).slice(fromRow-1,toRow)}.bind(this))},Worksheet.prototype.updateName=function(name){var ret=spreadsheets.batchUpdate({spreadsheetId:this.spreadsheet.id,resource:{requests:[{updateSheetProperties:{properties:{title:name},fields:"title"}}]}});return ret.then(function(_){this.title=name}.bind(this)),ret},Worksheet.prototype.refresh=function(){return spreadsheets.get({spreadsheetId:this.spreadsheet.id,ranges:this.title,fields:SHEET_REQ_FIELDS}).then(function(data){if(data.sheets&&data.sheets[0]&&data.sheets[0].data&&data.sheets[0].data[0]&&data.sheets[0].data[0].rowData)return this.rawData=data.sheets[this.index],this.init(),this;throw new SheetsError("Worksheet data not returned by Google. Please report this error to the developers.")}.bind(this))},Spreadsheet.fromId=function(id){return spreadsheets.get({spreadsheetId:id,fields:SHEET_REQ_FIELDS},!0).then(function(data){return new Spreadsheet(data)},function(err){throw new SheetsError('No Spreadsheet with id "'+id+'" found')})},Spreadsheet.fromFile=function(file){return Spreadsheet.fromId(file.getUniqueId())},{createSpreadsheet:function(name){var opts={mimeType:"application/vnd.google-apps.spreadsheet",fileExtension:!1},ret=Q.defer();return storageAPI.then(function(api){return api.createFile(name,opts)}).then(function(file){return spreadsheets.get({spreadsheetId:file.getUniqueId()})}).then(function(data){ret.resolve(new Spreadsheet(data))}).fail(ret.reject),ret.promise},loadSpreadsheetByName:function(name){return storageAPI.then(function(api){return api.getFileByName(name)}).then(function(res){if(0===res.length)throw new SheetsError('No spreadsheet named "'+name+'" found.');return res[0]}).then(Spreadsheet.fromFile)},loadSpreadsheetById:function(id){return Spreadsheet.fromId(id)},TYPES:VALUE_TYPES}}var ret=Q.defer();return gwrap.load({url:"https://sheets.googleapis.com/$discovery/rest?version=v4",reauth:{immediate:immediate},callback:function(sheets){if(Array.isArray(sheets)){for(var i=0;i<sheets.length;i+=1)if(sheets[i].spreadsheets)return void ret.resolve(createAPI(sheets[i].spreadsheets));ret.reject("Sheets could not load")}else ret.resolve(createAPI(sheets.spreadsheets))}}),ret.promise}window.createProgramCollectionAPI=function(collectionName,immediate,publicOnly){Error.prototype;var drive,FOLDER_MIME="application/vnd.google-apps.folder",BACKREF_KEY="originalProgram";function createAPI(baseCollection){function makeSharedFile(googFileObject,fetchFromGoogle){return{shared:!0,getOriginal:function(){return gapi.client.drive.properties.get({fileId:googFileObject.id,propertyKey:BACKREF_KEY,visibility:"PRIVATE"})},getContents:function(){var reqUrl;return fetchFromGoogle?(reqUrl=googFileObject.selfLink,Q($.get(reqUrl,{alt:"media",key:apiKey}))):Q($.ajax("/shared-program-contents?sharedProgramId="+googFileObject.id,{method:"get",dataType:"text"}))},getName:function(){return googFileObject.title},getModifiedTime:function(){return googFileObject.modifiedDate},getUniqueId:function(){return googFileObject.id}}}function makeFile(googFileObject,mimeType,fileExtension){return{shared:!1,getName:function(){return googFileObject.title},getModifiedTime:function(){return googFileObject.modifiedDate},getUniqueId:function(){return googFileObject.id},getExternalURL:function(){return googFileObject.alternateLink},getShares:function(){return drive.files.list({q:"trashed=false and properties has {key='"+BACKREF_KEY+"' and value='"+googFileObject.id+"' and visibility='PRIVATE'}"}).then(function(files){return files.items?files.items.map(fileBuilder):[]})},getContents:function(){var baseUrl="https://www.googleapis.com/drive/v3/files/"+googFileObject.id+"?alt=media&source=download";return Q($.ajax(baseUrl,{method:"get",dataType:"text",headers:{Authorization:"Bearer "+gapi.auth.getToken().access_token}})).then(function(response){return response})},rename:function(newName){return drive.files.update({fileId:googFileObject.id,resource:{title:newName}}).then(fileBuilder)},makeShareCopy:function(){return shareCollection.then(function(c){return Q($.ajax({url:"/create-shared-program",method:"post",data:{fileId:googFileObject.id,title:googFileObject.title,collectionId:c.id}}))}).then(fileBuilder)},save:function(contents,newRevision){var boundary="-------314159265358979323846",delimiter="\r\n--"+boundary+"\r\n",delimiter=delimiter+"Content-Type: application/json\r\n\r\n"+JSON.stringify({mimeType:mimeType,fileExtension:fileExtension})+delimiter+"Content-Type: text/plain\r\n\r\n"+contents+"\r\n---------314159265358979323846--";return gwrap.request({path:"/upload/drive/v2/files/"+googFileObject.id,method:"PUT",params:{uploadType:"multipart"},headers:{"Content-Type":'multipart/mixed; boundary="'+boundary+'"'},body:delimiter}).then(fileBuilder)},_googObj:googFileObject}}function fileBuilder(googFileObject){return"text/plain"===googFileObject.mimeType&&!googFileObject.fileExtension||"arr"===googFileObject.fileExtension?makeFile(googFileObject,"text/plain","arr"):makeFile(googFileObject,googFileObject.mimeType,googFileObject.fileExtension)}var shareCollectionQ,cacheCollectionQ,shareCollection,api={getCollectionLink:function(){return baseCollection.then(function(bc){return"https://drive.google.com/drive/u/0/folders/"+bc.id})},getCollectionFolderId:function(){return baseCollection.then(function(bc){return bc.id})},getFileById:function(id){return drive.files.get({fileId:id}).then(fileBuilder)},makeUrlFile:function(url){return makeUrlFile(url)},getFileByName:function(name){return this.getAllFiles().then(function(files){return files.filter(function(f){return f.getName()===name})})},getCachedFileByName:function(name){return this.getCachedFiles().then(function(files){return files.filter(function(f){return f.getName()===name})})},getSharedFileById:function(id){var fromServer=(fromDriveQ=publicOnly?((fromDriveQ=Q.defer()).reject("No shared files directly from client with publicOnly=true"),fromDriveQ.promise):drive.files.get({fileId:id},!0).then(function(googFileObject){return makeSharedFile(googFileObject,!0)})).fail(function(){return Q($.get("/shared-file",{sharedProgramId:id})).then(function(googlishFileObject){return makeSharedFile(googlishFileObject,!1)})}),fromDriveQ=Q.any([fromDriveQ,fromServer]);return fromDriveQ.then(function(r){console.log("Got result for shared file: ",r)},function(r){console.log("Got failure: ",r)}),fromDriveQ},getFiles:function(c){return c.then(function(bc){return drive.files.list({q:"trashed=false and '"+bc.id+"' in parents"}).then(function(filesResult){return filesResult.items?filesResult.items.map(fileBuilder):[]})})},getCachedFiles:function(){return this.getFiles(cacheCollection)},getAllFiles:function(){return this.getFiles(baseCollection)},createFile:function(name,opts){var mimeType=(opts=opts||{}).mimeType||"text/plain",fileExtension=opts.fileExtension||"arr";return(opts.saveInCache?cacheCollection:baseCollection).then(function(bc){bc={path:"/drive/v2/files",method:"POST",params:opts.params||{},body:{parents:[{id:bc.id}],mimeType:mimeType,title:name}};return!1!==opts.fileExtension&&(bc.body.fileExtension=fileExtension),gwrap.request(bc).then(fileBuilder)})},checkLogin:function(){return collection.then(function(){return!0})}},cacheCollection=publicOnly?(shareCollectionQ=Q.defer(),cacheCollectionQ=Q.defer(),shareCollectionQ.reject("No share collection with publicOnly=true"),cacheCollectionQ.reject("No cache collection with publicOnly=true"),shareCollection=shareCollectionQ.promise,cacheCollectionQ.promise):(shareCollection=findOrCreateDirectory(collectionName+".shared"),findOrCreateDirectory(collectionName+".compiled"));return{api:api,collection:baseCollection,cacheCollection:cacheCollection,shareCollection:shareCollection,reinitialize:function(){return Q.fcall(function(){return initialize(drive)})}}}function findOrCreateDirectory(name){return drive.files.list({q:"('me' in owners) and trashed=false and title='"+name+"' and mimeType='"+FOLDER_MIME+"'"}).then(function(files){return files.items&&0<files.items.length?files.items[0]:drive.files.insert({resource:{mimeType:FOLDER_MIME,title:name}})})}function initialize(wrappedDrive){return drive=wrappedDrive,createAPI(publicOnly?((wrappedDrive=Q.defer()).reject("No base collection with publicOnly=true"),wrappedDrive.promise):findOrCreateDirectory(collectionName))}var ret=Q.defer();return gwrap.load({name:"drive",version:"v2",reauth:{immediate:immediate,publicOnly:publicOnly},callback:function(drive){ret.resolve(initialize(drive))}}),ret.promise},FilePicker.prototype.init=function(picker){this.open=this.initOpen(picker)},FilePicker.prototype.initOpen=function(picker){var validateSelection=function(sel){if(0===sel.length)this.onInternalError("Internal Error (please report to developers): Should be impossible: Picker selection length is zero");else{var firstType=sel[0][picker.Document.TYPE];switch(sel.forEach(function(f){f[picker.Document.TYPE]!==firstType&&this.onError("Cannot open files of multiple types (Expected: "+firstType+"; Received: "+f[picker.Document.TYPE]+")")}.bind(this)),sel[0][picker.Document.TYPE]){case"file":break;case picker.Type.PHOTO:sel.forEach(function(photo){photo=photo[picker.Document.ID];Q($.ajax({url:"/share-image",method:"post",data:{fileId:photo}})).fail(this.onInternalError)}.bind(this));break;default:this.onError("Cannot open file of unknown type: "+sel[0][picker.Document.TYPE])}}}.bind(this),pickerCallback=function(data){var selection;data[picker.Response.ACTION]==picker.Action.PICKED&&(selection=data[picker.Response.DOCUMENTS],validateSelection(selection),storageAPI.then(function(drive){this.dataHandler(selection,picker,drive)}.bind(this)))}.bind(this),showPicker=function(drive,views,title){var pyretView=new picker.DocsView(picker.ViewId.DOCUMENTS),imageView=new picker.View(picker.ViewId.DOCS),allViews=(imageView.setMimeTypes("image/png,image/jpeg,image/jpg,image/gif,image/webp"),{imageView:imageView,pyretView:pyretView}),imageView=function(parentId){pyretView.setParent(parentId);for(var pickerBuilder=(new picker.PickerBuilder).enableFeature(picker.Feature.MULTISELECT_ENABLED).setTitle(title),i=0;i<views.length;i+=1)pickerBuilder.addView(allViews[views[i]]);this.pickerInstance=pickerBuilder.setOAuthToken(gapi.auth.getToken().access_token).setDeveloperKey(apiKey).setAppId(appId).setCallback(pickerCallback).build(),this.pickerInstance.setVisible(!0),$(".picker").css("z-index",9e3);var hidePicker=function(e){27===e.which&&($(".picker").remove(),$(document).unbind("keydown",hidePicker))};$(document).on("keydown",hidePicker)}.bind(this);return drive.getCollectionFolderId().then(imageView)}.bind(this);return function(){this.raisedError=!1;var views=this.options.views||[],title=this.options.title||"Select a file";return storageAPI.then(function(drive){return gwrap.withAuth(function(){return showPicker(drive,views,title)})}).catch(function(err){if(this.raisedError)throw err;err&&err.message?this.onInternalError(err.message):this.onInternalError(err)}.bind(this))}.bind(this)},FilePicker.prototype.openOn=function(elt,evt){elt.addEventListener(evt,this.open.bind(this))};var storageAPIDeferred=Q.defer(),sheetsAPIDeferred=Q.defer();window.storageAPI=storageAPIDeferred.promise,window.sheetsAPI=sheetsAPIDeferred.promise,window.handleClientLoad=function(apiKey,publicOnly){window.gapi&&window.gapi.client?(gapi.client.setApiKey(apiKey),(apiKey=createProgramCollectionAPI("code.pyret.org",!0,publicOnly)).then(function(api){storageAPIDeferred.resolve(api);api=createSheetsAPI(!0);api.then(function(sheetsAPI){sheetsAPIDeferred.resolve(sheetsAPI)}),api.fail(function(err){sheetsAPIDeferred.reject(err)})}),apiKey.fail(function(err){storageAPIDeferred.reject(err),sheetsAPIDeferred.reject(err),console.log("Not logged in; proceeding without login info",err)})):(storageAPIDeferred.reject("no gapi.client"),sheetsAPIDeferred.reject("no gapi.client"),console.log("Not logged in; proceeding without login info"))};
|